Skip to content

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

Rust

feat(multiuser): scope handoffs and sessions to their owner

Djalma Júnior2d7b325eafdc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4f13b8ff..cc9f04f3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -31,6 +31,105 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
exist", so a trusted-proxy deployment — which never writes a `users` row —
gets root-only admin gating instead of waving every proxied caller through
the single-operator escape hatch (#333).
+- Handoffs now belong to the operator that created them (migration V39). On a
+ server shared by several people the open-handoff lookup was scoped by
+ `(workspace, project, state)` alone, so the next session to start — whoever it
+ belonged to — consumed the pending baton, and delivery is destructive, so the
+ author simply lost it. `cwd` did not help: a handoff created through
+ `memory_handoff_begin` is always manual (`from_session_id = NULL`), and manual
+ handoffs bypass the cwd check and outrank automatic ones, so the deliberate
+ artefact was exactly the one that crossed operators. Ownership is now checked
+ before those rules, and the owner column holds the qualified
+ `IdentityKey::storage_key()` TEXT. `memory_handoff_begin` gains `shared: true`
+ to publish a baton to the whole project on purpose; `memory_handoff_accept`
+ gains `any_owner: true` for recovery. A NULL owner still means "shared", so
+ every stored row and every caller without an authenticated actor behaves
+ exactly as before (#310).
+- Sessions record their operator (migration V40), and the open-session lookup
+ behind `GET /admin/open-sessions` is scoped to the caller unless
+ `all_owners=true`. `finalize-session` drives off that lookup and acts
+ destructively on the result — ending the session, synthesising a page from its
+ observations and minting a handoff carrying its raw prompts — so picking "the
+ newest open session in the scope" could do all of that to a colleague's live
+ session. The new `--all-owners` flag exposes the server switch (#310).
+- New `GET /api/v1/workspaces/{workspace}/projects/{project}/handoffs` lists a
+ project's handoffs, filtered by `state` and scoped by owner, backed by a new
+ non-partial index (migration V41) since every pre-existing handoffs index is
+ partial on `state = 'open'`. There was no handoff listing anywhere in the
+ system: readers only ever fetched the single pending one and consumed it, so a
+ mis-delivered baton could not be inspected or recovered. On a server that
+ authenticates, the prompt-derived fields (`summary`, `open_questions`,
+ `next_steps`) are served to a caller the server can name and to the root
+ operator, and are omitted with `redacted: true` for a caller it can place as
+ neither — unowned rows are shared, so such a caller matches every one of them,
+ and unlike the overview's single newest card this returns the project's whole
+ history. Cross-owner reads are root-only. The metadata is served either way,
+ which is what makes the listing useful; a server with no auth configured
+ serves the bodies too, since it already serves every page body
+ unauthenticated (#310).
+- New admission-chain operations `handoff_begin`, `handoff_accept` and
+ `handoff_cancel`. Handoffs live in their own table, so their lifecycle never
+ passed through `Wiki::write_page` and was invisible to admission webhooks —
+ leaving the operations that move prompt-derived text between operators
+ unauthorizable. Every path raising one of them asks and announces in the same
+ order: only the webhooks that can refuse (blocking + reject policy) are
+ awaited before the operation, and observers are dispatched fire-and-forget
+ after it, only if it happened — so `memory_handoff_accept`, whose routine
+ answer is `{"handoff": null}`, never announces an accept that found nothing,
+ and a mirror is never told about a baton the engine then abandoned. The
+ automatic SessionEnd handoff and the session-start claim run through the same
+ chain as their operator-triggered counterparts, forwarding the caller's
+ webhook skip-list under the same root-only rule as every other transport.
+ Neither can cost an operator anything beyond the operation the webhook
+ declined: SessionEnd still writes the summary page, runs the opt-in
+ consolidation and commits (a refusal skips the baton and is logged), and a
+ refused, timed-out or unreachable claim leaves the handoff open for the next
+ session (#310).
+
+### Fixed
+- Handoff and session ownership is stamped only where the deployment actually
+ distinguishes operators. A server with `[auth].bearer_token` +
+ `[auth].root_username`, no `users` rows and no proxy has one operator and two
+ transports: stamping that one name on every HTTP write while the stdio /
+ in-process transport carries no actor would make one person's handoffs and
+ sessions invisible to their own other transport on the same data directory.
+ With nobody to separate, the stamp is the pre-ownership `NULL` and both
+ transports agree. Reads are deliberately not gated the same way, so rows
+ stamped while a deployment did distinguish operators stay readable by that
+ operator afterwards (#310).
+- The automatic SessionEnd handoff, the session page and both consolidation
+ paths attribute to the operator recorded on the **session**, not to whoever
+ delivered the event — a spool drain, a shared hook token or an operator
+ finalizing a stuck session all carry a different identity (#310).
+- Briefings and both read-only overviews — workspace and project — scope
+ handoffs to the requesting actor instead of showing only unowned ones, and
+ `pending_handoff_count` applies the same filter as the fetch — otherwise a
+ briefing advertises a pending baton the same caller can never retrieve, and on
+ any server that stamps owners the overview's handoff card would go permanently
+ empty while the count beside it kept reporting the row. The read-only
+ `/api/v1` overview no longer surfaces handoffs that belong to a specific
+ operator, including the raw prompt text an automatic handoff is synthesised
+ from, to a browser the server cannot attribute (#310).
+- Retiring superseded automatic handoffs no longer crosses an operator
+ boundary. Both sweeps — the same-cwd expiry on a new SessionEnd handoff and
+ the post-claim cleanup after an accept — match on the acting handoff's
+ `owner_user`, so one person starting or ending a session in a directory
+ cannot expire another person's pending baton. A shared handoff (no owner) is
+ visible to everyone, so it is only ever superseded by another shared one; on
+ a single-operator or unauthenticated server every row is unowned and the
+ sweeps behave exactly as they did (#310).
+- `ops::accept_handoff` propagates whether the claim actually succeeded, so
+ `memory_handoff_accept` no longer returns the handoff body when the atomic
+ claim was lost — previously two agents could be handed the same baton. The
+ cross-operator escape hatches require admin authority: `any_owner` on
+ `memory_handoff_accept` and on `memory_handoff_cancel` (which previously had
+ no recovery path at all, so a handoff whose owner no longer matched any
+ reachable identity could not be discarded), and `--all-owners` on
+ `ai-memory finalize-session` (#310).
+- The `[auto_scope] per_actor` active-project map is keyed by the qualified
+ identity on both sides — the hook ingress that publishes and the MCP tools
+ that read — so a sub-only proxied operator's writes and reads land on the
+ same slot instead of silently missing on every read (#310).
## [1.21.0] - 2026-07-31
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index ec8513b3..7ab8a213 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -1012,6 +1012,13 @@ pub struct FinalizeSessionArgs {
/// Project name. When omitted, auto-derived from the current project.
#[arg(long)]
pub project: Option<String>,
+ /// Finalize sessions belonging to OTHER operators too.
+ ///
+ /// By default only your own (and unattributed) sessions are considered, so
+ /// finalizing cannot end a colleague's live session. Use this to recover a
+ /// teammate's session that died without emitting SessionEnd.
+ #[arg(long, default_value_t = false)]
+ pub all_owners: bool,
/// Finalize every matching open session instead of just the latest one.
#[arg(long)]
pub all: bool,
diff --git a/crates/ai-memory-cli/src/commands/finalize_session.rs b/crates/ai-memory-cli/src/commands/finalize_session.rs
index c79e07ce..93347679 100644
--- a/crates/ai-memory-cli/src/commands/finalize_session.rs
+++ b/crates/ai-memory-cli/src/commands/finalize_session.rs
@@ -56,7 +56,15 @@ pub async fn run(config: &Config, args: FinalizeSessionArgs) -> Result<()> {
let (workspace, project) =
super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
- let sessions = fetch_open_sessions(&endpoint, &workspace, &project, agent, args.all).await?;
+ let sessions = fetch_open_sessions(
+ &endpoint,
+ &workspace,
+ &project,
+ agent,
+ args.all,
+ args.all_owners,
+ )
+ .await?;
if sessions.is_empty() {
return print_report(args, workspace, project, agent, Vec::new());
}
@@ -91,8 +99,10 @@ async fn fetch_open_sessions(
project: &str,
agent: AgentKind,
all: bool,
+ all_owners: bool,
) -> Result<Vec<OpenSessionEntry>> {
let all = if all { "true" } else { "false" };
+ let all_owners = if all_owners { "true" } else { "false" };
let result = get_json::<OpenSessionsResponse>(
endpoint,
"/admin/open-sessions",
@@ -101,6 +111,7 @@ async fn fetch_open_sessions(
("project", project),
("agent", agent.as_str()),
("all", all),
+ ("all_owners", all_owners),
],
)
.await;
@@ -269,6 +280,7 @@ mod tests {
project_id,
agent_kind: agent,
cwd: Some(std::path::PathBuf::from("/tmp/target")),
+ actor_user: None,
})
.await
.unwrap();
@@ -276,7 +288,13 @@ mod tests {
let selected = store
.reader
- .open_sessions_for_scope_agent(ws, target, AgentKind::AntigravityCli, Some(1))
+ .open_sessions_for_scope_agent(
+ ws,
+ target,
+ AgentKind::AntigravityCli,
+ ai_memory_core::OwnerFilter::Any,
+ Some(1),
+ )
.await
.unwrap();
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index a26cec0e..3ba4483e 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -593,6 +593,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
),
)),
home_dir: config.home_dir.clone(),
+ trusted_proxy_identity: trusted_proxy_identity_enabled(&config.auth),
});
let workstreams = workstream_router(WorkstreamState {
writer: store.writer.clone(),
@@ -2128,6 +2129,7 @@ mod tests {
project_id,
agent_kind: AgentKind::Codex,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
diff --git a/crates/ai-memory-consolidate/src/auto_improve.rs b/crates/ai-memory-consolidate/src/auto_improve.rs
index 6298ab95..d95aef2d 100644
--- a/crates/ai-memory-consolidate/src/auto_improve.rs
+++ b/crates/ai-memory-consolidate/src/auto_improve.rs
@@ -432,7 +432,13 @@ pub async fn run_auto_improve_review(
}
let briefing = reader
- .briefing_for_project(workspace_id, project_id, 100)
+ .briefing_for_project(
+ workspace_id,
+ project_id,
+ 100,
+ // Internal review pass: the pending-handoff count is not surfaced.
+ ai_memory_core::OwnerFilter::Any,
+ )
.await?;
let session_page_path = format!("sessions/{session_id}.md");
let session_page = reader
@@ -2212,6 +2218,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::Other,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
diff --git a/crates/ai-memory-consolidate/src/auto_improve_schedule.rs b/crates/ai-memory-consolidate/src/auto_improve_schedule.rs
index dcf3590c..849f1154 100644
--- a/crates/ai-memory-consolidate/src/auto_improve_schedule.rs
+++ b/crates/ai-memory-consolidate/src/auto_improve_schedule.rs
@@ -481,6 +481,7 @@ mod tests {
project_id,
agent_kind: AgentKind::OpenCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -510,6 +511,7 @@ mod tests {
project_id,
agent_kind: AgentKind::OpenCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
diff --git a/crates/ai-memory-consolidate/src/consolidator.rs b/crates/ai-memory-consolidate/src/consolidator.rs
index a125770f..3fdf4630 100644
--- a/crates/ai-memory-consolidate/src/consolidator.rs
+++ b/crates/ai-memory-consolidate/src/consolidator.rs
@@ -346,7 +346,14 @@ impl Consolidator {
) -> ConsolidatorResult<Vec<SlotSnapshot>> {
let briefing = self
.reader
- .briefing_for_project(workspace_id, project_id, 100)
+ .briefing_for_project(
+ workspace_id,
+ project_id,
+ 100,
+ // Internal slot snapshot: the pending-handoff count is not
+ // surfaced from here, so no owner scoping applies.
+ ai_memory_core::OwnerFilter::Any,
+ )
.await?;
let mut slots = Vec::with_capacity(briefing.slots.len());
for slot in briefing.slots {
diff --git a/crates/ai-memory-consolidate/tests/recall_eval.rs b/crates/ai-memory-consolidate/tests/recall_eval.rs
index 725f30a3..46b823e4 100644
--- a/crates/ai-memory-consolidate/tests/recall_eval.rs
+++ b/crates/ai-memory-consolidate/tests/recall_eval.rs
@@ -353,6 +353,7 @@ async fn raw_observation_fallback_recovers_detail_when_wiki_misses() {
project_id: proj,
agent_kind: AgentKind::OpenCode,
cwd: None,
+ actor_user: None,
})
.await
.expect("begin session");
diff --git a/crates/ai-memory-core/src/actor.rs b/crates/ai-memory-core/src/actor.rs
index 516127c9..596d3d9b 100644
--- a/crates/ai-memory-core/src/actor.rs
+++ b/crates/ai-memory-core/src/actor.rs
@@ -351,6 +351,47 @@ impl IdentityKey {
}
}
+ /// Inverse of [`Self::storage_key`], for reading a stored owner back into
+ /// the typed key.
+ ///
+ /// Rows persist the qualified TEXT form, and some paths must later act *as*
+ /// the operator that TEXT names — a SessionEnd delivered by a spool drain
+ /// attributes the session page to the session's recorded owner, not to
+ /// whoever flushed the event. Re-wrapping the stored string in a fresh
+ /// [`IdentityKey`] would double-qualify it (`user:sub:…`), so the parse
+ /// lives here, next to the encoding it inverts. `None` means the TEXT is
+ /// not a storage key at all — nothing this contract wrote.
+ #[must_use]
+ pub fn from_storage_key(key: &str) -> Option<Self> {
+ key.strip_prefix("sub:")
+ .map(|sub| Self::Subject(sub.to_owned()))
+ .or_else(|| {
+ key.strip_prefix("user:")
+ .map(|user| Self::User(user.to_owned()))
+ })
+ }
+
+ /// The [`ActorContext`] this key names — `Subject` fills `sub`, `User`
+ /// fills `user` — so [`ActorContext::identity_key`] round-trips to `self`.
+ ///
+ /// For paths that act on a STORED owner (see [`Self::from_storage_key`])
+ /// and need to hand downstream code a real actor: stuffing the qualified
+ /// storage TEXT into `ActorContext::user` instead would present a subject
+ /// as a username and re-derive a different identity.
+ #[must_use]
+ pub fn to_actor_context(&self) -> ActorContext {
+ match self {
+ Self::Subject(sub) => ActorContext {
+ sub: Some(sub.clone()),
+ ..ActorContext::default()
+ },
+ Self::User(user) => ActorContext {
+ user: Some(user.clone()),
+ ..ActorContext::default()
+ },
+ }
+ }
+
/// A filesystem-safe, injective encoding for per-operator wiki paths
/// (`_slots/<segment>/…`).
///
@@ -649,6 +690,34 @@ mod tests {
assert!(!names_filter.admits(Some(&by_subject.storage_key())));
}
+ /// Storage keys must read back as the identity that wrote them — including
+ /// a subject that CONTAINS a colon (URLs are common subjects) — and a
+ /// stored value this contract never produced must parse to nobody rather
+ /// than to a guessed operator.
+ #[test]
+ fn storage_key_round_trips_through_from_storage_key() {
+ for key in [
+ IdentityKey::User("alice".into()),
+ IdentityKey::Subject("oidc-subject-123".into()),
+ IdentityKey::Subject("https://idp.example/id/42".into()),
+ // The aliasing case: a username that LOOKS like a subject key must
+ // come back as the username it is.
+ IdentityKey::User("sub:alice".into()),
+ ] {
+ assert_eq!(
+ IdentityKey::from_storage_key(&key.storage_key()).as_ref(),
+ Some(&key)
+ );
+ assert_eq!(
+ key.to_actor_context().identity_key().as_ref(),
+ Some(&key),
+ "to_actor_context must name the same operator"
+ );
+ }
+ assert_eq!(IdentityKey::from_storage_key("alice"), None);
+ assert_eq!(IdentityKey::from_storage_key(""), None);
+ }
+
/// Subjects are IdP-issued and often URLs; wiki paths are real files on
/// every platform. Path-hostile values hex-encode under a DISTINCT prefix
/// so a passthrough value that merely looks like hex cannot collide with
diff --git a/crates/ai-memory-core/src/handoff.rs b/crates/ai-memory-core/src/handoff.rs
index 268de0e4..0dafb72b 100644
--- a/crates/ai-memory-core/src/handoff.rs
+++ b/crates/ai-memory-core/src/handoff.rs
@@ -76,6 +76,12 @@ pub struct NewHandoff {
pub next_steps: Vec<String>,
/// Files touched in the session.
pub files_touched: Vec<String>,
+ /// Operator this handoff belongs to, as an
+ /// [`crate::IdentityKey::storage_key`] string. `None` publishes it to the
+ /// whole project (the pre-ownership behaviour, and what a caller with no
+ /// actor produces).
+ #[serde(default)]
+ pub owner_user: Option<String>,
}
/// Materialised view of a handoff row.
@@ -113,4 +119,10 @@ pub struct Handoff {
pub accepted_at: Option<Timestamp>,
/// Session that accepted, if any.
pub accepted_by_session: Option<SessionId>,
+ /// Operator this handoff belongs to ([`crate::IdentityKey::storage_key`]
+ /// form); `None` means shared with the project.
+ pub owner_user: Option<String>,
+ /// Operator that accepted it. Unlike [`Handoff::accepted_by`] (the agent
+ /// CLI), this answers "which teammate took the baton".
+ pub accepted_by_user: Option<String>,
}
diff --git a/crates/ai-memory-core/src/observation.rs b/crates/ai-memory-core/src/observation.rs
index c45ceef3..1b4bd031 100644
--- a/crates/ai-memory-core/src/observation.rs
+++ b/crates/ai-memory-core/src/observation.rs
@@ -148,6 +148,12 @@ pub struct NewSession {
pub agent_kind: AgentKind,
/// Working directory at session start.
pub cwd: Option<PathBuf>,
+ /// Operator this session belongs to, as an
+ /// [`crate::IdentityKey::storage_key`] string. `None` (no authenticated
+ /// actor, or a deployment that does not distinguish operators) keeps the
+ /// session shared, which is the single-operator behaviour.
+ #[serde(default)]
+ pub actor_user: Option<String>,
}
#[cfg(test)]
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index ee29d966..7356d686 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -14,7 +14,7 @@ use std::sync::{Arc, Weak};
use ai_memory_consolidate::Consolidator;
use ai_memory_core::{
- ActiveProject, ActorKey, AgentKind, DEFAULT_WORKSPACE_NAME, Handoff,
+ ActiveProject, ActorKey, AgentKind, DEFAULT_WORKSPACE_NAME, Handoff, IdentityKey,
MANAGED_WORKSTREAM_PACKET_MARKER, ManagedRunId, NewHandoff, NewObservation, NewSession,
ObservationKind, ProjectId, Sanitized, Sanitizer, SessionId, WorkspaceId, WorkstreamEvent,
WorkstreamEventKind,
@@ -24,7 +24,7 @@ use ai_memory_wiki::Wiki;
use axum::Json;
use axum::Router;
use axum::extract::{Query, State};
-use axum::http::StatusCode;
+use axum::http::{HeaderMap, StatusCode};
use axum::response::IntoResponse;
use axum::routing::{get, post};
use jiff::Timestamp;
@@ -474,6 +474,85 @@ pub struct HookState {
/// to this, so `$HOME` cannot become a catch-all (issue #103). `None`
/// disables the guard. Held here so the hooks crate makes no env reads.
pub home_dir: Option<String>,
+ /// `[auth].actor_proxy_secret` + `[auth].bearer_token`: can a trusted proxy
+ /// assert identities on this server?
+ ///
+ /// Half of "does this deployment distinguish operators" — the other half
+ /// (`users` rows) is a store read. A proxied deployment never writes a
+ /// `users` row, so counting only rows would report a multi-operator server
+ /// as single-operator forever. Held here because the hooks crate makes no
+ /// config reads.
+ pub trusted_proxy_identity: bool,
+}
+
+/// The owner to stamp on the session and handoff rows this event creates
+/// ([`ai_memory_core::IdentityKey::storage_key`] TEXT).
+///
+/// One rule, one place: the stamp is `None` unless the deployment actually
+/// tells its operators apart, because a single-operator server whose HTTP
+/// requests carry `[auth].root_username` would otherwise write rows that the
+/// SAME operator's stdio / in-process transport — which carries no actor —
+/// cannot see. See [`ai_memory_core::owner_stamp`].
+///
+/// The topology is asked per event rather than cached, exactly as the admin
+/// gates ask it, so committing a first user starts bucketing without a restart.
+/// A request that names nobody short-circuits before the store, so an
+/// unauthenticated server pays nothing.
+async fn owner_stamp_for_event(
+ state: &HookState,
+ identity: Option<&IdentityKey>,
+) -> Option<String> {
+ let identity = identity?;
+ let distinguishes = match state
+ .reader
+ .distinguishes_operators(state.trusted_proxy_identity)
+ .await
+ {
+ Ok(distinguishes) => distinguishes,
+ // Toward bucketing, not away from it: a row wrongly left shared is
+ // readable by every operator on the server and cannot be un-shared
+ // afterwards, while a row wrongly stamped is still reachable through
+ // the `any_owner` / `all_owners` recovery switches.
+ Err(e) => {
+ warn!(error = %e, "operator-topology lookup failed; stamping this row per operator");
+ true
+ }
+ };
+ ai_memory_core::owner_stamp(Some(identity), distinguishes)
+}
+
+/// The human this request names, if any — as the typed [`IdentityKey`].
+///
+/// [`ai_memory_core::ActorContext::identity_key`] rather than `ctx.user`, so
+/// the ingress that forwards only an OIDC subject claim is identified here in
+/// the same way the auth middleware already treats it — reading `user` alone
+/// would file every operator behind such a proxy as anonymous and hand them all
+/// one shared bucket.
+fn actor_identity(
+ actor: Option<axum::Extension<ai_memory_core::ActorContext>>,
+) -> Option<IdentityKey> {
+ actor.and_then(|axum::Extension(ctx)| ctx.identity_key())
+}
+
+/// Webhook names this request opted out of, read from the
+/// `X-Memory-Skip-Admission-Chain` header.
+///
+/// The hook ingress runs the admission chain for the two ops that carry no
+/// page — `HandoffBegin` on SessionEnd, `HandoffAccept` on session start — so a
+/// webhook that reacts to one of them by calling back in through a hook has to
+/// be able to exclude itself here, exactly as it can on the MCP and admin
+/// paths. Gating is the shared core rule: the header is client-controlled, so a
+/// regular DB user must not use it to walk past a reject-policy webhook.
+fn admission_skips(
+ level: Option<axum::Extension<ai_memory_core::AuthLevel>>,
+ headers: &HeaderMap,
+) -> Vec<String> {
+ ai_memory_core::skip_admission_chain_for(
+ level.map_or(ai_memory_core::AuthLevel::Anonymous, |ext| ext.0),
+ headers
+ .get(ai_memory_core::SKIP_ADMISSION_CHAIN_HEADER)
+ .and_then(|value| value.to_str().ok()),
+ )
}
/// Build a router with `POST /hook` (event ingress) and `GET /handoff`
@@ -490,6 +569,8 @@ async fn handle_hook(
State(state): State<Arc<HookState>>,
Query(query): Query<HookQuery>,
actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,
+ level_ext: Option<axum::Extension<ai_memory_core::AuthLevel>>,
+ headers: HeaderMap,
Json(mut body): Json<serde_json::Value>,
) -> impl IntoResponse {
// Unconditional backstop (#196): drop any raw assistant-message field on the
@@ -510,12 +591,14 @@ async fn handle_hook(
// it. Runs before the semaphore so a dropped event consumes no capacity.
// The auth middleware in front of `/hook` injects the request's
// [`ActorContext`] (rung 1 root, rung 2 DB user, or anonymous). We
- // capture its `user` field NOW — before the spawn drops the request
+ // capture the identity it names NOW — before the spawn drops the request
// extensions — so `process()` can key the `ActiveProject` map by the
// authenticated identity when `[auto_scope] mode = per_actor` is on.
- let actor_user = actor_ext
- .map(|axum::Extension(ctx)| ctx.user)
- .unwrap_or_default();
+ let actor = actor_identity(actor_ext);
+ // Same reason: the skip-list header is read here, while the request
+ // extensions still exist, and travels with the event into `process()`.
+ let skip_webhooks = admission_skips(level_ext, &headers);
+ let actor_user = actor.as_ref().map(IdentityKey::storage_key);
let actor_key = ActorKey {
user: actor_user.clone(),
session_id: env.session_id.clone(),
@@ -539,7 +622,7 @@ async fn handle_hook(
}
tokio::spawn(async move {
let _permit = permit;
- process_envelope(state, env, actor_user).await;
+ process_envelope(state, env, actor, skip_webhooks).await;
});
(StatusCode::ACCEPTED, "queued")
}
@@ -641,6 +724,8 @@ impl HookBatchAck {
async fn handle_hook_batch(
State(state): State<Arc<HookState>>,
actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,
+ level_ext: Option<axum::Extension<ai_memory_core::AuthLevel>>,
+ headers: HeaderMap,
Json(items): Json<Vec<HookBatchItem>>,
) -> impl IntoResponse {
if items.len() > MAX_HOOK_BATCH_ITEMS {
@@ -653,9 +738,9 @@ async fn handle_hook_batch(
}
// All items in a batch share the drain's single identity, so the actor is
// captured once from the batch request (mirrors `handle_hook`).
- let actor_user = actor_ext
- .map(|axum::Extension(ctx)| ctx.user)
- .unwrap_or_default();
+ let actor = actor_identity(actor_ext);
+ let skip_webhooks = admission_skips(level_ext, &headers);
+ let actor_user = actor.as_ref().map(IdentityKey::storage_key);
let mut accepted_indices = Vec::new();
for (idx, mut item) in items.into_iter().enumerate() {
// Same unconditional assistant-message backstop as `handle_hook`, applied
@@ -707,7 +792,7 @@ async fn handle_hook_batch(
continue;
}
let _permit = permit;
- if let Err(e) = process(&state, env, actor_user.clone()).await {
+ if let Err(e) = process(&state, env, actor.clone(), skip_webhooks.clone()).await {
warn!(error = %e, accepted = accepted_indices.len(), "hook batch item failed; stopping (fail-fast)");
return (
StatusCode::OK,
@@ -1068,11 +1153,12 @@ async fn handle_handoff(
State(state): State<Arc<HookState>>,
Query(query): Query<HandoffQuery>,
actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,
+ level_ext: Option<axum::Extension<ai_memory_core::AuthLevel>>,
+ headers: HeaderMap,
) -> impl IntoResponse {
- let actor_user = actor_ext
- .map(|axum::Extension(ctx)| ctx.user)
- .unwrap_or_default();
- match fetch_and_accept_handoff(&state, query, actor_user).await {
+ let actor = actor_identity(actor_ext);
+ let skip_webhooks = admission_skips(level_ext, &headers);
+ match fetch_and_accept_handoff(&state, query, actor, skip_webhooks).await {
Ok(Some(markdown)) => (StatusCode::OK, markdown),
Ok(None) => (StatusCode::OK, String::new()),
Err(e) => {
@@ -1085,7 +1171,8 @@ async fn handle_handoff(
async fn fetch_and_accept_handoff(
state: &HookState,
query: HandoffQuery,
- actor_user: Option<String>,
+ actor: Option<IdentityKey>,
+ skip_webhooks: Vec<String>,
) -> anyhow::Result<Option<String>> {
let agent = query.agent.as_deref().map_or(AgentKind::Other, parse_agent);
// A managed run's ledger is additive, not a replacement. Returning it here
@@ -1100,7 +1187,7 @@ async fn fetch_and_accept_handoff(
// therefore falls back to the single slot (graceful degradation),
// while `per_actor` keys by `user` alone.
let actor_key = ai_memory_core::ActorKey {
- user: actor_user,
+ user: actor.as_ref().map(IdentityKey::storage_key),
session_id: None,
};
let (ws, proj) = resolve_project_ids_inner(
@@ -1115,9 +1202,18 @@ async fn fetch_and_accept_handoff(
false,
)
.await?;
+ // The actor is what makes this lookup safe on a shared server: without it
+ // the newest open handoff in the project is returned to whoever starts a
+ // session next, and the claim below consumes it — so one operator's baton
+ // lands in another operator's context and is lost to its author. Handoffs
+ // with no owner stay project-wide, which is the single-operator behaviour.
+ let owner_filter = match &actor {
+ Some(key) => ai_memory_core::OwnerFilter::User(key.storage_key()),
+ None => ai_memory_core::OwnerFilter::Unattributed,
+ };
let handoff = state
.reader
- .latest_open_handoff(ws, proj, query.cwd.clone())
+ .latest_open_handoff(ws, proj, query.cwd.clone(), owner_filter.clone())
.await?;
let handoff_md = handoff.as_ref().map(render_handoff_markdown);
// The brief is additive and non-destructive: unlike the handoff (a
@@ -1129,6 +1225,52 @@ async fn fetch_and_accept_handoff(
// order is preserved. Claim both single-use inputs only after every
// fallible read and render has succeeded, and in one transaction so a
// failed or racing managed claim cannot consume the handoff by itself.
+ // Same reasoning as the SessionEnd insert: the session-start claim is how
+ // most handoffs are consumed, so a webhook must be able to see it. Two
+ // properties keep that policy call from costing the operator the baton:
+ //
+ // - Only a webhook the operator set to `reject` is waited for. This
+ // endpoint sits on the session-start hook path, whose script hard-timeouts
+ // at ≤200 ms (AGENTS.md invariant 5), and an ignore-policy webhook cannot
+ // refuse anything — waiting for one would spend that budget to learn
+ // nothing, and losing the baton to an observer's round trip is exactly the
+ // outcome admission on this path exists to avoid. Observers are notified
+ // below, off the critical path, once the claim is durable. What is left
+ // waiting is the SUM of the deciding webhooks' own `timeout_ms` — the
+ // chain awaits them one after another — each defaulting to 2 s: the budget
+ // is not enforced here, and `docs/admission-webhooks.md` tells the
+ // operator to lower them on every `reject` hook that subscribes to this
+ // op. Cutting it short instead would refuse a claim the webhook was
+ // about to admit, on the path where the baton is normally consumed.
+ // - A refusal (or a down reject-policy host, which a reject chain cannot
+ // tell apart) cancels only the CLAIM. The handoff stays open for the next
+ // session and the brief is still served, instead of the whole endpoint
+ // erroring out.
+ let (handoff, admission_ctx) = match handoff {
+ Some(pending) => {
+ let authorized = state
+ .wiki
+ .authorize_operation(
+ ws,
+ proj,
+ ai_memory_wiki::AdmissionOp::HandoffAccept,
+ actor
+ .as_ref()
+ .map(IdentityKey::to_actor_context)
+ .unwrap_or_default(),
+ skip_webhooks,
+ )
+ .await;
+ match authorized {
+ Ok(ctx) => (Some(pending), ctx),
+ Err(e) => {
+ warn!(error = %e, "handoff claim refused by admission chain; leaving it open");
+ (None, None)
+ }
+ }
+ }
+ None => (None, None),
+ };
let acceptance = if handoff.is_some() || managed.is_some() {
state
.writer
@@ -1136,6 +1278,8 @@ async fn fetch_and_accept_handoff(
handoff.as_ref().map(|handoff| handoff.id),
agent,
None,
+ actor.as_ref().map(IdentityKey::storage_key),
+ owner_filter,
managed.as_ref().map(|managed| managed.run_id),
query.cwd.clone(),
)
@@ -1144,6 +1288,13 @@ async fn fetch_and_accept_handoff(
ai_memory_store::StartupContextAcceptance::default()
};
let handoff_md = if acceptance.handoff_accepted {
+ // The claim is durable now, so the observers can be told about it. A
+ // racing session that won the row leaves `handoff_accepted` false, and
+ // then nothing is dispatched: a mirror is only ever told about a baton
+ // this request actually consumed.
+ if let Some(ctx) = &admission_ctx {
+ state.wiki.notify_operation_observers(ctx);
+ }
handoff_md
} else {
None
@@ -1892,8 +2043,13 @@ fn sticky_within_session_tree(
std::path::Path::new(&event_norm).starts_with(std::path::Path::new(&session_norm))
}
-async fn process_envelope(state: Arc<HookState>, env: HookEnvelope, actor_user: Option<String>) {
- if let Err(e) = process(&state, env, actor_user).await {
+async fn process_envelope(
+ state: Arc<HookState>,
+ env: HookEnvelope,
+ actor: Option<IdentityKey>,
+ skip_webhooks: Vec<String>,
+) {
+ if let Err(e) = process(&state, env, actor, skip_webhooks).await {
warn!(error = %e, "hook processing failed");
}
}
@@ -1930,20 +2086,23 @@ async fn enqueue_session_end_consolidation(
async fn process(
state: &HookState,
env: HookEnvelope,
- actor_user: Option<String>,
+ actor: Option<IdentityKey>,
+ // Admission webhooks this request opted out of (see `admission_skips`).
+ // Empty for every caller with no HTTP request behind it.
+ skip_webhooks: Vec<String>,
) -> anyhow::Result<()> {
let session_id = resolve_session_id(&env)?;
// Build the actor key used to scope the in-process `ActiveProject`
- // pointer. `user` is whatever the auth middleware extracted from this
- // request; `session_id` is the RAW string from the payload (NOT the
- // resolved UUID) — agents that forward an opaque session id over
- // `X-Memory-Actor-Session-Id` on /mcp pass the same raw string, so set
- // and get land on the same map slot. The MCP server's
+ // pointer. `user` is the qualified storage key of whatever identity the
+ // auth middleware extracted from this request; `session_id` is the RAW
+ // string from the payload (NOT the resolved UUID) — agents that forward an
+ // opaque session id over `X-Memory-Actor-Session-Id` on /mcp pass the same
+ // raw string, so set and get land on the same map slot. The MCP server's
// `actor_key_from_parts` mirrors this convention. Empty actor
// (anonymous + no session) is allowed — `set_for` falls back to the
// single slot.
let actor_key = ai_memory_core::ActorKey {
- user: actor_user.clone(),
+ user: actor.as_ref().map(IdentityKey::storage_key),
session_id: env.session_id.clone(),
};
// Session-sticky attribution: for an event whose session already
@@ -2068,12 +2227,20 @@ async fn process(
// session idempotently before every observation so a resumed agent
// session, or a prompt racing ahead of SessionStart, cannot trip the
// observations.session_id foreign key.
+ // Stamp the authenticated operator so anything that later picks "the open
+ // session for this scope" can tell whose it is — but only where operators
+ // are actually told apart. On an unauthenticated server, and on one that
+ // authenticates a single operator, this stays None and the session is
+ // shared, as before. The same value owns the SessionEnd handoff below, so
+ // the session and its baton can never disagree about who they belong to.
+ let owner_stamp = owner_stamp_for_event(state, actor.as_ref()).await;
let new_session = NewSession {
id: session_id,
workspace_id: ws,
project_id: proj,
agent_kind: env.agent,
cwd: env.cwd.as_ref().map(std::path::PathBuf::from),
+ actor_user: owner_stamp.clone(),
};
if let Err(e) = state.writer.begin_session(new_session).await {
// The cached (workspace, project) may have been deleted out from
@@ -2114,6 +2281,7 @@ async fn process(
project_id: proj,
agent_kind: env.agent,
cwd: env.cwd.as_ref().map(std::path::PathBuf::from),
+ actor_user: owner_stamp.clone(),
})
.await?;
}
@@ -2221,8 +2389,36 @@ async fn process(
HookEvent::PostCompaction => Some("post-compaction"),
_ => None,
};
+ // Whose session this is, as recorded at session start (a qualified
+ // storage key). Everything written on its behalf is attributed to them
+ // rather than to whoever delivered the event; falls back to the request
+ // actor when the row predates owner recording (or the lookup fails),
+ // which is the previous behaviour.
+ let session_owner: Option<IdentityKey> = match state.reader.session_actor_user(session_id).await
+ {
+ // A stored owner is always a storage key this branch wrote; a value
+ // that does not parse names nobody rather than a guessed operator.
+ Ok(Some(owner)) => IdentityKey::from_storage_key(&owner),
+ Ok(None) => actor.clone(),
+ Err(e) => {
+ warn!(error = %e, "session owner lookup failed; attributing to the request actor");
+ actor.clone()
+ }
+ };
+ let session_actor = session_owner
+ .as_ref()
+ .map(IdentityKey::to_actor_context)
+ .unwrap_or_default();
if let Some(checkpoint_label) = checkpoint_label
- && let Err(e) = consolidate_or_synth(state, session_id, ws, proj, checkpoint_label).await
+ && let Err(e) = consolidate_or_synth(
+ state,
+ session_id,
+ ws,
+ proj,
+ checkpoint_label,
+ session_actor.clone(),
+ )
+ .await
{
warn!(error = %e, "PreCompact/PostCompaction consolidation failed; continuing");
}
@@ -2245,28 +2441,100 @@ async fn process(
title: None,
admission_ctx: None,
author_id: None,
- actor: ai_memory_core::ActorContext::anonymous(),
+ // Attribute to the operator who OWNED the session, read back
+ // from the session row, not to whoever delivered this
+ // SessionEnd — a spool drain, an operator finalizing a stuck
+ // session, or a shared hook token can all carry a different
+ // identity. Falls back to the request actor for sessions that
+ // predate owner recording, and stays anonymous on a server
+ // without authentication.
+ actor: session_actor.clone(),
})
.await?;
- let handoff_id = if managed {
- state.writer.end_session(session_id, Some(page_id)).await?;
- None
- } else {
- let handoff = build_auto_handoff(
+ // The baton follows the SESSION's owner, so it reaches the person who
+ // was working, not whoever flushed the event. Run through the ownership
+ // gate again because `session_owner` above is an ATTRIBUTION value: it
+ // falls back to the request actor for sessions with no recorded owner,
+ // and a fallback name must not become an owner on a deployment that
+ // does not tell its operators apart — that is exactly the case where
+ // the baton would land in a bucket the operator's other transport
+ // cannot read.
+ let handoff_owner = owner_stamp_for_event(state, session_owner.as_ref()).await;
+ let handoff = (!managed).then(|| {
+ build_auto_handoff(
ws,
proj,
env.agent,
session_id,
env.cwd.clone(),
&observations,
- );
- Some(
+ handoff_owner,
+ )
+ });
+ // Automatic SessionEnd handoffs are the bulk of handoff traffic;
+ // skipping admission here would leave a webhook seeing only the
+ // MCP-initiated minority and silently not enforcing its policy.
+ //
+ // Asked BEFORE the write below, which commits and cannot be undone: a
+ // policy answer that arrives after it can only take the baton away
+ // from a session that no longer exists. And whatever the answer is, it
+ // never aborts the handler — a refusal (or a webhook host that is down
+ // or slow, which a reject policy cannot tell apart) skips the handoff
+ // and is logged, while the session page, the queued consolidation and
+ // the auto-commit below still run.
+ //
+ // Only the webhooks that can refuse are awaited here; the observers are
+ // told below, once the row exists, so a mirror is never announced a
+ // baton that a failed insert (or a refusal further down the chain)
+ // meant never happened. Same order as the session-start claim and the
+ // MCP tools that raise this op.
+ let (handoff, admission_ctx) = match handoff {
+ Some(handoff) => {
+ match state
+ .wiki
+ .authorize_operation(
+ ws,
+ proj,
+ ai_memory_wiki::AdmissionOp::HandoffBegin,
+ session_actor.clone(),
+ skip_webhooks,
+ )
+ .await
+ {
+ Ok(ctx) => (Some(handoff), ctx),
+ Err(e) => {
+ warn!(
+ session = %session_id,
+ error = %e,
+ "auto handoff refused by admission chain; session ends without a baton",
+ );
+ (None, None)
+ }
+ }
+ }
+ None => (None, None),
+ };
+ // The end stamp and the baton commit in one transaction: a crash
+ // between them would leave an ended session whose successor has
+ // nothing to pick up. A managed run and an admission refusal both take
+ // the second arm, ending the session with no handoff at all.
+ let handoff_id = match handoff {
+ Some(handoff) => Some(
state
.writer
.end_session_with_handoff(session_id, Some(page_id), handoff)
.await?,
- )
+ ),
+ None => {
+ state.writer.end_session(session_id, Some(page_id)).await?;
+ None
+ }
};
+ if handoff_id.is_some()
+ && let Some(ctx) = &admission_ctx
+ {
+ state.wiki.notify_operation_observers(ctx);
+ }
// Auto-commit the wiki tree so the session/handoff/log.md
// changes land in git in one atomic snapshot.
let commit_msg = format!(
@@ -2291,13 +2559,22 @@ async fn process(
handoff = %handoff_id,
"session ended; summary page + open handoff created",
);
- } else {
+ } else if managed {
info!(
session = %session_id,
page = %new_page.path,
managed_run = ?managed_run,
"managed session ended; summary page written without duplicate legacy handoff",
);
+ } else {
+ // Only reachable through the admission refusal above, which already
+ // warned with the reason; without this arm the refusal would be
+ // logged as a managed session end and hide why the baton is gone.
+ info!(
+ session = %session_id,
+ page = %new_page.path,
+ "session ended; summary page written without a handoff (admission refused)",
+ );
}
}
@@ -2332,6 +2609,7 @@ fn build_auto_handoff(
session_id: SessionId,
cwd: Option<String>,
observations: &[ai_memory_core::Observation],
+ owner_user: Option<String>,
) -> NewHandoff {
// Prefer obs.body (the full prompt) over obs.title (first-line +
// truncated to 80 chars for log/list display). When body is
@@ -2407,6 +2685,7 @@ fn build_auto_handoff(
open_questions,
next_steps,
files_touched: Vec::new(),
+ owner_user,
}
}
@@ -2419,16 +2698,16 @@ async fn consolidate_or_synth(
workspace_id: WorkspaceId,
project_id: ProjectId,
checkpoint_label: &str,
+ actor: ai_memory_core::ActorContext,
) -> anyhow::Result<()> {
if let Some(c) = state.consolidator.as_ref() {
let outcome = c
- .consolidate_session(
- session_id,
- false,
- ai_memory_core::ActorContext::anonymous(),
- None,
- None,
- )
+ // The hook path has no per-call override, so `None` lets the
+ // project's standing `_prompts/consolidation.md` preferences
+ // apply; the actor is the session's own operator so the
+ // checkpoint is attributed to them, not to whoever delivered
+ // the event.
+ .consolidate_session(session_id, false, actor.clone(), None, None)
.await?;
debug!(
session = %session_id,
@@ -2467,7 +2746,7 @@ async fn consolidate_or_synth(
title: None,
admission_ctx: None,
author_id: None,
- actor: ai_memory_core::ActorContext::anonymous(),
+ actor,
})
.await?;
let _ = state
@@ -2504,7 +2783,9 @@ const fn importance_for(event: HookEvent) -> u8 {
#[cfg(test)]
mod tests {
+ use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
+ use std::time::Duration;
use ai_memory_consolidate::{AutoImproveReviewConfig, run_auto_improve_review};
use ai_memory_core::{SanitizeConfig, Sanitizer};
@@ -2577,6 +2858,7 @@ mod tests {
subagent_sessions: Arc::new(tokio::sync::Mutex::new(SubagentSessionSet::default())),
ingest_rate: Arc::new(tokio::sync::Mutex::new(IngestRateLimiter::disabled())),
home_dir: None,
+ trusted_proxy_identity: false,
ingest_semaphore: Arc::new(tokio::sync::Semaphore::new(
DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT,
)),
@@ -2630,6 +2912,8 @@ mod tests {
accepted_by: None,
accepted_at: None,
accepted_by_session: None,
+ owner_user: None,
+ accepted_by_user: None,
};
let rendered = render_handoff_markdown(&handoff);
let warning = rendered
@@ -2875,12 +3159,22 @@ mod tests {
// Session starts at the parent; a later tool event reports the
// subdirectory cwd (agent shells keep their working directory).
- process(&state, fire("session-start", parent.clone()), None)
- .await
- .unwrap();
- process(&state, fire("post-tool-use", subdir.clone()), None)
- .await
- .unwrap();
+ process(
+ &state,
+ fire("session-start", parent.clone()),
+ None,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+ process(
+ &state,
+ fire("post-tool-use", subdir.clone()),
+ None,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
let parent_proj = state
.reader
@@ -2926,7 +3220,7 @@ mod tests {
"tool_name": "Bash",
}),
);
- process(&state, env, None).await.unwrap();
+ process(&state, env, None, Vec::new()).await.unwrap();
assert!(
state
.reader
@@ -2965,7 +3259,7 @@ mod tests {
)
};
- process(&state, fire("session-start", None), None)
+ process(&state, fire("session-start", None), None, Vec::new())
.await
.unwrap();
@@ -3004,6 +3298,7 @@ mod tests {
&state,
fire("user-prompt-submit", Some("entry-pending")),
None,
+ Vec::new(),
)
.await
.unwrap();
@@ -3023,6 +3318,7 @@ mod tests {
&state,
fire("user-prompt-submit", Some("entry-abc123")),
None,
+ Vec::new(),
)
.await
.unwrap();
@@ -3030,6 +3326,7 @@ mod tests {
&state,
fire("user-prompt-submit", Some("entry-abc123")),
None,
+ Vec::new(),
)
.await
.unwrap();
@@ -3038,14 +3335,15 @@ mod tests {
&state,
fire("user-prompt-submit", Some("entry-def456")),
None,
+ Vec::new(),
)
.await
.unwrap();
// Keyless events (older clients) keep at-least-once behavior.
- process(&state, fire("user-prompt-submit", None), None)
+ process(&state, fire("user-prompt-submit", None), None, Vec::new())
.await
.unwrap();
- process(&state, fire("user-prompt-submit", None), None)
+ process(&state, fire("user-prompt-submit", None), None, Vec::new())
.await
.unwrap();
@@ -3085,10 +3383,10 @@ mod tests {
)
};
- process(&state, fire("session-start", None), None)
+ process(&state, fire("session-start", None), None, Vec::new())
.await
.unwrap();
- process(&state, fire("user-prompt-submit", None), None)
+ process(&state, fire("user-prompt-submit", None), None, Vec::new())
.await
.unwrap();
let session_id: SessionId = sid.parse().unwrap();
@@ -3101,15 +3399,15 @@ mod tests {
let first = fire("session-end", Some("entry-session-end"));
let overlapping_retry = fire("session-end", Some("entry-session-end"));
let (first_result, retry_result) = tokio::join!(
- process(&state, first, None),
- process(&state, overlapping_retry, None)
+ process(&state, first, None, Vec::new()),
+ process(&state, overlapping_retry, None, Vec::new())
);
first_result.unwrap();
retry_result.unwrap();
let briefing = state
.reader
- .briefing_for_project(ws, proj, 1)
+ .briefing_for_project(ws, proj, 1, ai_memory_core::OwnerFilter::Any)
.await
.unwrap();
assert_eq!(
@@ -3285,6 +3583,8 @@ mod tests {
..Default::default()
}),
None,
+ None,
+ HeaderMap::new(),
Json(serde_json::json!({ "session_id": sid })),
)
.await
@@ -3319,6 +3619,8 @@ mod tests {
..Default::default()
}),
None,
+ None,
+ HeaderMap::new(),
Json(serde_json::json!({})),
)
.await
@@ -3345,6 +3647,8 @@ mod tests {
State(state.clone()),
Query(query.clone()),
None,
+ None,
+ HeaderMap::new(),
Json(body.clone()),
)
.await
@@ -3352,9 +3656,16 @@ mod tests {
assert_eq!(first.status(), StatusCode::TOO_MANY_REQUESTS);
state.ingest_semaphore.add_permits(1);
- let second = handle_hook(State(state), Query(query), None, Json(body))
- .await
- .into_response();
+ let second = handle_hook(
+ State(state),
+ Query(query),
+ None,
+ None,
+ HeaderMap::new(),
+ Json(body),
+ )
+ .await
+ .into_response();
assert_eq!(second.status(), StatusCode::ACCEPTED);
}
@@ -3375,9 +3686,15 @@ mod tests {
},
];
- let response = handle_hook_batch(State(Arc::new(state)), None, Json(items))
- .await
- .into_response();
+ let response = handle_hook_batch(
+ State(Arc::new(state)),
+ None,
+ None,
+ HeaderMap::new(),
+ Json(items),
+ )
+ .await
+ .into_response();
assert_eq!(response.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
@@ -3432,9 +3749,15 @@ mod tests {
},
];
- let response = handle_hook_batch(State(state.clone()), None, Json(items))
- .await
- .into_response();
+ let response = handle_hook_batch(
+ State(state.clone()),
+ None,
+ None,
+ HeaderMap::new(),
+ Json(items),
+ )
+ .await
+ .into_response();
assert_eq!(response.status(), StatusCode::OK);
let sid = resolve_session_id(&HookEnvelope::from_query_and_body(
@@ -3515,9 +3838,15 @@ mod tests {
let state = Arc::new(state);
let items = vec![opted_in_stop_item("cap-on", "the fix is in config.rs")];
- let response = handle_hook_batch(State(state.clone()), None, Json(items))
- .await
- .into_response();
+ let response = handle_hook_batch(
+ State(state.clone()),
+ None,
+ None,
+ HeaderMap::new(),
+ Json(items),
+ )
+ .await
+ .into_response();
assert_eq!(response.status(), StatusCode::OK);
let observations = state
@@ -3544,9 +3873,15 @@ mod tests {
let state = Arc::new(make_state(&tmp).await);
let items = vec![opted_in_stop_item("cap-off", "should not persist")];
- let response = handle_hook_batch(State(state.clone()), None, Json(items))
- .await
- .into_response();
+ let response = handle_hook_batch(
+ State(state.clone()),
+ None,
+ None,
+ HeaderMap::new(),
+ Json(items),
+ )
+ .await
+ .into_response();
assert_eq!(response.status(), StatusCode::OK);
let observations = state
@@ -3599,9 +3934,15 @@ mod tests {
},
];
- let response = handle_hook_batch(State(state.clone()), None, Json(items))
- .await
- .into_response();
+ let response = handle_hook_batch(
+ State(state.clone()),
+ None,
+ None,
+ HeaderMap::new(),
+ Json(items),
+ )
+ .await
+ .into_response();
assert_eq!(response.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
@@ -3660,9 +4001,15 @@ mod tests {
body: sub_body.clone(),
}];
- let response = handle_hook_batch(State(state.clone()), None, Json(items))
- .await
- .into_response();
+ let response = handle_hook_batch(
+ State(state.clone()),
+ None,
+ None,
+ HeaderMap::new(),
+ Json(items),
+ )
+ .await
+ .into_response();
assert_eq!(response.status(), StatusCode::OK);
let sub_sid = resolve_session_id(&HookEnvelope::from_query_and_body(
@@ -3710,9 +4057,15 @@ mod tests {
},
];
- let response = handle_hook_batch(State(state.clone()), None, Json(items))
- .await
- .into_response();
+ let response = handle_hook_batch(
+ State(state.clone()),
+ None,
+ None,
+ HeaderMap::new(),
+ Json(items),
+ )
+ .await
+ .into_response();
assert_eq!(response.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
@@ -3766,9 +4119,15 @@ mod tests {
},
];
- let response = handle_hook_batch(State(state.clone()), None, Json(items))
- .await
- .into_response();
+ let response = handle_hook_batch(
+ State(state.clone()),
+ None,
+ None,
+ HeaderMap::new(),
+ Json(items),
+ )
+ .await
+ .into_response();
assert_eq!(response.status(), StatusCode::OK);
let sid = resolve_session_id(&HookEnvelope::from_query_and_body(
@@ -3905,6 +4264,8 @@ mod tests {
let response = handle_hook_batch(
State(Arc::new(state)),
None,
+ None,
+ HeaderMap::new(),
Json(vec![HookBatchItem {
url: "http://h/hook?event=session-start&agent=claude-code".into(),
body: serde_json::json!({}),
@@ -3926,6 +4287,8 @@ mod tests {
let response = handle_hook_batch(
State(Arc::new(state)),
None,
+ None,
+ HeaderMap::new(),
Json(vec![
HookBatchItem {
url: "http://h/hook?event=session-start&agent=claude-code".into(),
@@ -3959,6 +4322,8 @@ mod tests {
let response = handle_hook_batch(
State(Arc::new(state)),
None,
+ None,
+ HeaderMap::new(),
Json(vec![
HookBatchItem {
url: "http://h/hook?event=session-start&agent=claude-code".into(),
@@ -3991,6 +4356,8 @@ mod tests {
let response = handle_hook_batch(
State(Arc::new(state)),
None,
+ None,
+ HeaderMap::new(),
Json(vec![HookBatchItem {
url: "http://h/hook?event=pre-tool-use&agent=grok&drop_subagent=1".into(),
body: serde_json::json!({
@@ -4020,6 +4387,8 @@ mod tests {
let response = handle_hook_batch(
State(Arc::new(state)),
None,
+ None,
+ HeaderMap::new(),
Json(vec![
HookBatchItem {
url: "http://h/hook?event=pre-tool-use&agent=grok&drop_subagent=1".into(),
@@ -4056,9 +4425,15 @@ mod tests {
})
.collect();
- let response = handle_hook_batch(State(Arc::new(state)), None, Json(items))
- .await
- .into_response();
+ let response = handle_hook_batch(
+ State(Arc::new(state)),
+ None,
+ None,
+ HeaderMap::new(),
+ Json(items),
+ )
+ .await
+ .into_response();
assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
@@ -4084,9 +4459,15 @@ mod tests {
},
];
- let response = handle_hook_batch(State(Arc::new(state)), None, Json(items))
- .await
- .into_response();
+ let response = handle_hook_batch(
+ State(Arc::new(state)),
+ None,
+ None,
+ HeaderMap::new(),
+ Json(items),
+ )
+ .await
+ .into_response();
assert_eq!(response.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
@@ -4895,7 +5276,7 @@ mod tests {
},
serde_json::json!({ "sessionID": "heal-sess-1" }),
);
- process(&state, env1, None).await.unwrap();
+ process(&state, env1, None, Vec::new()).await.unwrap();
let (ws, proj) = resolve_project_ids(
&state,
Some(cwd),
@@ -4935,7 +5316,7 @@ mod tests {
},
serde_json::json!({ "sessionID": "heal-sess-2" }),
);
- process(&state, env2, None)
+ process(&state, env2, None, Vec::new())
.await
.expect("self-heal: stale cached project must be recreated, not FK-fail");
@@ -4980,7 +5361,7 @@ mod tests {
},
serde_json::json!({ "sessionID": "move-sess-1" }),
);
- process(&state, env1, None).await.unwrap();
+ process(&state, env1, None, Vec::new()).await.unwrap();
let (ws, proj) = resolve_project_ids(
&state,
Some(cwd),
@@ -5027,7 +5408,7 @@ mod tests {
},
serde_json::json!({ "sessionID": "move-sess-2" }),
);
- process(&state, env2, None)
+ process(&state, env2, None, Vec::new())
.await
.expect("self-heal: stale cross-workspace pair must re-resolve, not write split-brain");
@@ -5080,7 +5461,7 @@ mod tests {
},
serde_json::json!({ "sessionID": "heal-repo-root-1" }),
);
- process(&state, env1, None).await.unwrap();
+ process(&state, env1, None, Vec::new()).await.unwrap();
let (ws, proj) = resolve_project_ids(
&state,
Some(cwd),
@@ -5108,7 +5489,7 @@ mod tests {
},
serde_json::json!({ "sessionID": "heal-repo-root-2" }),
);
- process(&state, env2, None)
+ process(&state, env2, None, Vec::new())
.await
.expect("repo-root cache slot must be evicted and recreated");
@@ -5145,7 +5526,7 @@ mod tests {
}),
);
- process(&state, env, None).await.unwrap();
+ process(&state, env, None, Vec::new()).await.unwrap();
// The observation must be in the project derived from the cwd,
// not in the server-default `scratch` project.
@@ -5186,7 +5567,7 @@ mod tests {
},
serde_json::json!({ "session_id": sid }),
);
- process(&state, env, None).await.unwrap();
+ process(&state, env, None, Vec::new()).await.unwrap();
}
let pages = state
@@ -5217,7 +5598,7 @@ mod tests {
},
serde_json::json!({ "session_id": sid }),
);
- process(&state, env, None).await.unwrap();
+ process(&state, env, None, Vec::new()).await.unwrap();
let completed = state
.reader
@@ -5260,6 +5641,7 @@ mod tests {
project_id,
agent_kind: agent,
cwd: Some(std::path::PathBuf::from("/tmp/target")),
+ actor_user: None,
})
.await
.unwrap();
@@ -5276,7 +5658,7 @@ mod tests {
},
serde_json::json!({ "session_id": target_sid.to_string(), "cwd": "/tmp/target" }),
);
- process(&state, env, None).await.unwrap();
+ process(&state, env, None, Vec::new()).await.unwrap();
assert_eq!(
state
@@ -5289,7 +5671,13 @@ mod tests {
assert_eq!(
state
.reader
- .open_sessions_for_scope_agent(state.workspace_id, other, AgentKind::Codex, None)
+ .open_sessions_for_scope_agent(
+ state.workspace_id,
+ other,
+ AgentKind::Codex,
+ ai_memory_core::OwnerFilter::Any,
+ None
+ )
.await
.unwrap()
.len(),
@@ -5303,6 +5691,7 @@ mod tests {
state.workspace_id,
target,
AgentKind::ClaudeCode,
+ ai_memory_core::OwnerFilter::Any,
None
)
.await
@@ -5352,6 +5741,7 @@ mod tests {
project_id,
agent_kind: agent,
cwd: Some(std::path::PathBuf::from("/tmp/target")),
+ actor_user: None,
})
.await
.unwrap();
@@ -5369,7 +5759,7 @@ mod tests {
},
serde_json::json!({ "session_id": sid.to_string(), "cwd": "/tmp/target" }),
);
- process(&state, env, None).await.unwrap();
+ process(&state, env, None, Vec::new()).await.unwrap();
}
let pages = state
@@ -5387,7 +5777,12 @@ mod tests {
assert!(
state
.reader
- .latest_open_handoff(state.workspace_id, target, None)
+ .latest_open_handoff(
+ state.workspace_id,
+ target,
+ None,
+ ai_memory_core::OwnerFilter::Any
+ )
.await
.unwrap()
.is_none(),
@@ -5427,12 +5822,17 @@ mod tests {
"cwd": tmp.path(),
}),
);
- process(&state, envelope, None).await.unwrap();
+ process(&state, envelope, None, Vec::new()).await.unwrap();
}
assert!(
state
.reader
- .latest_open_handoff(state.workspace_id, state.project_id, None)
+ .latest_open_handoff(
+ state.workspace_id,
+ state.project_id,
+ None,
+ ai_memory_core::OwnerFilter::Any
+ )
.await
.unwrap()
.is_none(),
@@ -5455,12 +5855,17 @@ mod tests {
"cwd": tmp.path(),
}),
);
- process(&state, envelope, None).await.unwrap();
+ process(&state, envelope, None, Vec::new()).await.unwrap();
}
assert!(
state
.reader
- .latest_open_handoff(state.workspace_id, state.project_id, None)
+ .latest_open_handoff(
+ state.workspace_id,
+ state.project_id,
+ None,
+ ai_memory_core::OwnerFilter::Any
+ )
.await
.unwrap()
.is_some(),
@@ -5468,45 +5873,872 @@ mod tests {
);
}
+ /// `GET /handoff` is the session-start delivery path, and it filters by the
+ /// human the request names. An ingress that forwards only the OIDC subject
+ /// claim names one — the auth layer resolves it to `AuthLevel::User` — so
+ /// reading `actor.user` here left a proxied operator unable to pick up the
+ /// baton their own previous session left them.
#[tokio::test]
- async fn already_ended_session_end_does_not_create_summary_or_handoff() {
+ async fn sub_only_proxy_session_start_claims_its_own_baton() {
let tmp = TempDir::new().unwrap();
let state = make_state(&tmp).await;
- let target = state
- .writer
- .get_or_create_project(state.workspace_id, "target", None)
- .await
- .unwrap();
- let sid = SessionId::new();
state
.writer
- .begin_session(NewSession {
- id: sid,
+ .insert_handoff(NewHandoff {
workspace_id: state.workspace_id,
- project_id: target,
- agent_kind: AgentKind::Codex,
- cwd: Some(std::path::PathBuf::from("/tmp/target")),
+ project_id: state.project_id,
+ from_session_id: None,
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: None,
+ summary: "SUB-OWNED-MARKER".to_string(),
+ open_questions: Vec::new(),
+ next_steps: Vec::new(),
+ files_touched: Vec::new(),
+ // Stamped through the contract, exactly as this operator's own
+ // previous SessionEnd would have: a qualified subject key.
+ owner_user: ai_memory_core::owner_stamp(
+ Some(&IdentityKey::Subject("oidc-subject-alice".into())),
+ true,
+ ),
})
.await
.unwrap();
- state.writer.end_session(sid, None).await.unwrap();
-
- let env = HookEnvelope::from_query_and_body(
- HookQuery {
- event: "session-end".into(),
- agent: Some("codex".into()),
- cwd: Some("/tmp/target".into()),
- workspace: Some("default".into()),
- project: Some("target".into()),
- ..Default::default()
- },
- serde_json::json!({ "session_id": sid.to_string(), "cwd": "/tmp/target" }),
+ let state = Arc::new(state);
+ let (status, body) = read_handoff_response(
+ handle_handoff(
+ State(state.clone()),
+ Query(HandoffQuery {
+ agent: Some("claude-code".into()),
+ cwd: Some(tmp.path().to_string_lossy().into_owned()),
+ workspace: Some("default".into()),
+ project: Some("scratch".into()),
+ project_strategy: None,
+ briefing: None,
+ briefing_budget: None,
+ managed_run: None,
+ session_id: None,
+ }),
+ Some(axum::Extension(ai_memory_core::ActorContext {
+ sub: Some("oidc-subject-alice".into()),
+ ..ai_memory_core::ActorContext::default()
+ })),
+ Some(axum::Extension(ai_memory_core::AuthLevel::User)),
+ HeaderMap::new(),
+ )
+ .await,
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK);
+ assert!(
+ body.contains("SUB-OWNED-MARKER"),
+ "a proxied operator could not claim their own baton: {body}",
);
- process(&state, env, None).await.unwrap();
+ }
- let pages = state
- .reader
- .recent_pages_for_project(state.workspace_id, target, 20)
+ /// A single-operator server that happens to name its operator
+ /// (`[auth].bearer_token` + `[auth].root_username`, no `users` rows, no
+ /// proxy) must keep stamping the pre-ownership `NULL` on the rows its hook
+ /// ingress creates. Naming the one operator separates nobody from anybody,
+ /// but it does separate that operator's HTTP traffic from their own stdio /
+ /// in-process transport, which carries no actor and therefore filters as
+ /// `Unattributed` — the session and the baton the hook writes would become
+ /// invisible to the person who produced them.
+ #[tokio::test]
+ async fn single_operator_hook_ingress_stamps_no_owner() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let operator = Some(IdentityKey::User("dj".into()));
+
+ process(
+ &state,
+ session_envelope("user-prompt-submit", "single-op-session", "/tmp/scratch"),
+ operator.clone(),
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+ process(
+ &state,
+ session_envelope("session-end", "single-op-session", "/tmp/scratch"),
+ operator,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+
+ let session_id = resolve_session_id(&session_envelope(
+ "session-end",
+ "single-op-session",
+ "/tmp/scratch",
+ ))
+ .unwrap();
+ assert_eq!(
+ state.reader.session_actor_user(session_id).await.unwrap(),
+ None,
+ "the session was bucketed under the only operator there is",
+ );
+
+ let handoff = state
+ .reader
+ .latest_open_handoff(
+ state.workspace_id,
+ state.project_id,
+ None,
+ ai_memory_core::OwnerFilter::Any,
+ )
+ .await
+ .unwrap()
+ .expect("SessionEnd writes a handoff");
+ assert_eq!(
+ handoff.owner_user, None,
+ "the baton was bucketed under the only operator there is",
+ );
+ // The point of the NULL: the same person's actorless transport still
+ // finds it.
+ assert!(
+ state
+ .reader
+ .latest_open_handoff(
+ state.workspace_id,
+ state.project_id,
+ None,
+ ai_memory_core::OwnerFilter::Unattributed,
+ )
+ .await
+ .unwrap()
+ .is_some(),
+ "the operator's own stdio transport cannot see the baton it produced",
+ );
+ }
+
+ /// A blocking, `Reject`-policy webhook on an address nothing answers. To a
+ /// reject chain a refusal and an unreachable policy host are the same
+ /// answer, so this covers both hazards without a test HTTP server.
+ fn refusing_admission_chain(
+ name: &str,
+ events: Vec<ai_memory_wiki::AdmissionOp>,
+ ) -> ai_memory_wiki::AdmissionChain {
+ ai_memory_wiki::AdmissionChain::new(vec![ai_memory_wiki::WebhookConfig {
+ name: name.into(),
+ url: "http://127.0.0.1:1/admission".into(),
+ timeout_ms: 50,
+ failure_policy: ai_memory_wiki::FailurePolicy::Reject,
+ events,
+ blocking: true,
+ }])
+ .unwrap()
+ }
+
+ async fn make_state_with_admission(
+ tmp: &TempDir,
+ chain: ai_memory_wiki::AdmissionChain,
+ ) -> HookState {
+ let mut state = make_state(tmp).await;
+ state.wiki = state.wiki.clone().with_admission_chain(chain);
+ state
+ }
+
+ fn session_envelope(event: &str, session: &str, cwd: &str) -> HookEnvelope {
+ HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: event.into(),
+ agent: Some("claude-code".into()),
+ cwd: Some(cwd.to_string()),
+ workspace: Some("default".into()),
+ project: Some("scratch".into()),
+ ..Default::default()
+ },
+ serde_json::json!({ "session_id": session, "cwd": cwd }),
+ )
+ }
+
+ async fn read_handoff_response(response: impl IntoResponse) -> (StatusCode, String) {
+ let response = response.into_response();
+ let status = response.status();
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ (status, String::from_utf8(bytes.to_vec()).unwrap())
+ }
+
+ async fn open_handoff_exists(state: &HookState) -> bool {
+ state
+ .reader
+ .latest_open_handoff(
+ state.workspace_id,
+ state.project_id,
+ None,
+ ai_memory_core::OwnerFilter::Any,
+ )
+ .await
+ .unwrap()
+ .is_some()
+ }
+
+ async fn session_pages(state: &HookState) -> Vec<String> {
+ state
+ .reader
+ .recent_pages_for_project(state.workspace_id, state.project_id, 20)
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|page| page.path.as_str().to_string())
+ .filter(|path| path.starts_with("sessions/"))
+ .collect()
+ }
+
+ /// A refused (or unreachable) `handoff_begin` webhook costs the baton and
+ /// nothing else: `end_session` commits either way, so a policy answer must
+ /// never abort the rest of SessionEnd — the summary page, the opt-in
+ /// consolidation and the auto-commit all still run, and the handler still
+ /// returns `Ok`.
+ #[tokio::test]
+ async fn session_end_completes_when_the_admission_chain_refuses_the_baton() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state_with_admission(
+ &tmp,
+ refusing_admission_chain(
+ "scope-guard",
+ vec![ai_memory_wiki::AdmissionOp::HandoffBegin],
+ ),
+ )
+ .await;
+ let cwd = tmp.path().to_string_lossy().into_owned();
+ let session = SessionId::new().to_string();
+ for event in ["session-start", "session-end"] {
+ process(
+ &state,
+ session_envelope(event, &session, &cwd),
+ None,
+ Vec::new(),
+ )
+ .await
+ .expect("a refused baton must not fail the SessionEnd handler");
+ }
+ assert!(
+ !session_pages(&state).await.is_empty(),
+ "the session summary page must be written even when the baton is refused",
+ );
+ assert!(
+ state
+ .reader
+ .latest_completed_session_for_project(state.workspace_id, state.project_id)
+ .await
+ .unwrap()
+ .is_some(),
+ "the session must still be closed",
+ );
+ assert!(
+ !open_handoff_exists(&state).await,
+ "the webhook refused the handoff, so none may be inserted",
+ );
+
+ // Default config (no admission chain at all) keeps creating the baton —
+ // the behaviour every single-operator install has today.
+ let default_tmp = TempDir::new().unwrap();
+ let default_state = make_state(&default_tmp).await;
+ let default_cwd = default_tmp.path().to_string_lossy().into_owned();
+ let default_session = SessionId::new().to_string();
+ for event in ["session-start", "session-end"] {
+ process(
+ &default_state,
+ session_envelope(event, &default_session, &default_cwd),
+ None,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+ }
+ assert!(
+ open_handoff_exists(&default_state).await,
+ "with no admission chain configured SessionEnd must still leave a baton",
+ );
+ }
+
+ /// `blocking = false` is the documented way to say "observer, off the
+ /// critical path". Which code path raised the event must not decide whether
+ /// that webhook hears about it: one `[[admission_webhooks]]` entry, one
+ /// subscription, both automatic handoff paths — the SessionEnd baton and
+ /// the session-start claim — reporting.
+ #[tokio::test]
+ async fn a_non_blocking_observer_hears_both_automatic_handoff_paths() {
+ let (addr, ops) = op_recording_webhook_host().await;
+ let tmp = TempDir::new().unwrap();
+ let state = Arc::new(
+ make_state_with_admission(
+ &tmp,
+ ai_memory_wiki::AdmissionChain::new(vec![ai_memory_wiki::WebhookConfig {
+ name: "mirror".into(),
+ url: format!("http://{addr}/admission"),
+ timeout_ms: 2_000,
+ failure_policy: ai_memory_wiki::FailurePolicy::default(),
+ events: vec![
+ ai_memory_wiki::AdmissionOp::HandoffBegin,
+ ai_memory_wiki::AdmissionOp::HandoffAccept,
+ ],
+ blocking: false,
+ }])
+ .unwrap(),
+ )
+ .await,
+ );
+ let cwd = tmp.path().to_string_lossy().into_owned();
+ let session = SessionId::new().to_string();
+ for event in ["session-start", "session-end"] {
+ process(
+ &state,
+ session_envelope(event, &session, &cwd),
+ None,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+ }
+ assert!(
+ open_handoff_exists(&state).await,
+ "SessionEnd must leave the baton this test is about",
+ );
+ wait_for_webhook_op(&ops, "handoff_begin").await;
+
+ let (body, _) = session_start_handoff(&state, &cwd).await;
+ assert!(
+ !body.is_empty(),
+ "the next session start claims the baton: {body}",
+ );
+ wait_for_webhook_op(&ops, "handoff_accept").await;
+ }
+
+ /// The hook ingress forwards `X-Memory-Skip-Admission-Chain` like every
+ /// other transport, so a webhook that re-enters the engine through a hook
+ /// can exclude itself — and only a caller that may use the header does.
+ #[tokio::test]
+ async fn hook_ingress_forwards_the_admission_skip_header() {
+ async fn baton_after_session(
+ level: Option<ai_memory_core::AuthLevel>,
+ skip: Option<&str>,
+ ) -> bool {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state_with_admission(
+ &tmp,
+ refusing_admission_chain(
+ "loop-guard",
+ vec![ai_memory_wiki::AdmissionOp::HandoffBegin],
+ ),
+ )
+ .await;
+ let cwd = tmp.path().to_string_lossy().into_owned();
+ let session = SessionId::new().to_string();
+ let items = ["session-start", "session-end"]
+ .into_iter()
+ .map(|event| HookBatchItem {
+ url: format!(
+ "http://h/hook?event={event}&agent=claude-code&workspace=default&project=scratch"
+ ),
+ body: serde_json::json!({ "session_id": session, "cwd": cwd }),
+ })
+ .collect::<Vec<_>>();
+ let mut headers = HeaderMap::new();
+ if let Some(skip) = skip {
+ headers.insert(
+ axum::http::HeaderName::from_static(
+ ai_memory_core::SKIP_ADMISSION_CHAIN_HEADER,
+ ),
+ skip.parse().unwrap(),
+ );
+ }
+ let response = handle_hook_batch(
+ State(Arc::new(state.clone())),
+ None,
+ level.map(axum::Extension),
+ headers,
+ Json(items),
+ )
+ .await
+ .into_response();
+ assert_eq!(response.status(), StatusCode::OK);
+ open_handoff_exists(&state).await
+ }
+
+ assert!(
+ !baton_after_session(Some(ai_memory_core::AuthLevel::Root), None).await,
+ "without the header the reject-policy webhook still refuses the baton",
+ );
+ assert!(
+ baton_after_session(Some(ai_memory_core::AuthLevel::Root), Some("loop-guard")).await,
+ "the skip list must reach the chain from the hook path",
+ );
+ assert!(
+ !baton_after_session(Some(ai_memory_core::AuthLevel::User), Some("loop-guard")).await,
+ "a DB user must not bypass a reject-policy webhook with a header",
+ );
+ }
+
+ /// The session-start claim is destructive (a handoff is single-use), so a
+ /// refused or unreachable `handoff_accept` webhook must leave the baton
+ /// open for the next session instead of failing the endpoint — and the
+ /// same skip header releases it.
+ #[tokio::test]
+ async fn refused_handoff_claim_leaves_the_baton_open_for_the_next_session() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state_with_admission(
+ &tmp,
+ refusing_admission_chain(
+ "loop-guard",
+ vec![ai_memory_wiki::AdmissionOp::HandoffAccept],
+ ),
+ )
+ .await;
+ let cwd = tmp.path().to_string_lossy().into_owned();
+ state
+ .writer
+ .insert_handoff(NewHandoff {
+ workspace_id: state.workspace_id,
+ project_id: state.project_id,
+ from_session_id: None,
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: None,
+ summary: "HANDOFF-MARKER".to_string(),
+ open_questions: Vec::new(),
+ next_steps: Vec::new(),
+ files_touched: Vec::new(),
+ owner_user: None,
+ })
+ .await
+ .unwrap();
+ let query = || HandoffQuery {
+ agent: Some("claude-code".into()),
+ cwd: Some(cwd.clone()),
+ workspace: Some("default".into()),
+ project: Some("scratch".into()),
+ project_strategy: None,
+ briefing: None,
+ briefing_budget: None,
+ managed_run: None,
+ session_id: None,
+ };
+
+ let state = Arc::new(state);
+ let (status, body) = read_handoff_response(
+ handle_handoff(
+ State(state.clone()),
+ Query(query()),
+ None,
+ None,
+ HeaderMap::new(),
+ )
+ .await,
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK);
+ assert!(
+ !body.contains("HANDOFF-MARKER"),
+ "a refused claim must not deliver the handoff: {body}",
+ );
+ assert!(
+ open_handoff_exists(&state).await,
+ "a refused claim must leave the baton open for the next session",
+ );
+
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ axum::http::HeaderName::from_static(ai_memory_core::SKIP_ADMISSION_CHAIN_HEADER),
+ axum::http::HeaderValue::from_static("loop-guard"),
+ );
+ let (status, body) = read_handoff_response(
+ handle_handoff(
+ State(state.clone()),
+ Query(query()),
+ None,
+ Some(axum::Extension(ai_memory_core::AuthLevel::Root)),
+ headers,
+ )
+ .await,
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK);
+ assert!(
+ body.contains("HANDOFF-MARKER"),
+ "the skip list must reach the session-start claim: {body}",
+ );
+ assert!(
+ !open_handoff_exists(&state).await,
+ "an admitted claim consumes the baton exactly as before",
+ );
+ }
+
+ /// A listener that accepts connections and never replies, so a webhook
+ /// pointed at it hangs until its own configured timeout.
+ async fn hung_webhook_host() -> std::net::SocketAddr {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ let mut accepted = Vec::new();
+ while let Ok((stream, _)) = listener.accept().await {
+ accepted.push(stream);
+ }
+ });
+ addr
+ }
+
+ /// A webhook host that answers `204` and counts the requests it saw.
+ async fn counting_webhook_host() -> (std::net::SocketAddr, Arc<AtomicUsize>) {
+ let hits = Arc::new(AtomicUsize::new(0));
+ let seen = hits.clone();
+ let app = axum::Router::new().route(
+ "/admission",
+ axum::routing::post(move || {
+ let seen = seen.clone();
+ async move {
+ seen.fetch_add(1, Ordering::SeqCst);
+ StatusCode::NO_CONTENT
+ }
+ }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+ (addr, hits)
+ }
+
+ /// A webhook host that answers `204` and records the `X-Memory-Op` of every
+ /// request, so a test can tell which event reached it.
+ async fn op_recording_webhook_host()
+ -> (std::net::SocketAddr, Arc<std::sync::Mutex<Vec<String>>>) {
+ let ops = Arc::new(std::sync::Mutex::new(Vec::new()));
+ let seen = ops.clone();
+ let app = axum::Router::new().route(
+ "/admission",
+ axum::routing::post(move |headers: HeaderMap| {
+ let seen = seen.clone();
+ async move {
+ seen.lock().unwrap().push(
+ headers
+ .get("x-memory-op")
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("")
+ .to_string(),
+ );
+ StatusCode::NO_CONTENT
+ }
+ }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+ (addr, ops)
+ }
+
+ async fn wait_for_webhook_op(ops: &Arc<std::sync::Mutex<Vec<String>>>, want: &str) {
+ let deadline = std::time::Instant::now() + Duration::from_secs(5);
+ loop {
+ let seen = ops.lock().unwrap().clone();
+ if seen.iter().any(|op| op == want) {
+ return;
+ }
+ assert!(
+ std::time::Instant::now() < deadline,
+ "the observer was never told about {want}; saw {seen:?}",
+ );
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ }
+
+ async fn state_with_pending_handoff(
+ tmp: &TempDir,
+ chain: ai_memory_wiki::AdmissionChain,
+ ) -> Arc<HookState> {
+ let state = make_state_with_admission(tmp, chain).await;
+ state
+ .writer
+ .insert_handoff(NewHandoff {
+ workspace_id: state.workspace_id,
+ project_id: state.project_id,
+ from_session_id: None,
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: None,
+ summary: "HANDOFF-MARKER".to_string(),
+ open_questions: Vec::new(),
+ next_steps: Vec::new(),
+ files_touched: Vec::new(),
+ owner_user: None,
+ })
+ .await
+ .unwrap();
+ Arc::new(state)
+ }
+
+ async fn session_start_handoff(state: &Arc<HookState>, cwd: &str) -> (String, Duration) {
+ let started = std::time::Instant::now();
+ let (status, body) = read_handoff_response(
+ handle_handoff(
+ State(state.clone()),
+ Query(HandoffQuery {
+ agent: Some("claude-code".into()),
+ cwd: Some(cwd.to_string()),
+ workspace: Some("default".into()),
+ project: Some("scratch".into()),
+ project_strategy: None,
+ briefing: None,
+ briefing_budget: None,
+ managed_run: None,
+ session_id: None,
+ }),
+ None,
+ None,
+ HeaderMap::new(),
+ )
+ .await,
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK);
+ (body, started.elapsed())
+ }
+
+ /// `GET /handoff` is called synchronously by the session-start hook, which
+ /// hard-timeouts at ≤200 ms (AGENTS.md invariant 5). Under the default
+ /// `ignore` policy a webhook has nothing to decide — one ordinary observer
+ /// on a host that stalls must therefore neither hold the endpoint nor cost
+ /// the operator the baton, which is the whole point of admitting this op.
+ #[tokio::test]
+ async fn default_policy_webhook_never_costs_the_session_start_baton() {
+ let addr = hung_webhook_host().await;
+ let tmp = TempDir::new().unwrap();
+ let chain = ai_memory_wiki::AdmissionChain::new(vec![ai_memory_wiki::WebhookConfig {
+ name: "observer".into(),
+ url: format!("http://{addr}/admission"),
+ timeout_ms: 5_000,
+ failure_policy: ai_memory_wiki::FailurePolicy::default(),
+ events: vec![ai_memory_wiki::AdmissionOp::HandoffAccept],
+ blocking: true,
+ }])
+ .unwrap();
+ let state = state_with_pending_handoff(&tmp, chain).await;
+ let cwd = tmp.path().to_string_lossy().into_owned();
+
+ let (body, elapsed) = session_start_handoff(&state, &cwd).await;
+ assert!(
+ elapsed < Duration::from_secs(2),
+ "a stalled observer must not hold the session-start path: {elapsed:?}",
+ );
+ assert!(
+ body.contains("HANDOFF-MARKER"),
+ "an ignore-policy webhook cannot refuse the claim, so the baton is delivered: {body}",
+ );
+ assert!(
+ !open_handoff_exists(&state).await,
+ "the delivered baton must be consumed",
+ );
+ }
+
+ /// The other half: a webhook the operator explicitly set to `reject` is a
+ /// deliberate request to gate the claim, so it is still waited for and a
+ /// host that never answers still leaves the baton open.
+ ///
+ /// The 200 ms below is this test's own choice, not the engine's: what the
+ /// endpoint actually waits for is the hook's `timeout_ms`, whose default is
+ /// ten times that — see
+ /// [`a_reject_webhook_on_its_default_timeout_outlasts_the_hook_budget`].
+ #[tokio::test]
+ async fn reject_policy_webhook_still_gates_the_session_start_claim() {
+ let addr = hung_webhook_host().await;
+ let tmp = TempDir::new().unwrap();
+ let chain = ai_memory_wiki::AdmissionChain::new(vec![ai_memory_wiki::WebhookConfig {
+ name: "scope-guard".into(),
+ url: format!("http://{addr}/admission"),
+ timeout_ms: 200,
+ failure_policy: ai_memory_wiki::FailurePolicy::Reject,
+ events: vec![ai_memory_wiki::AdmissionOp::HandoffAccept],
+ blocking: true,
+ }])
+ .unwrap();
+ let state = state_with_pending_handoff(&tmp, chain).await;
+ let cwd = tmp.path().to_string_lossy().into_owned();
+
+ let (body, _) = session_start_handoff(&state, &cwd).await;
+ assert!(
+ body.is_empty(),
+ "nothing was admitted, so nothing is served: {body}",
+ );
+ assert!(
+ open_handoff_exists(&state).await,
+ "the unanswered claim must leave the baton open for the next session",
+ );
+ }
+
+ /// What actually bounds the session-start claim, on the config an operator
+ /// gets by writing no `timeout_ms` at all: the webhook's own default, 2 s —
+ /// an order of magnitude past the ≤200 ms budget of the script calling this
+ /// endpoint. `docs/admission-webhooks.md` says so and tells operators to set
+ /// `timeout_ms` themselves if they want the round trip to fit; this pins the
+ /// number that documentation quotes, since only a `reject` hook is waited
+ /// for and nothing else in the chain shortens it.
+ #[tokio::test]
+ async fn a_reject_webhook_on_its_default_timeout_outlasts_the_hook_budget() {
+ let addr = hung_webhook_host().await;
+ // Built the way the operator's config is: through serde, so the
+ // omitted `timeout_ms` is the engine's default and not a literal
+ // repeated here (which is how the bound stopped matching the docs).
+ let guard: ai_memory_wiki::WebhookConfig = serde_json::from_value(serde_json::json!({
+ "name": "scope-guard",
+ "url": format!("http://{addr}/admission"),
+ "failure_policy": "reject",
+ "events": ["handoff_accept"],
+ }))
+ .unwrap();
+ assert_eq!(
+ guard.timeout_ms, 2_000,
+ "the documented default this test is about",
+ );
+
+ let tmp = TempDir::new().unwrap();
+ let state = state_with_pending_handoff(
+ &tmp,
+ ai_memory_wiki::AdmissionChain::new(vec![guard]).unwrap(),
+ )
+ .await;
+ let cwd = tmp.path().to_string_lossy().into_owned();
+
+ let (body, elapsed) = session_start_handoff(&state, &cwd).await;
+ assert!(
+ elapsed > Duration::from_millis(200),
+ "the claim is NOT bounded by the 200 ms hook budget; it waited {elapsed:?}",
+ );
+ assert!(
+ elapsed < Duration::from_secs(10),
+ "but it is bounded by the hook's own timeout_ms: {elapsed:?}",
+ );
+ assert!(
+ body.is_empty(),
+ "an unanswered reject serves nothing: {body}"
+ );
+ assert!(
+ open_handoff_exists(&state).await,
+ "and leaves the baton open for the next session",
+ );
+ }
+
+ /// A handoff is single-use, so a webhook that is told the claim happened
+ /// and then sees the same claim replayed next session has been lied to.
+ /// Observers are therefore dispatched only once the claim is durable —
+ /// never before a reject-policy webhook later in the chain has spoken.
+ #[tokio::test]
+ async fn observers_only_hear_about_a_claim_that_landed() {
+ let (mirror_addr, mirror_hits) = counting_webhook_host().await;
+ let mirror = ai_memory_wiki::WebhookConfig {
+ name: "mirror".into(),
+ url: format!("http://{mirror_addr}/admission"),
+ timeout_ms: 2_000,
+ failure_policy: ai_memory_wiki::FailurePolicy::default(),
+ events: vec![ai_memory_wiki::AdmissionOp::HandoffAccept],
+ blocking: true,
+ };
+ let guard = ai_memory_wiki::WebhookConfig {
+ name: "scope-guard".into(),
+ // Nothing answers here: to a reject chain that is a refusal.
+ url: "http://127.0.0.1:1/admission".into(),
+ timeout_ms: 50,
+ failure_policy: ai_memory_wiki::FailurePolicy::Reject,
+ events: vec![ai_memory_wiki::AdmissionOp::HandoffAccept],
+ blocking: true,
+ };
+
+ let refused_tmp = TempDir::new().unwrap();
+ let refused = state_with_pending_handoff(
+ &refused_tmp,
+ ai_memory_wiki::AdmissionChain::new(vec![mirror.clone(), guard]).unwrap(),
+ )
+ .await;
+ let refused_cwd = refused_tmp.path().to_string_lossy().into_owned();
+ let (body, _) = session_start_handoff(&refused, &refused_cwd).await;
+ assert!(body.is_empty(), "the refused claim serves nothing: {body}");
+ assert!(
+ open_handoff_exists(&refused).await,
+ "the refused claim leaves the baton open",
+ );
+ // The dispatch is fire-and-forget; give a wrongly-spawned one time to land.
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ assert_eq!(
+ mirror_hits.load(Ordering::SeqCst),
+ 0,
+ "no webhook may be told about a claim the engine abandoned",
+ );
+
+ // Same observer, nothing gating it: the claim lands and the observer is
+ // told exactly once, off the critical path.
+ let accepted_tmp = TempDir::new().unwrap();
+ let accepted = state_with_pending_handoff(
+ &accepted_tmp,
+ ai_memory_wiki::AdmissionChain::new(vec![mirror]).unwrap(),
+ )
+ .await;
+ let accepted_cwd = accepted_tmp.path().to_string_lossy().into_owned();
+ let (body, _) = session_start_handoff(&accepted, &accepted_cwd).await;
+ assert!(
+ body.contains("HANDOFF-MARKER"),
+ "the admitted claim delivers the baton: {body}",
+ );
+ let deadline = std::time::Instant::now() + Duration::from_secs(5);
+ while mirror_hits.load(Ordering::SeqCst) == 0 {
+ assert!(
+ std::time::Instant::now() < deadline,
+ "the observer must still be notified of a claim that landed",
+ );
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ assert_eq!(
+ mirror_hits.load(Ordering::SeqCst),
+ 1,
+ "a single-use claim is announced once",
+ );
+ }
+
+ #[tokio::test]
+ async fn already_ended_session_end_does_not_create_summary_or_handoff() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let target = state
+ .writer
+ .get_or_create_project(state.workspace_id, "target", None)
+ .await
+ .unwrap();
+ let sid = SessionId::new();
+ state
+ .writer
+ .begin_session(NewSession {
+ id: sid,
+ workspace_id: state.workspace_id,
+ project_id: target,
+ agent_kind: AgentKind::Codex,
+ cwd: Some(std::path::PathBuf::from("/tmp/target")),
+ actor_user: None,
+ })
+ .await
+ .unwrap();
+ state.writer.end_session(sid, None).await.unwrap();
+
+ let env = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "session-end".into(),
+ agent: Some("codex".into()),
+ cwd: Some("/tmp/target".into()),
+ workspace: Some("default".into()),
+ project: Some("target".into()),
+ ..Default::default()
+ },
+ serde_json::json!({ "session_id": sid.to_string(), "cwd": "/tmp/target" }),
+ );
+ process(&state, env, None, Vec::new()).await.unwrap();
+
+ let pages = state
+ .reader
+ .recent_pages_for_project(state.workspace_id, target, 20)
.await
.unwrap();
assert!(
@@ -5518,7 +6750,12 @@ mod tests {
assert!(
state
.reader
- .latest_open_handoff(state.workspace_id, target, None)
+ .latest_open_handoff(
+ state.workspace_id,
+ target,
+ None,
+ ai_memory_core::OwnerFilter::Any
+ )
.await
.unwrap()
.is_none(),
@@ -5552,10 +6789,12 @@ mod tests {
serde_json::json!({ "session_id": sid, "prompt": "finish" }),
)
};
- process(&state, fire("user-prompt-submit"), None)
+ process(&state, fire("user-prompt-submit"), None, Vec::new())
+ .await
+ .unwrap();
+ process(&state, fire("session-end"), None, Vec::new())
.await
.unwrap();
- process(&state, fire("session-end"), None).await.unwrap();
assert!(
llm.0.lock().unwrap().is_none(),
@@ -5600,7 +6839,7 @@ mod tests {
serde_json::json!({ "session_id": sid, "prompt": "finish" }),
)
};
- process(&state, fire("user-prompt-submit", None), None)
+ process(&state, fire("user-prompt-submit", None), None, Vec::new())
.await
.unwrap();
let (workspace_id, project_id, _) = state
@@ -5667,6 +6906,7 @@ mod tests {
session_id,
None,
&observations,
+ None,
);
state
.writer
@@ -5674,9 +6914,14 @@ mod tests {
.await
.unwrap();
- process(&state, fire("session-end", Some("entry-recovery")), None)
- .await
- .unwrap();
+ process(
+ &state,
+ fire("session-end", Some("entry-recovery")),
+ None,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
let now = Timestamp::now().as_microsecond();
let job = state
.writer
@@ -5697,7 +6942,12 @@ mod tests {
);
let briefing = state
.reader
- .briefing_for_project(workspace_id, project_id, 1)
+ .briefing_for_project(
+ workspace_id,
+ project_id,
+ 1,
+ ai_memory_core::OwnerFilter::Any,
+ )
.await
.unwrap();
assert_eq!(
@@ -5739,10 +6989,15 @@ mod tests {
};
// First life: one tool call, then a real end.
- process(&state, fire("post-tool-use", Some("Bash")), None)
- .await
- .unwrap();
- process(&state, fire("session-end", None), None)
+ process(
+ &state,
+ fire("post-tool-use", Some("Bash")),
+ None,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+ process(&state, fire("session-end", None), None, Vec::new())
.await
.unwrap();
let disposition = state
@@ -5770,9 +7025,14 @@ mod tests {
.expect("first SessionEnd writes the session page");
// Second life: the agent resumed the same id and did more work.
- process(&state, fire("post-tool-use", Some("Edit")), None)
- .await
- .unwrap();
+ process(
+ &state,
+ fire("post-tool-use", Some("Edit")),
+ None,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
let disposition = state
.reader
.session_end_disposition(
@@ -5789,7 +7049,7 @@ mod tests {
"a newer observation generation must mark the session re-endable"
);
- process(&state, fire("session-end", None), None)
+ process(&state, fire("session-end", None), None, Vec::new())
.await
.unwrap();
@@ -5810,7 +7070,12 @@ mod tests {
assert!(
state
.reader
- .latest_open_handoff(state.workspace_id, state.project_id, None)
+ .latest_open_handoff(
+ state.workspace_id,
+ state.project_id,
+ None,
+ ai_memory_core::OwnerFilter::Any
+ )
.await
.unwrap()
.is_some(),
@@ -5854,7 +7119,7 @@ mod tests {
}),
);
- process(&state, env, None).await.unwrap();
+ process(&state, env, None, Vec::new()).await.unwrap();
let counts = state.reader.status_counts().await.unwrap();
assert_eq!(counts.sessions, 1);
@@ -5882,7 +7147,7 @@ mod tests {
);
let session_id = resolve_session_id(&env).unwrap();
- process(&state, env, None).await.unwrap();
+ process(&state, env, None, Vec::new()).await.unwrap();
let observations = state
.reader
@@ -5924,7 +7189,7 @@ mod tests {
);
let session_id = resolve_session_id(&env).unwrap();
- process(&state, env, None).await.unwrap();
+ process(&state, env, None, Vec::new()).await.unwrap();
let observations = state
.reader
@@ -6013,6 +7278,7 @@ mod tests {
open_questions: Vec::new(),
next_steps: vec!["continue".to_string()],
files_touched: Vec::new(),
+ owner_user: None,
})
.await
.unwrap();
@@ -6031,6 +7297,7 @@ mod tests {
session_id: None,
},
None,
+ Vec::new(),
)
.await
.unwrap();
@@ -6060,6 +7327,7 @@ mod tests {
project_id: state.project_id,
agent_kind: AgentKind::ClaudeCode,
cwd: Some(cwd.into()),
+ actor_user: None,
})
.await
.unwrap();
@@ -6076,6 +7344,7 @@ mod tests {
open_questions: Vec::new(),
next_steps: Vec::new(),
files_touched: Vec::new(),
+ owner_user: None,
})
.await
.unwrap()
@@ -6098,6 +7367,7 @@ mod tests {
session_id: None,
},
None,
+ Vec::new(),
)
.await
.unwrap()
@@ -6193,6 +7463,7 @@ mod tests {
open_questions: Vec::new(),
next_steps: vec!["resume the curated thread".to_string()],
files_touched: Vec::new(),
+ owner_user: None,
})
.await
.unwrap();
@@ -6208,7 +7479,7 @@ mod tests {
managed_run: Some(run.run_id.to_string()),
session_id: Some("native-2".into()),
};
- let rendered = fetch_and_accept_handoff(&state, query.clone(), None)
+ let rendered = fetch_and_accept_handoff(&state, query.clone(), None, Vec::new())
.await
.unwrap();
@@ -6224,14 +7495,19 @@ mod tests {
assert!(
state
.reader
- .latest_open_handoff(state.workspace_id, state.project_id, None)
+ .latest_open_handoff(
+ state.workspace_id,
+ state.project_id,
+ None,
+ ai_memory_core::OwnerFilter::Any
+ )
.await
.unwrap()
.is_none(),
"a handoff delivered on a managed SessionStart must be marked accepted"
);
assert!(
- fetch_and_accept_handoff(&state, query, None)
+ fetch_and_accept_handoff(&state, query, None, Vec::new())
.await
.unwrap()
.is_none(),
@@ -6307,7 +7583,7 @@ mod tests {
};
// Non-truthy opt-in: no handoff pending, nothing to inject.
- let rendered = fetch_and_accept_handoff(&state, query(Some("false")), None)
+ let rendered = fetch_and_accept_handoff(&state, query(Some("false")), None, Vec::new())
.await
.unwrap();
assert!(
@@ -6316,7 +7592,7 @@ mod tests {
);
// Truthy opt-in, no pending handoff: brief alone (the /clear case).
- let rendered = fetch_and_accept_handoff(&state, query(Some("true")), None)
+ let rendered = fetch_and_accept_handoff(&state, query(Some("true")), None, Vec::new())
.await
.unwrap()
.expect("brief must be injected without a pending handoff");
@@ -6349,10 +7625,11 @@ mod tests {
open_questions: Vec::new(),
next_steps: Vec::new(),
files_touched: Vec::new(),
+ owner_user: None,
})
.await
.unwrap();
- let rendered = fetch_and_accept_handoff(&state, query(Some("true")), None)
+ let rendered = fetch_and_accept_handoff(&state, query(Some("true")), None, Vec::new())
.await
.unwrap()
.expect("handoff + brief must both be injected");
@@ -6448,7 +7725,7 @@ mod tests {
session_id: Some("kimi-session".into()),
};
- let rendered = fetch_and_accept_handoff(&state, query(Some("true")), None)
+ let rendered = fetch_and_accept_handoff(&state, query(Some("true")), None, Vec::new())
.await
.unwrap()
.expect("managed delta and brief must be injected");
@@ -6459,7 +7736,7 @@ mod tests {
"managed delta must precede the project brief: {rendered}"
);
- let rendered = fetch_and_accept_handoff(&state, query(None), None)
+ let rendered = fetch_and_accept_handoff(&state, query(None), None, Vec::new())
.await
.unwrap();
assert!(
@@ -6467,7 +7744,7 @@ mod tests {
"delivered managed context must not repeat without a new briefing request"
);
- let rendered = fetch_and_accept_handoff(&state, query(Some("true")), None)
+ let rendered = fetch_and_accept_handoff(&state, query(Some("true")), None, Vec::new())
.await
.unwrap()
.expect("an explicit later briefing request must still render the project brief");
@@ -6570,6 +7847,7 @@ mod tests {
open_questions: Vec::new(),
next_steps: vec!["resume plain repo".to_string()],
files_touched: Vec::new(),
+ owner_user: None,
})
.await
.unwrap();
@@ -6588,6 +7866,7 @@ mod tests {
session_id: None,
},
None,
+ Vec::new(),
)
.await
.unwrap();
@@ -7277,7 +8556,7 @@ mod tests {
"source": "startup"
}),
);
- process(&state, start, None).await.unwrap();
+ process(&state, start, None, Vec::new()).await.unwrap();
let pages_before = state
.reader
@@ -7301,7 +8580,9 @@ mod tests {
"summary": summary
}),
);
- process(&state, post_compaction, None).await.unwrap();
+ process(&state, post_compaction, None, Vec::new())
+ .await
+ .unwrap();
let pages_after = state
.reader
@@ -7357,7 +8638,12 @@ mod tests {
assert!(
state
.reader
- .latest_open_handoff(state.workspace_id, state.project_id, None)
+ .latest_open_handoff(
+ state.workspace_id,
+ state.project_id,
+ None,
+ ai_memory_core::OwnerFilter::Any
+ )
.await
.unwrap()
.is_none(),
@@ -7645,6 +8931,7 @@ mod tests {
body,
),
None,
+ Vec::new(),
)
.await
.unwrap();
@@ -7682,7 +8969,7 @@ mod tests {
metadata.body_excerpt.as_deref() == Some("tool_family: file\noutcome: unknown"),
"metadata-only protocol renders only its safe summary"
);
- process(&state, metadata, None).await.unwrap();
+ process(&state, metadata, None, Vec::new()).await.unwrap();
let mut assistant_body = serde_json::json!({
"session_id": session_id,
@@ -7709,7 +8996,7 @@ mod tests {
&mut assistant,
state.capture_assistant_enabled,
);
- process(&state, assistant, None).await.unwrap();
+ process(&state, assistant, None, Vec::new()).await.unwrap();
process(
&state,
@@ -7722,6 +9009,7 @@ mod tests {
serde_json::json!({ "session_id": session_id, "cwd": "/repo" }),
),
None,
+ Vec::new(),
)
.await
.unwrap();
@@ -7773,7 +9061,12 @@ mod tests {
assert!(!page.body.contains(ASSISTANT_SENTINEL));
let handoff = state
.reader
- .latest_open_handoff(workspace_id, project_id, None)
+ .latest_open_handoff(
+ workspace_id,
+ project_id,
+ None,
+ ai_memory_core::OwnerFilter::Any,
+ )
.await
.unwrap()
.unwrap();
@@ -7854,6 +9147,7 @@ mod tests {
}),
),
None,
+ Vec::new(),
)
.await
.unwrap();
@@ -7969,6 +9263,8 @@ mod tests {
let response = handle_hook_batch(
State(state.clone()),
None,
+ None,
+ HeaderMap::new(),
Json(vec![
HookBatchItem {
url: "http://h/hook?event=session-start&agent=claude-code".into(),
@@ -7989,8 +9285,7 @@ mod tests {
"_ai_memory_capture": capture_protocol("metadata-only", "invalid", "file", 1, "extracted"),
}),
},
- ]),
- )
+ ]))
.await
.into_response();
assert_eq!(response.status(), StatusCode::OK);
@@ -8028,6 +9323,8 @@ mod tests {
let response = handle_hook_batch(
State(state.clone()),
None,
+ None,
+ HeaderMap::new(),
Json(vec![HookBatchItem {
url: "http://h/hook?event=post-tool-use&agent=claude-code".into(),
body: serde_json::json!({
@@ -8035,8 +9332,7 @@ mod tests {
"tool_input": { "file_path": "/repo/private.txt" },
"_ai_memory_capture": capture_protocol("drop", "inactive", "unknown", 99, "extracted"),
}),
- }]),
- )
+ }]))
.await
.into_response();
assert_eq!(response.status(), StatusCode::OK);
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 281240a5..7be3aea3 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -864,6 +864,17 @@ struct OpenSessionsQuery {
/// When true, return every open session; otherwise just the newest.
#[serde(default)]
all: bool,
+ /// Include sessions belonging to OTHER operators.
+ ///
+ /// Off by default because the caller of this endpoint (`finalize-session`)
+ /// acts destructively on what it returns: it ends the session, synthesises
+ /// a page from its observations and mints a handoff carrying its raw
+ /// prompts. Picking "the newest open session in the scope" across everyone
+ /// would do all of that to a colleague's live session. Sessions with no
+ /// recorded operator stay visible either way, so a single-operator server
+ /// is unaffected.
+ #[serde(default)]
+ all_owners: bool,
}
/// Wire shape for one open session in the `GET /admin/open-sessions`
@@ -881,6 +892,7 @@ fn parse_agent_kind(raw: &str) -> Option<AgentKind> {
async fn handle_open_sessions(
State(state): State<Arc<AdminState>>,
+ actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,
Query(query): Query<OpenSessionsQuery>,
) -> impl IntoResponse {
let Some(agent) = parse_agent_kind(&query.agent) else {
@@ -897,9 +909,16 @@ async fn handle_open_sessions(
Err(e) => return e,
};
let limit = if query.all { None } else { Some(1) };
+ let owner_filter = if query.all_owners {
+ ai_memory_core::OwnerFilter::Any
+ } else {
+ ai_memory_core::OwnerFilter::for_actor_context(
+ &actor_ext.map_or_else(ai_memory_core::ActorContext::anonymous, |ext| ext.0),
+ )
+ };
match state
.reader
- .open_sessions_for_scope_agent(ws, proj, agent, limit)
+ .open_sessions_for_scope_agent(ws, proj, agent, owner_filter, limit)
.await
{
Ok(sessions) => {
@@ -5241,6 +5260,7 @@ mod tests {
project_id,
agent_kind: agent,
cwd: Some(std::path::PathBuf::from("/tmp/target")),
+ actor_user: None,
})
.await
.unwrap();
@@ -5675,6 +5695,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::Other,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -5805,6 +5826,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::Other,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -5903,6 +5925,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::Other,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 0213d99e..d7e6a8cf 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -729,10 +729,19 @@ struct HandoffBeginArgs {
/// Files touched during the session.
#[serde(default)]
files_touched: Vec<String>,
- /// Working directory at the time of handoff. Used to match the
- /// next agent's `memory_handoff_accept` call.
+ /// Working directory at the time of handoff. Recorded on the handoff and
+ /// used to scope AUTOMATIC session-end handoffs by path boundary. A handoff
+ /// created through this tool is project-wide, so `cwd` does not narrow who
+ /// receives it — ownership does.
#[serde(default)]
cwd: Option<String>,
+ /// Publish the handoff to everyone in the project instead of keeping it for
+ /// you. By default a handoff belongs to the operator that created it, so on
+ /// a shared server a teammate's session cannot consume it by accident. Set
+ /// this when you deliberately want to pass the baton to whoever picks the
+ /// project up next.
+ #[serde(default)]
+ shared: Option<bool>,
/// Project to scope the handoff to. Omit to target the project you're
/// currently working in (resolved from recent hook activity). When set to a
/// name that doesn't exist yet, the project is **created** — so the handoff
@@ -758,6 +767,12 @@ struct HandoffAcceptArgs {
/// project (the SessionStart hook usually pre-fetches it into context).
#[serde(default)]
cwd: Option<String>,
+ /// Also consider handoffs that belong to OTHER operators. Off by default:
+ /// on a shared server you only see your own plus the ones published to the
+ /// whole project. Use this for recovery ("somebody left a baton here and
+ /// they are away"), knowing it consumes their handoff.
+ #[serde(default)]
+ any_owner: Option<bool>,
/// Project to accept a handoff from. Omit to target the project you're
/// currently working in (resolved from recent hook activity). **Omit unless the user explicitly names a *different* project.**
#[serde(default)]
@@ -772,6 +787,10 @@ struct HandoffAcceptArgs {
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct HandoffCancelArgs {
+ /// Cancel even when the handoff belongs to another operator. Off by
+ /// default; requires the same authority as other cross-operator actions.
+ #[serde(default)]
+ any_owner: Option<bool>,
/// Exact handoff id returned by `memory_handoff_begin`. Required so this
/// tool only discards a handoff the agent can identify.
handoff_id: String,
@@ -1051,7 +1070,14 @@ impl AiMemoryServer {
return ai_memory_core::ActorKey::default();
};
let ctx = parts.extensions.get::<ai_memory_core::ActorContext>();
- let user = ctx.and_then(|c| c.user.clone());
+ // Same identity rule as the hook ingress, which is the side that
+ // PUBLISHES into this map: keying on `user` here while the router keyed
+ // on the whole qualified identity would put a sub-only proxied
+ // operator's writes in one slot and their reads in another, so
+ // `[auto_scope] per_actor` would silently miss on every read.
+ let user = ctx
+ .and_then(ai_memory_core::ActorContext::identity_key)
+ .map(|key| key.storage_key());
let header_session = |name: &str| {
parts
.headers
@@ -1850,6 +1876,50 @@ impl AiMemoryServer {
}
}
+ /// Ask the admission chain's deciders about an operation that writes no
+ /// page, and hand back the context its observers are owed once the
+ /// operation has actually happened.
+ ///
+ /// The observers are deliberately NOT run here: these tools decide before
+ /// they know whether there is anything to do (an accept may find no
+ /// handoff, a cancel may be refused by ownership), and a mirror told about
+ /// an operation the engine then abandons has been lied to. Pass the context
+ /// to [`Self::notify_operation_observers`] on the success path only — the
+ /// same order the hook ingress uses for the same ops.
+ ///
+ /// A no-op when the server was built without a wiki handle (stdio/tests).
+ async fn authorize_operation(
+ &self,
+ ws: WorkspaceId,
+ proj: ProjectId,
+ op: ai_memory_wiki::AdmissionOp,
+ parts: &axum::http::request::Parts,
+ ) -> Result<Option<ai_memory_wiki::AdmissionContext>, McpError> {
+ let Some(wiki) = self.wiki.as_ref() else {
+ return Ok(None);
+ };
+ // Forward the caller's webhook skip-list, exactly like the write and
+ // admin admission paths do. Dropping it breaks the documented
+ // loop-prevention header: a webhook that reacts to one of these ops by
+ // calling back into the engine would re-trigger itself forever.
+ wiki.authorize_operation(
+ ws,
+ proj,
+ op,
+ crate::actor::actor_from_parts(parts),
+ crate::actor::skip_webhooks_from_parts(parts),
+ )
+ .await
+ .map_err(|e| McpError::invalid_request(e.to_string(), None))
+ }
+
+ /// Fire-and-forget the observer webhooks for an operation that landed.
+ fn notify_operation_observers(&self, ctx: Option<&ai_memory_wiki::AdmissionContext>) {
+ if let (Some(wiki), Some(ctx)) = (self.wiki.as_ref(), ctx) {
+ wiki.notify_operation_observers(ctx);
+ }
+ }
+
/// Does this deployment tell its operators apart?
///
/// "Several operators" is not the same question as "are there `users` rows".
@@ -2660,7 +2730,11 @@ impl AiMemoryServer {
the next agent reads those first; long prose summaries make the \
TUI rendering ugly. `files_touched` is a hint, not exhaustive. \
\
- Use `cwd` to scope the handoff to a specific working directory.")]
+ By default the handoff BELONGS TO YOU: on a server shared by several \
+ operators, a teammate's session will not consume it. Pass \
+ `shared: true` to hand the baton to whoever opens the project next. \
+ `cwd` is recorded for reference; it does not restrict who receives a \
+ handoff created here.")]
async fn memory_handoff_begin(
&self,
Parameters(args): Parameters<HandoffBeginArgs>,
@@ -2706,6 +2780,11 @@ impl AiMemoryServer {
"handoff file",
"handoff files_touched",
);
+ let creator = crate::actor::actor_from_parts(&parts);
+ let distinguishes = self
+ .deployment_distinguishes_operators()
+ .await
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;
let handoff = NewHandoff {
workspace_id: ws,
project_id: proj,
@@ -2721,12 +2800,27 @@ impl AiMemoryServer {
open_questions,
next_steps,
files_touched,
+ // A handoff belongs to whoever created it unless it is explicitly
+ // published. With no actor, or on a deployment that does not tell
+ // its operators apart, this stays None and the handoff is
+ // project-wide, exactly as it behaved before ownership existed —
+ // see [`ai_memory_core::owner_stamp`] for why naming the single
+ // operator would split them across transports.
+ owner_user: if args.shared.unwrap_or(false) {
+ None
+ } else {
+ ai_memory_core::owner_stamp(creator.identity_key().as_ref(), distinguishes)
+ },
};
+ let admission = self
+ .authorize_operation(ws, proj, ai_memory_wiki::AdmissionOp::HandoffBegin, &parts)
+ .await?;
let id = self
.writer
.insert_handoff(handoff)
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
+ self.notify_operation_observers(admission.as_ref());
ok_json(&serde_json::json!({ "handoff_id": id.to_string() }))
}
@@ -2762,20 +2856,68 @@ impl AiMemoryServer {
&aps_actor,
)
.await?;
+ let actor_user = crate::actor::actor_from_parts(&parts)
+ .identity_key()
+ .map(|key| key.storage_key());
+ let owner_filter = if args.any_owner.unwrap_or(false) {
+ // Reading another operator's baton consumes it and hands over text
+ // synthesised from their prompts, so this opt-out is an operator
+ // action — gated exactly like `all_owners` on /admin/open-sessions,
+ // rather than being a free argument any caller can set.
+ self.require_admin_capability(&parts).await?;
+ ai_memory_core::OwnerFilter::Any
+ } else {
+ match actor_user.clone() {
+ Some(key) => ai_memory_core::OwnerFilter::User(key),
+ None => ai_memory_core::OwnerFilter::Unattributed,
+ }
+ };
let receiving_cwd = args.cwd;
let handoff = self
.reader
- .latest_open_handoff(ws, proj, receiving_cwd.clone())
+ .latest_open_handoff(ws, proj, receiving_cwd.clone(), owner_filter.clone())
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
match handoff {
None => ok_json(&serde_json::json!({ "handoff": null })),
Some(h) => {
- self.writer
- .accept_handoff(h.id, AgentKind::Other, None, receiving_cwd)
+ // Admission is asked here, not before the lookup: the routine
+ // outcome of this tool is `{"handoff": null}` — the tool's own
+ // description says so, because the SessionStart hook has
+ // usually already consumed the baton — and asking up front
+ // announces an accept on every one of those calls. A webhook
+ // is only worth asking once there is a handoff to accept.
+ let admission = self
+ .authorize_operation(
+ ws,
+ proj,
+ ai_memory_wiki::AdmissionOp::HandoffAccept,
+ &parts,
+ )
+ .await?;
+ // Deliver the body only when THIS call is the one that claimed
+ // it. The accept is an atomic compare-and-set, so a racing
+ // session (or a caller the owner does not admit) gets `false`
+ // here; returning the handoff anyway would hand the same baton
+ // to two agents.
+ let claimed = self
+ .writer
+ .accept_handoff(
+ h.id,
+ AgentKind::Other,
+ None,
+ actor_user.clone(),
+ owner_filter,
+ receiving_cwd,
+ )
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
- ok_json(&serde_json::json!({ "handoff": h }))
+ if claimed {
+ self.notify_operation_observers(admission.as_ref());
+ ok_json(&serde_json::json!({ "handoff": h }))
+ } else {
+ ok_json(&serde_json::json!({ "handoff": null }))
+ }
}
}
}
@@ -2823,16 +2965,46 @@ impl AiMemoryServer {
"state": handoff.state.as_str(),
}));
}
+ // Cancelling is scoped the same way as accepting: you can discard your
+ // own handoff or one published to the project, not a teammate's — with
+ // the same admin-gated opt-out, so a handoff whose owner no longer
+ // matches any reachable identity (renamed root_username, a stdio
+ // caller, a departed teammate) stays cancellable instead of becoming
+ // permanently stuck.
+ //
+ // Resolved BEFORE the chain is consulted, the order
+ // `memory_handoff_accept` uses: a caller refused this escape hatch has
+ // no operation to admit, so the server must not POST one out to every
+ // reject-policy webhook on their behalf.
+ let cancel_owner_filter = if args.any_owner.unwrap_or(false) {
+ self.require_admin_capability(&parts).await?;
+ ai_memory_core::OwnerFilter::Any
+ } else {
+ ai_memory_core::OwnerFilter::for_actor_context(&crate::actor::actor_from_parts(&parts))
+ };
+ let admission = self
+ .authorize_operation(ws, proj, ai_memory_wiki::AdmissionOp::HandoffCancel, &parts)
+ .await?;
let cancelled = self
.writer
- .cancel_handoff(handoff_id)
+ .cancel_handoff(handoff_id, cancel_owner_filter)
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
- ok_json(&serde_json::json!({
+ if cancelled {
+ self.notify_operation_observers(admission.as_ref());
+ }
+ let mut result = serde_json::json!({
"handoff_id": handoff_id.to_string(),
"cancelled": cancelled,
"state": if cancelled { "expired" } else { "open" },
- }))
+ });
+ if !cancelled && handoff.owner_user.is_some() {
+ // Otherwise this reads as a plain no-op and the caller cannot tell
+ // that ownership is what refused it.
+ result["reason"] =
+ serde_json::json!("handoff belongs to another operator; retry with any_owner=true");
+ }
+ ok_json(&result)
}
/// Report aggregate counts (pages, sessions, observations).
@@ -2888,7 +3060,14 @@ impl AiMemoryServer {
.await?;
let snapshot = self
.reader
- .briefing_for_project(ws, proj, limit)
+ .briefing_for_project(
+ ws,
+ proj,
+ limit,
+ ai_memory_core::OwnerFilter::for_actor_context(&crate::actor::actor_from_parts(
+ &parts,
+ )),
+ )
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
ok_json(&snapshot)
@@ -2924,7 +3103,14 @@ impl AiMemoryServer {
.await?;
let snapshot = self
.reader
- .briefing_for_project(ws, proj, limit)
+ .briefing_for_project(
+ ws,
+ proj,
+ limit,
+ ai_memory_core::OwnerFilter::for_actor_context(&crate::actor::actor_from_parts(
+ &parts,
+ )),
+ )
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
@@ -3459,7 +3645,9 @@ mod tests {
assert_eq!(
AiMemoryServer::actor_key_from_parts(Some(&parts)),
ai_memory_core::ActorKey {
- user: Some("alice".into()),
+ // Qualified: the same storage key the hook ingress publishes
+ // under, so set and get land on the same slot.
+ user: Some("user:alice".into()),
session_id: Some("session-from-header".into()),
},
"real HTTP request parts must preserve auth identity and routing session"
@@ -3883,6 +4071,7 @@ mod tests {
project_id,
agent_kind: AgentKind::OpenCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -3992,7 +4181,9 @@ mod tests {
let actor = AiMemoryServer::actor_key_from_parts(Some(&parts));
- assert_eq!(actor.user.as_deref(), Some("alice"));
+ // The map is keyed by the QUALIFIED identity — the same storage key
+ // the hook ingress publishes under — never the raw username.
+ assert_eq!(actor.user.as_deref(), Some("user:alice"));
assert_eq!(actor.session_id.as_deref(), Some("context-session"));
}
@@ -5548,6 +5739,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::OpenCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -5622,6 +5814,7 @@ mod tests {
project_id: scoped,
agent_kind: AgentKind::OpenCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -7587,6 +7780,7 @@ mod tests {
cwd: Some(r"C:\GIT\ai-memory".into()),
project: None,
workspace: None,
+ shared: None,
}),
OptionalParts(test_parts_default()),
)
@@ -7629,6 +7823,7 @@ mod tests {
cwd: Some("/tmp/aim".into()),
project: None,
workspace: None,
+ shared: None,
}),
OptionalParts(test_parts_default()),
)
@@ -7649,6 +7844,7 @@ mod tests {
cwd: Some("/tmp/aim".into()),
project: None,
workspace: None,
+ any_owner: None,
}),
OptionalParts(test_parts_default()),
)
@@ -7670,6 +7866,7 @@ mod tests {
cwd: Some("/tmp/aim".into()),
project: None,
workspace: None,
+ any_owner: None,
}),
OptionalParts(test_parts_default()),
)
@@ -7697,6 +7894,7 @@ mod tests {
cwd: Some("/tmp/aim".into()),
project: None,
workspace: None,
+ shared: None,
}),
OptionalParts(test_parts_default()),
)
@@ -7709,6 +7907,7 @@ mod tests {
cwd: Some("/tmp/aim".into()),
project: None,
workspace: None,
+ any_owner: None,
}),
OptionalParts(test_parts_default()),
)
@@ -7741,6 +7940,7 @@ mod tests {
cwd: Some("/tmp/aim".into()),
project: None,
workspace: None,
+ shared: None,
}),
OptionalParts(test_parts_default()),
)
@@ -7753,6 +7953,7 @@ mod tests {
cwd: Some("/tmp/aim".into()),
project: None,
workspace: None,
+ any_owner: None,
}),
OptionalParts(test_parts_default()),
)
@@ -7800,6 +8001,7 @@ mod tests {
cwd: None,
project: Some("sibling-app".into()),
workspace: Some("djalmajr".into()),
+ shared: None,
}),
OptionalParts(test_parts_default()),
)
@@ -7813,6 +8015,7 @@ mod tests {
cwd: None,
project: None,
workspace: None,
+ any_owner: None,
}),
OptionalParts(test_parts_default()),
)
@@ -7836,6 +8039,7 @@ mod tests {
cwd: None,
project: Some("sibling-app".into()),
workspace: Some("djalmajr".into()),
+ any_owner: None,
}),
OptionalParts(test_parts_default()),
)
@@ -7866,6 +8070,7 @@ mod tests {
cwd: Some("/tmp/aim".into()),
project: None,
workspace: None,
+ shared: None,
}),
OptionalParts(test_parts_default()),
)
@@ -7905,6 +8110,7 @@ mod tests {
handoff_id: handoff_id.clone(),
project: None,
workspace: None,
+ any_owner: None,
}),
OptionalParts(test_parts_default()),
)
@@ -7944,6 +8150,7 @@ mod tests {
cwd: Some("/tmp/aim".into()),
project: None,
workspace: None,
+ any_owner: None,
}),
OptionalParts(test_parts_default()),
)
@@ -8196,6 +8403,7 @@ mod tests {
cwd: None,
project: None,
workspace: None,
+ any_owner: None,
}),
OptionalParts(test_parts_default()),
)
diff --git a/crates/ai-memory-mcp/tests/admin_move.rs b/crates/ai-memory-mcp/tests/admin_move.rs
index 022b71a0..349d2223 100644
--- a/crates/ai-memory-mcp/tests/admin_move.rs
+++ b/crates/ai-memory-mcp/tests/admin_move.rs
@@ -598,6 +598,7 @@ async fn move_project_true_move_preserves_sessions_and_observations() {
project_id: src_proj,
agent_kind: AgentKind::ClaudeCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
diff --git a/crates/ai-memory-mcp/tests/admin_phase3.rs b/crates/ai-memory-mcp/tests/admin_phase3.rs
index 55577880..ae34fb93 100644
--- a/crates/ai-memory-mcp/tests/admin_phase3.rs
+++ b/crates/ai-memory-mcp/tests/admin_phase3.rs
@@ -342,6 +342,7 @@ async fn seed_sessions_for_reorg(store: &Store) -> (SessionId, SessionId) {
project_id: scratch,
agent_kind: AgentKind::ClaudeCode,
cwd: Some(std::path::PathBuf::from("/home/user/alpha-repo")),
+ actor_user: None,
})
.await
.unwrap();
@@ -373,6 +374,7 @@ async fn seed_sessions_for_reorg(store: &Store) -> (SessionId, SessionId) {
project_id: scratch,
agent_kind: AgentKind::ClaudeCode,
cwd: Some(std::path::PathBuf::from("/home/user/beta-repo")),
+ actor_user: None,
})
.await
.unwrap();
diff --git a/crates/ai-memory-mcp/tests/admin_purge.rs b/crates/ai-memory-mcp/tests/admin_purge.rs
index a279c9f0..d28cb931 100644
--- a/crates/ai-memory-mcp/tests/admin_purge.rs
+++ b/crates/ai-memory-mcp/tests/admin_purge.rs
@@ -135,6 +135,7 @@ async fn seed_two_projects(store: &Store, wiki: &Wiki) -> (WorkspaceId, ProjectI
project_id: proj,
agent_kind: AgentKind::ClaudeCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -173,6 +174,7 @@ async fn seed_two_projects(store: &Store, wiki: &Wiki) -> (WorkspaceId, ProjectI
open_questions: vec![],
next_steps: vec![],
files_touched: vec![],
+ owner_user: None,
})
.await
.unwrap();
diff --git a/crates/ai-memory-mcp/tests/autoscope_multiuser.rs b/crates/ai-memory-mcp/tests/autoscope_multiuser.rs
index 8fa9e59e..ce31d949 100644
--- a/crates/ai-memory-mcp/tests/autoscope_multiuser.rs
+++ b/crates/ai-memory-mcp/tests/autoscope_multiuser.rs
@@ -168,6 +168,7 @@ impl MultiUserHarness {
ai_memory_hooks::IngestRateLimiter::disabled(),
)),
home_dir: None,
+ trusted_proxy_identity: false,
});
// Production-equivalent Bearer middleware. Pepper + reader are
diff --git a/crates/ai-memory-mcp/tests/autoscope_stress.rs b/crates/ai-memory-mcp/tests/autoscope_stress.rs
index b35bd7ab..ed113cab 100644
--- a/crates/ai-memory-mcp/tests/autoscope_stress.rs
+++ b/crates/ai-memory-mcp/tests/autoscope_stress.rs
@@ -167,6 +167,7 @@ impl Harness {
ai_memory_hooks::IngestRateLimiter::disabled(),
)),
home_dir: None,
+ trusted_proxy_identity: false,
});
let router = Router::new()
diff --git a/crates/ai-memory-mcp/tests/handoff_admission.rs b/crates/ai-memory-mcp/tests/handoff_admission.rs
new file mode 100644
index 00000000..f6e7ee77
--- /dev/null
+++ b/crates/ai-memory-mcp/tests/handoff_admission.rs
@@ -0,0 +1,433 @@
+//! The MCP handoff tools and the admission chain.
+//!
+//! Handoff ops carry no page and no body, so the chain has nothing to mutate:
+//! the only reason to run a webhook BEFORE the operation is that it can refuse
+//! it. Everything else is an observer, and an observer is owed the truth — it
+//! must hear about a handoff that was actually created or claimed, and about
+//! nothing else. `memory_handoff_accept` is the sharp case: its routine answer
+//! is `{"handoff": null}` (the SessionStart hook has usually already consumed
+//! the baton), so announcing the accept up front tells a mirror about accepts
+//! that never happen, on most calls.
+//!
+//! These tests drive the tools through the production JSON-RPC transport, the
+//! same way `autoscope_multiuser.rs` does, and point the chain at a real
+//! webhook host that records every request it receives.
+
+use ai_memory_mcp::AiMemoryServer;
+use ai_memory_mcp::auth::{AuthState, require_bearer};
+use ai_memory_store::Store;
+use ai_memory_wiki::Wiki;
+use axum::Router;
+use axum::body::Body;
+use axum::http::{Request, StatusCode};
+use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
+use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
+use serde_json::json;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+use tempfile::TempDir;
+use tower::ServiceExt;
+
+/// One recorded webhook request: which hook was called, for which op.
+type Calls = Arc<Mutex<Vec<(String, String)>>>;
+
+/// A webhook host with one route per hook, answering `204` and recording the
+/// `X-Memory-Op` header it was called with.
+async fn recording_webhook_host() -> (std::net::SocketAddr, Calls) {
+ let calls: Calls = Arc::new(Mutex::new(Vec::new()));
+ let mut app = axum::Router::new();
+ for hook in ["guard", "mirror", "observer"] {
+ let seen = calls.clone();
+ app = app.route(
+ &format!("/{hook}"),
+ axum::routing::post(move |headers: axum::http::HeaderMap| {
+ let seen = seen.clone();
+ async move {
+ let op = headers
+ .get("x-memory-op")
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("")
+ .to_string();
+ seen.lock().unwrap().push((hook.to_string(), op));
+ StatusCode::NO_CONTENT
+ }
+ }),
+ );
+ }
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+ (addr, calls)
+}
+
+fn hook(
+ name: &str,
+ addr: std::net::SocketAddr,
+ blocking: bool,
+ events: Vec<ai_memory_wiki::AdmissionOp>,
+) -> ai_memory_wiki::WebhookConfig {
+ ai_memory_wiki::WebhookConfig {
+ name: name.to_string(),
+ url: format!("http://{addr}/{name}"),
+ timeout_ms: 2_000,
+ failure_policy: ai_memory_wiki::FailurePolicy::Ignore,
+ events,
+ blocking,
+ }
+}
+
+/// The one shape that decides: `blocking` + `reject`, the hook the engine
+/// awaits BEFORE the operation. It is the only one an unauthorised call can
+/// reach, since the observers are dispatched afterwards.
+fn deciding_hook(
+ name: &str,
+ addr: std::net::SocketAddr,
+ events: Vec<ai_memory_wiki::AdmissionOp>,
+) -> ai_memory_wiki::WebhookConfig {
+ ai_memory_wiki::WebhookConfig {
+ failure_policy: ai_memory_wiki::FailurePolicy::Reject,
+ ..hook(name, addr, true, events)
+ }
+}
+
+fn handoff_ops() -> Vec<ai_memory_wiki::AdmissionOp> {
+ vec![
+ ai_memory_wiki::AdmissionOp::HandoffBegin,
+ ai_memory_wiki::AdmissionOp::HandoffAccept,
+ ai_memory_wiki::AdmissionOp::HandoffCancel,
+ ]
+}
+
+/// A blocking observer (`ignore` policy, so it decides nothing) plus a
+/// non-blocking one — the two shapes an operator writes when they mean
+/// "tell me, don't ask me".
+fn observer_chain(addr: std::net::SocketAddr) -> ai_memory_wiki::AdmissionChain {
+ let events = handoff_ops();
+ ai_memory_wiki::AdmissionChain::new(vec![
+ hook("mirror", addr, true, events.clone()),
+ hook("observer", addr, false, events),
+ ])
+ .unwrap()
+}
+
+/// The observers plus a decider, for the calls that must reach neither.
+fn guarded_chain(addr: std::net::SocketAddr) -> ai_memory_wiki::AdmissionChain {
+ let events = handoff_ops();
+ ai_memory_wiki::AdmissionChain::new(vec![
+ deciding_hook("guard", addr, events.clone()),
+ hook("mirror", addr, true, events.clone()),
+ hook("observer", addr, false, events),
+ ])
+ .unwrap()
+}
+
+const ROOT_TOKEN: &str = "the-root-token";
+const PROXY_SECRET: &str = "proxy-shared-secret";
+
+struct Harness {
+ router: Router,
+ store: Store,
+ ws: ai_memory_core::WorkspaceId,
+ proj: ai_memory_core::ProjectId,
+ _tmp: TempDir,
+}
+
+async fn harness(chain: ai_memory_wiki::AdmissionChain) -> Harness {
+ build_harness(chain, false).await
+}
+
+/// The same server behind the production `require_bearer` layer with
+/// `[auth].actor_proxy_secret` configured: the only configuration in which a
+/// caller can be BOTH named and non-admin, and therefore the only one where the
+/// `any_owner` gate has anybody to refuse.
+async fn proxied_harness(chain: ai_memory_wiki::AdmissionChain) -> Harness {
+ build_harness(chain, true).await
+}
+
+async fn build_harness(chain: ai_memory_wiki::AdmissionChain, proxy_auth: bool) -> Harness {
+ let tmp = TempDir::new().expect("tempdir");
+ let store = Store::open(tmp.path()).expect("store");
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .expect("ws");
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .expect("proj");
+ let wiki = Wiki::new(tmp.path(), store.writer.clone())
+ .expect("wiki")
+ .with_admission_chain(chain);
+
+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)
+ .with_wiki(wiki.clone())
+ .with_trusted_proxy_identity(proxy_auth);
+ let mcp_service = StreamableHttpService::new(
+ move || Ok(server.clone()),
+ LocalSessionManager::default().into(),
+ StreamableHttpServerConfig::default()
+ .with_stateful_mode(false)
+ .with_json_response(true),
+ );
+ let mut router = Router::new().nest_service("/mcp", mcp_service);
+ if proxy_auth {
+ let auth_state = AuthState::new(Some(ROOT_TOKEN.to_string()))
+ .with_root_actor(ai_memory_core::ActorContext {
+ user: Some("dj".to_string()),
+ ..ai_memory_core::ActorContext::default()
+ })
+ .with_trusted_proxy(PROXY_SECRET);
+ router = router.layer(axum::middleware::from_fn_with_state(
+ Arc::new(auth_state),
+ require_bearer,
+ ));
+ }
+ Harness {
+ router,
+ store,
+ ws,
+ proj,
+ _tmp: tmp,
+ }
+}
+
+/// Headers a trusted proxy sends for a named, non-root end user.
+fn proxied_as(user: &'static str) -> Vec<(&'static str, &'static str)> {
+ vec![
+ ("authorization", "Bearer the-root-token"),
+ ("x-memory-actor-proxy-secret", PROXY_SECRET),
+ ("x-memory-actor-user", user),
+ ]
+}
+
+/// The raw JSON-RPC envelope, so a test can assert on a rejection.
+async fn call_tool_raw(
+ router: &Router,
+ name: &str,
+ arguments: serde_json::Value,
+ headers: &[(&str, &str)],
+) -> serde_json::Value {
+ let body = json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": { "name": name, "arguments": arguments },
+ });
+ let mut req = Request::builder()
+ .method("POST")
+ .uri("/mcp")
+ .header("host", "localhost")
+ .header("content-type", "application/json")
+ .header("accept", "application/json, text/event-stream");
+ for (k, v) in headers {
+ req = req.header(*k, *v);
+ }
+ let resp = router
+ .clone()
+ .oneshot(req.body(Body::from(body.to_string())).expect("mcp req"))
+ .await
+ .expect("oneshot");
+ let bytes = axum::body::to_bytes(resp.into_body(), 4_000_000)
+ .await
+ .expect("body");
+ let text = String::from_utf8(bytes.to_vec()).expect("utf8");
+ serde_json::from_str(&text).unwrap_or_else(|e| panic!("non-JSON: {text}\nerr: {e}"))
+}
+
+async fn call_tool(router: &Router, name: &str, arguments: serde_json::Value) -> serde_json::Value {
+ let v = call_tool_raw(router, name, arguments, &[]).await;
+ if let Some(err) = v.get("error") {
+ panic!("JSON-RPC error: {err}\nfull: {v}");
+ }
+ let joined = v
+ .pointer("/result/content")
+ .and_then(|c| c.as_array())
+ .unwrap_or_else(|| panic!("missing result.content: {v}"))
+ .iter()
+ .filter_map(|i| i.get("text").and_then(|t| t.as_str()))
+ .collect::<Vec<_>>()
+ .join("\n");
+ serde_json::from_str(&joined).unwrap_or_else(|e| panic!("tool text not JSON: {joined}: {e}"))
+}
+
+/// Observer dispatch is fire-and-forget, so give a wrongly-spawned call time to
+/// land before asserting that nothing was called.
+async fn settle() {
+ tokio::time::sleep(Duration::from_millis(300)).await;
+}
+
+async fn wait_for(calls: &Calls, want: (&str, &str)) {
+ let deadline = std::time::Instant::now() + Duration::from_secs(5);
+ loop {
+ let seen = calls.lock().unwrap().clone();
+ if seen.iter().any(|(hook, op)| hook == want.0 && op == want.1) {
+ return;
+ }
+ assert!(
+ std::time::Instant::now() < deadline,
+ "webhook {want:?} was never called; saw {seen:?}",
+ );
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+}
+
+/// The routine `memory_handoff_accept` call finds nothing to accept. No webhook
+/// may be told that an accept happened, because none did.
+#[tokio::test]
+async fn accept_with_nothing_pending_tells_no_webhook() {
+ let (addr, calls) = recording_webhook_host().await;
+ let h = harness(observer_chain(addr)).await;
+
+ let result = call_tool(
+ &h.router,
+ "memory_handoff_accept",
+ json!({ "workspace": "default", "project": "scratch" }),
+ )
+ .await;
+ assert_eq!(
+ result,
+ json!({ "handoff": null }),
+ "nothing was pending, so nothing is accepted",
+ );
+
+ settle().await;
+ assert!(
+ calls.lock().unwrap().is_empty(),
+ "an accept that found no handoff must reach no webhook: {:?}",
+ calls.lock().unwrap(),
+ );
+}
+
+/// The other half, and the consistency rule: for an op that DID happen, both
+/// observer shapes are notified — the blocking-but-undeciding one and the
+/// non-blocking one an operator writes to say "off the critical path".
+#[tokio::test]
+async fn begin_and_accept_notify_both_observer_shapes_once_they_land() {
+ let (addr, calls) = recording_webhook_host().await;
+ let h = harness(observer_chain(addr)).await;
+
+ let begun = call_tool(
+ &h.router,
+ "memory_handoff_begin",
+ json!({
+ "workspace": "default",
+ "project": "scratch",
+ "summary": "where the session left off",
+ "shared": true,
+ }),
+ )
+ .await;
+ assert!(
+ begun.get("handoff_id").is_some(),
+ "handoff created: {begun}"
+ );
+ wait_for(&calls, ("mirror", "handoff_begin")).await;
+ wait_for(&calls, ("observer", "handoff_begin")).await;
+
+ let accepted = call_tool(
+ &h.router,
+ "memory_handoff_accept",
+ json!({ "workspace": "default", "project": "scratch" }),
+ )
+ .await;
+ assert!(
+ accepted
+ .pointer("/handoff/summary")
+ .and_then(|s| s.as_str())
+ .is_some_and(|s| s.contains("where the session left off")),
+ "the pending baton is delivered: {accepted}",
+ );
+ wait_for(&calls, ("mirror", "handoff_accept")).await;
+ wait_for(&calls, ("observer", "handoff_accept")).await;
+
+ settle().await;
+ let seen = calls.lock().unwrap().clone();
+ assert_eq!(
+ seen.len(),
+ 4,
+ "each landed op is announced exactly once per subscriber: {seen:?}",
+ );
+}
+
+/// A cross-owner `memory_handoff_cancel` from a caller without the capability
+/// for it is not an operation, so the chain must not hear about it — not even
+/// the decider, which sits in front. `memory_handoff_accept` already authorises
+/// its `any_owner` before asking; the cancel path is the sibling.
+#[tokio::test]
+async fn unauthorised_any_owner_cancel_reaches_no_webhook() {
+ let (addr, calls) = recording_webhook_host().await;
+ let h = proxied_harness(guarded_chain(addr)).await;
+
+ // Inserted directly: creating it through the tool would put a legitimate
+ // `handoff_begin` in the recording, and what is under test is that the
+ // refused cancel adds nothing to it.
+ let id = h
+ .store
+ .writer
+ .insert_handoff(ai_memory_core::NewHandoff {
+ workspace_id: h.ws,
+ project_id: h.proj,
+ from_session_id: None,
+ from_agent: ai_memory_core::AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: None,
+ summary: "bobs-baton".to_string(),
+ open_questions: Vec::new(),
+ next_steps: Vec::new(),
+ files_touched: Vec::new(),
+ // Stamped through the contract, as the tool would: owners are
+ // qualified storage keys, never raw names.
+ owner_user: ai_memory_core::owner_stamp(
+ Some(&ai_memory_core::IdentityKey::User("bob".into())),
+ true,
+ ),
+ })
+ .await
+ .expect("insert handoff");
+
+ let response = call_tool_raw(
+ &h.router,
+ "memory_handoff_cancel",
+ json!({
+ "workspace": "default",
+ "project": "scratch",
+ "handoff_id": id.to_string(),
+ "any_owner": true,
+ }),
+ &proxied_as("alice"),
+ )
+ .await;
+ // The message is asserted, not merely the presence of an error: a rejection
+ // from the auth layer itself would also produce one, and would make this
+ // test pass without the capability gate ever running.
+ let message = response
+ .pointer("/error/message")
+ .and_then(|m| m.as_str())
+ .unwrap_or_else(|| panic!("a non-admin caller must be refused any_owner: {response}"));
+ assert!(
+ message.contains("admin"),
+ "expected the admin capability gate to refuse this, got: {message}",
+ );
+
+ settle().await;
+ assert!(
+ calls.lock().unwrap().is_empty(),
+ "an operation the caller was never permitted must reach no webhook: {:?}",
+ calls.lock().unwrap(),
+ );
+ assert_eq!(
+ h.store
+ .reader
+ .handoff_by_id(id)
+ .await
+ .expect("read back")
+ .expect("row still there")
+ .state,
+ ai_memory_core::HandoffState::Open,
+ "the refused cancel must not have discarded the baton",
+ );
+}
diff --git a/crates/ai-memory-mcp/tests/handoff_identity.rs b/crates/ai-memory-mcp/tests/handoff_identity.rs
new file mode 100644
index 00000000..862e2ce5
--- /dev/null
+++ b/crates/ai-memory-mcp/tests/handoff_identity.rs
@@ -0,0 +1,329 @@
+//! Who a request names, and what that means for a handoff's owner.
+//!
+//! Two independent decisions have to agree or a baton lands somewhere its
+//! author cannot reach:
+//!
+//! 1. **Which field names the human.** The auth middleware resolves a proxy
+//! that asserts only an OIDC subject claim to `AuthLevel::User` — it named
+//! somebody. If ownership keys on `actor.user` alone, that same request is
+//! "nobody" when a row is stamped, so every operator behind such a proxy
+//! writes into the one shared bucket and reads each other's prompt trails.
+//! 2. **Whether the deployment tells operators apart at all.** A server with
+//! `[auth].bearer_token` + `[auth].root_username`, no `users` rows and no
+//! proxy has exactly one operator, but two transports: HTTP requests carry
+//! that one name, while the local stdio / in-process transport carries no
+//! actor. Stamping the name splits one person in half — what they write
+//! over HTTP becomes invisible to their own local CLI on the same data
+//! directory.
+//!
+//! These drive the real tools through the production JSON-RPC transport with
+//! the production `require_bearer` middleware in front, so the rungs under test
+//! are the ones an operator actually configures.
+
+use ai_memory_core::ActorContext;
+use ai_memory_mcp::AiMemoryServer;
+use ai_memory_mcp::auth::{AuthState, require_bearer};
+use ai_memory_store::Store;
+use ai_memory_wiki::Wiki;
+use axum::Router;
+use axum::body::Body;
+use axum::http::Request;
+use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
+use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
+use serde_json::{Value, json};
+use std::sync::Arc;
+use tempfile::TempDir;
+use tower::ServiceExt;
+
+const ROOT_TOKEN: &str = "the-root-token";
+const PROXY_SECRET: &str = "proxy-shared-secret";
+
+struct Harness {
+ /// The HTTP transport: production `require_bearer` in front of `/mcp`.
+ http: Router,
+ /// The stdio / in-process transport, modelled as the SAME server mounted
+ /// with no auth layer at all — a call therefore carries neither an
+ /// `ActorContext` nor an `AuthLevel`, which is exactly what a local
+ /// `ai-memory` process or an editor's stdio MCP client produces.
+ local: Router,
+ store: Store,
+ ws: ai_memory_core::WorkspaceId,
+ proj: ai_memory_core::ProjectId,
+ _tmp: TempDir,
+}
+
+fn mount(server: AiMemoryServer) -> Router {
+ let service = StreamableHttpService::new(
+ move || Ok(server.clone()),
+ LocalSessionManager::default().into(),
+ StreamableHttpServerConfig::default()
+ .with_stateful_mode(false)
+ .with_json_response(true),
+ );
+ Router::new().nest_service("/mcp", service)
+}
+
+/// `root_username` is `[auth].root_username`; `proxy` is
+/// `[auth].actor_proxy_secret`, which is also what makes the deployment
+/// distinguish operators without ever writing a `users` row.
+async fn harness(root_username: Option<&str>, proxy: bool) -> Harness {
+ let tmp = TempDir::new().expect("tempdir");
+ let store = Store::open(tmp.path()).expect("store");
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .expect("ws");
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .expect("proj");
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).expect("wiki");
+
+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)
+ .with_wiki(wiki)
+ .with_trusted_proxy_identity(proxy);
+
+ let mut auth_state = AuthState::new(Some(ROOT_TOKEN.to_string()));
+ if let Some(user) = root_username {
+ auth_state = auth_state.with_root_actor(ActorContext {
+ user: Some(user.to_string()),
+ ..ActorContext::default()
+ });
+ }
+ if proxy {
+ auth_state = auth_state.with_trusted_proxy(PROXY_SECRET);
+ }
+ let http = mount(server.clone()).layer(axum::middleware::from_fn_with_state(
+ Arc::new(auth_state),
+ require_bearer,
+ ));
+
+ Harness {
+ http,
+ local: mount(server),
+ store,
+ ws,
+ proj,
+ _tmp: tmp,
+ }
+}
+
+async fn call(router: &Router, name: &str, arguments: Value, headers: &[(&str, &str)]) -> Value {
+ let body = json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": { "name": name, "arguments": arguments },
+ });
+ let mut req = Request::builder()
+ .method("POST")
+ .uri("/mcp")
+ .header("host", "localhost")
+ .header("content-type", "application/json")
+ .header("accept", "application/json, text/event-stream");
+ for (k, v) in headers {
+ req = req.header(*k, *v);
+ }
+ let resp = router
+ .clone()
+ .oneshot(req.body(Body::from(body.to_string())).expect("mcp req"))
+ .await
+ .expect("oneshot");
+ let bytes = axum::body::to_bytes(resp.into_body(), 4_000_000)
+ .await
+ .expect("body");
+ let text = String::from_utf8(bytes.to_vec()).expect("utf8");
+ let v: Value = serde_json::from_str(&text).unwrap_or_else(|e| panic!("non-JSON: {text}: {e}"));
+ if let Some(err) = v.get("error") {
+ panic!("JSON-RPC error: {err}\nfull: {text}");
+ }
+ let joined = v
+ .pointer("/result/content")
+ .and_then(|c| c.as_array())
+ .unwrap_or_else(|| panic!("missing result.content: {text}"))
+ .iter()
+ .filter_map(|i| i.get("text").and_then(|t| t.as_str()))
+ .collect::<Vec<_>>()
+ .join("\n");
+ serde_json::from_str(&joined).unwrap_or_else(|e| panic!("tool text not JSON: {joined}: {e}"))
+}
+
+fn root_headers() -> Vec<(&'static str, &'static str)> {
+ vec![("authorization", "Bearer the-root-token")]
+}
+
+fn proxied(header: &'static str, value: &'static str) -> Vec<(&'static str, &'static str)> {
+ vec![
+ ("authorization", "Bearer the-root-token"),
+ ("x-memory-actor-proxy-secret", PROXY_SECRET),
+ (header, value),
+ ]
+}
+
+async fn begin(router: &Router, summary: &str, headers: &[(&str, &str)]) {
+ let begun = call(
+ router,
+ "memory_handoff_begin",
+ json!({ "workspace": "default", "project": "scratch", "summary": summary }),
+ headers,
+ )
+ .await;
+ assert!(
+ begun.get("handoff_id").is_some(),
+ "handoff not created: {begun}"
+ );
+}
+
+/// The accepted handoff's summary, or `None` when the caller was shown nothing.
+async fn accept(router: &Router, headers: &[(&str, &str)]) -> Option<String> {
+ let got = call(
+ router,
+ "memory_handoff_accept",
+ json!({ "workspace": "default", "project": "scratch" }),
+ headers,
+ )
+ .await;
+ got.pointer("/handoff/summary")
+ .and_then(|s| s.as_str())
+ .map(str::to_owned)
+}
+
+/// A single-operator server that happens to name its operator: one person, one
+/// data directory, two transports. What the HTTP side writes must stay visible
+/// to the local one, because there is nobody else it could belong to.
+#[tokio::test]
+async fn single_operator_handoff_crosses_between_http_and_local_transports() {
+ let h = harness(Some("dj"), false).await;
+
+ begin(&h.http, "the-http-baton", &root_headers()).await;
+
+ assert_eq!(
+ accept(&h.local, &[]).await.as_deref(),
+ Some("the-http-baton"),
+ "the operator's own local transport cannot see what they wrote over HTTP",
+ );
+}
+
+/// …and the row itself carries no owner, so it is shared exactly as it was
+/// before ownership existed. Pins the stamp, not just the read that follows it.
+#[tokio::test]
+async fn single_operator_handoff_is_stamped_shared() {
+ let h = harness(Some("dj"), false).await;
+
+ begin(&h.http, "the-http-baton", &root_headers()).await;
+
+ let rows = h
+ .store
+ .reader
+ .list_handoffs(h.ws, h.proj, None, ai_memory_core::OwnerFilter::Any, 10)
+ .await
+ .expect("list");
+ assert_eq!(rows.len(), 1);
+ assert_eq!(
+ rows[0].owner_user, None,
+ "a deployment that separates nobody must stamp nobody",
+ );
+}
+
+/// An ingress that terminates OIDC and forwards only the subject claim names a
+/// human — the auth layer already resolves it to `AuthLevel::User`. Ownership
+/// has to agree, or every proxied operator shares one bucket and reads batons
+/// synthesised from a colleague's prompts.
+#[tokio::test]
+async fn sub_only_proxy_operators_do_not_share_a_bucket() {
+ let h = harness(Some("dj"), true).await;
+
+ begin(
+ &h.http,
+ "alices-baton",
+ &proxied("x-memory-actor-sub", "oidc-subject-alice"),
+ )
+ .await;
+
+ assert_eq!(
+ accept(&h.http, &proxied("x-memory-actor-sub", "oidc-subject-bob")).await,
+ None,
+ "a second proxied operator consumed a baton asserted for somebody else",
+ );
+ assert_eq!(
+ accept(
+ &h.http,
+ &proxied("x-memory-actor-sub", "oidc-subject-alice")
+ )
+ .await
+ .as_deref(),
+ Some("alices-baton"),
+ "the operator who created the baton must still be able to claim it",
+ );
+}
+
+/// The named-user rung of the same rule, unchanged: two operators a deployment
+/// really does tell apart stay isolated from each other.
+#[tokio::test]
+async fn named_proxy_operators_stay_isolated() {
+ let h = harness(Some("dj"), true).await;
+
+ begin(
+ &h.http,
+ "alices-baton",
+ &proxied("x-memory-actor-user", "alice"),
+ )
+ .await;
+
+ assert_eq!(
+ accept(&h.http, &proxied("x-memory-actor-user", "bob")).await,
+ None,
+ "bob claimed alice's baton",
+ );
+ assert_eq!(
+ accept(&h.http, &proxied("x-memory-actor-user", "alice"))
+ .await
+ .as_deref(),
+ Some("alices-baton"),
+ );
+}
+
+/// Absent = shared. A handoff with no owner — every row written before
+/// ownership existed, and everything an unattributed caller writes — stays
+/// visible to every reader in every mode, named or not.
+#[tokio::test]
+async fn legacy_unowned_handoffs_stay_visible_to_everyone() {
+ let h = harness(Some("dj"), true).await;
+ for i in 0..3 {
+ h.store
+ .writer
+ .insert_handoff(ai_memory_core::NewHandoff {
+ workspace_id: h.ws,
+ project_id: h.proj,
+ from_session_id: None,
+ from_agent: ai_memory_core::AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: None,
+ summary: format!("legacy-baton-{i}"),
+ open_questions: Vec::new(),
+ next_steps: Vec::new(),
+ files_touched: Vec::new(),
+ owner_user: None,
+ })
+ .await
+ .expect("insert legacy handoff");
+ }
+
+ for (label, headers) in [
+ ("named proxy user", proxied("x-memory-actor-user", "alice")),
+ (
+ "sub-only proxy user",
+ proxied("x-memory-actor-sub", "oidc-subject-bob"),
+ ),
+ ("root with no assertion", root_headers()),
+ ] {
+ assert!(
+ accept(&h.http, &headers)
+ .await
+ .is_some_and(|s| s.starts_with("legacy-baton-")),
+ "{label} was refused a handoff that belongs to nobody",
+ );
+ }
+}
diff --git a/crates/ai-memory-store/migrations/V39__handoff_ownership.sql b/crates/ai-memory-store/migrations/V39__handoff_ownership.sql
new file mode 100644
index 00000000..723f9464
--- /dev/null
+++ b/crates/ai-memory-store/migrations/V39__handoff_ownership.sql
@@ -0,0 +1,31 @@
+-- V39: give handoffs an owner so a shared server stops delivering one
+-- operator's baton to another.
+--
+-- Before this, `handoffs` carried no human identity at all: the open-handoff
+-- lookup filtered on (workspace_id, project_id, state) only, and the session
+-- start hook claims whatever it finds. On a single-operator server that is the
+-- intended 1:1 behaviour; with several operators in one project it means the
+-- next session to start — whoever it belongs to — consumes the pending handoff
+-- and the author never receives it.
+--
+-- Additive on purpose:
+-- * Both columns are nullable. Every pre-existing row keeps `owner_user
+-- IS NULL`, which the reader treats as "project-wide / shared" — exactly
+-- the old delivery semantics, so existing deployments see no change.
+-- * A single-operator server whose requests carry no actor keeps writing
+-- NULL owners and keeps behaving as before.
+-- * `ALTER TABLE ... ADD COLUMN` with a NULL default rewrites no rows, so
+-- this is O(1) even on a large table.
+ALTER TABLE handoffs ADD COLUMN owner_user TEXT;
+
+-- Who actually consumed it. `accepted_by` records the accepting AGENT kind
+-- ('claude-code', …), which cannot answer "which teammate took my baton".
+ALTER TABLE handoffs ADD COLUMN accepted_by_user TEXT;
+
+-- The open-handoff lookup is always (workspace, project, state='open') and now
+-- additionally discriminates on owner. Partial index: only open rows are ever
+-- queried this way, and accepted/expired rows are the overwhelming majority
+-- over time.
+CREATE INDEX idx_handoffs_open_owner
+ ON handoffs (workspace_id, project_id, owner_user, created_at DESC)
+ WHERE state = 'open';
diff --git a/crates/ai-memory-store/migrations/V40__session_owner.sql b/crates/ai-memory-store/migrations/V40__session_owner.sql
new file mode 100644
index 00000000..1390ff76
--- /dev/null
+++ b/crates/ai-memory-store/migrations/V40__session_owner.sql
@@ -0,0 +1,18 @@
+-- V40: record which operator a session belongs to.
+--
+-- `sessions` never carried a human identity, so anything that picks "the open
+-- session" for a scope picks somebody else's just as easily as your own. That
+-- is how `finalize-session` could end a teammate's LIVE session, synthesise a
+-- page from their observations, and mint an auto handoff containing their raw
+-- prompts.
+--
+-- Additive and nullable: existing rows and any caller without an authenticated
+-- actor keep `actor_user IS NULL`, which every reader treats as shared — the
+-- pre-ownership behaviour a single-operator server depends on.
+ALTER TABLE sessions ADD COLUMN actor_user TEXT;
+
+-- Open-session lookups are (workspace, project, agent_kind, ended_at IS NULL)
+-- and now additionally discriminate on the owner.
+CREATE INDEX idx_sessions_open_owner
+ ON sessions (workspace_id, project_id, agent_kind, actor_user)
+ WHERE ended_at IS NULL;
diff --git a/crates/ai-memory-store/migrations/V41__handoffs_listing_index.sql b/crates/ai-memory-store/migrations/V41__handoffs_listing_index.sql
new file mode 100644
index 00000000..f4f15ff6
--- /dev/null
+++ b/crates/ai-memory-store/migrations/V41__handoffs_listing_index.sql
@@ -0,0 +1,12 @@
+-- V41: support the handoff listing added alongside ownership.
+--
+-- Every existing handoffs index is partial (`WHERE state = 'open'`), including
+-- V39's. The listing endpoint's default call asks for EVERY state — that is how
+-- an operator finds a baton that was already consumed — so it had no usable
+-- index and made SQLite scan the project's entire handoff history and build a
+-- temp B-tree to sort it, on every request.
+--
+-- Non-partial and ordered to match the query's `ORDER BY created_at DESC`, so
+-- the scan is bounded by the LIMIT instead of by the table.
+CREATE INDEX idx_handoffs_project_recent
+ ON handoffs (workspace_id, project_id, created_at DESC);
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 3b44e07d..03742a22 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -691,6 +691,7 @@ mod tests {
project_id: other,
agent_kind: AgentKind::Codex,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -1590,6 +1591,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::OpenCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -1802,12 +1804,16 @@ mod tests {
assert_eq!(edges[0].to_project, "infra");
// Briefing degree: app depends on 1 project; infra has 1 dependent.
- let app_brief = store.reader.briefing_for_project(ws, app, 5).await.unwrap();
+ let app_brief = store
+ .reader
+ .briefing_for_project(ws, app, 5, ai_memory_core::OwnerFilter::Any)
+ .await
+ .unwrap();
assert_eq!(app_brief.cross_project_dependencies, 1);
assert_eq!(app_brief.cross_project_dependents, 0);
let infra_brief = store
.reader
- .briefing_for_project(ws, infra, 5)
+ .briefing_for_project(ws, infra, 5, ai_memory_core::OwnerFilter::Any)
.await
.unwrap();
assert_eq!(infra_brief.cross_project_dependents, 1);
@@ -1938,6 +1944,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::AntigravityCli,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -2534,6 +2541,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::OpenCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -2593,6 +2601,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::ClaudeCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -2663,6 +2672,7 @@ mod tests {
project_id,
agent_kind: AgentKind::ClaudeCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -2776,6 +2786,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::OpenCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -2820,6 +2831,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::Codex,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -2834,6 +2846,7 @@ mod tests {
open_questions: Vec::new(),
next_steps: Vec::new(),
files_touched: Vec::new(),
+ owner_user: None,
};
assert!(
@@ -2910,6 +2923,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::ClaudeCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -3047,6 +3061,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::OpenCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -3077,6 +3092,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::OpenCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -3151,6 +3167,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::OpenCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -3225,6 +3242,7 @@ mod tests {
project_id,
agent_kind: AgentKind::OpenCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -3251,6 +3269,7 @@ mod tests {
project_id,
agent_kind: AgentKind::OpenCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -3293,6 +3312,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::OpenCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -3339,6 +3359,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::OpenCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -3412,6 +3433,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::OpenCode,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -3469,15 +3491,20 @@ mod tests {
&conn,
&sample_page(ws, proj, "notes/v103.md", "v1.0.3 upgrade fixture"),
);
- super::ops::begin_session(
- &mut conn,
- &NewSession {
- id: session_id,
- workspace_id: ws,
- project_id: proj,
- agent_kind: AgentKind::OpenCode,
- cwd: None,
- },
+ // Era-appropriate raw insert: this fixture stops at V19 on
+ // purpose, while `begin_session` writes whatever columns the
+ // CURRENT schema has — including V40's `actor_user`, which a
+ // v19-era `sessions` table does not have.
+ conn.execute(
+ "INSERT INTO sessions \
+ (id, workspace_id, project_id, agent_kind, cwd, started_at) \
+ VALUES (?1, ?2, ?3, 'open-code', NULL, ?4)",
+ params![
+ session_id.as_bytes(),
+ ws.as_bytes(),
+ proj.as_bytes(),
+ jiff::Timestamp::now().as_microsecond(),
+ ],
)
.unwrap();
super::ops::insert_observation(
@@ -3733,18 +3760,25 @@ mod tests {
"explicit kind must win"
);
- assert_briefing_kinds(&store.reader.briefing(100).await.unwrap().recent_pages);
assert_briefing_kinds(
&store
.reader
- .briefing_for_workspace(ws, 100)
+ .briefing(100, ai_memory_core::OwnerFilter::Any)
+ .await
+ .unwrap()
+ .recent_pages,
+ );
+ assert_briefing_kinds(
+ &store
+ .reader
+ .briefing_for_workspace(ws, 100, ai_memory_core::OwnerFilter::Any)
.await
.unwrap()
.recent_pages,
);
let project_briefing = store
.reader
- .briefing_for_project(ws, proj, 100)
+ .briefing_for_project(ws, proj, 100, ai_memory_core::OwnerFilter::Any)
.await
.unwrap();
assert_briefing_kinds(&project_briefing.recent_pages);
@@ -4923,6 +4957,7 @@ mod tests {
open_questions: Vec::new(),
next_steps: Vec::new(),
files_touched: Vec::new(),
+ owner_user: None,
};
let first_handoff = store.writer.insert_handoff(insert_handoff()).await.unwrap();
@@ -4932,6 +4967,8 @@ mod tests {
Some(first_handoff),
AgentKind::Codex,
None,
+ None,
+ ai_memory_core::OwnerFilter::Any,
Some(run.run_id),
None,
)
@@ -4947,7 +4984,7 @@ mod tests {
assert!(
store
.reader
- .latest_open_handoff(ws, proj, None)
+ .latest_open_handoff(ws, proj, None, ai_memory_core::OwnerFilter::Any)
.await
.unwrap()
.is_none()
@@ -4960,6 +4997,8 @@ mod tests {
Some(second_handoff),
AgentKind::Codex,
None,
+ None,
+ ai_memory_core::OwnerFilter::Any,
Some(run.run_id),
None,
)
@@ -4973,7 +5012,7 @@ mod tests {
assert_eq!(
store
.reader
- .latest_open_handoff(ws, proj, None)
+ .latest_open_handoff(ws, proj, None, ai_memory_core::OwnerFilter::Any)
.await
.unwrap()
.map(|handoff| handoff.id),
@@ -4996,6 +5035,7 @@ mod tests {
project_id,
agent_kind: AgentKind::ClaudeCode,
cwd: Some(cwd.into()),
+ actor_user: None,
})
.await
.unwrap();
@@ -5012,6 +5052,7 @@ mod tests {
open_questions: Vec::new(),
next_steps: Vec::new(),
files_touched: Vec::new(),
+ owner_user: None,
})
.await
.unwrap()
@@ -5026,6 +5067,8 @@ mod tests {
Some(selected_auto),
AgentKind::Codex,
None,
+ None,
+ ai_memory_core::OwnerFilter::Any,
Some(run.run_id),
Some("/repo/api/src".into()),
)
diff --git a/crates/ai-memory-store/src/migrations.rs b/crates/ai-memory-store/src/migrations.rs
index 3c1ec00a..b1c8a513 100644
--- a/crates/ai-memory-store/src/migrations.rs
+++ b/crates/ai-memory-store/src/migrations.rs
@@ -52,7 +52,7 @@ pub(crate) fn run_to(conn: &mut rusqlite::Connection, target: u32) -> Result<(),
#[cfg(test)]
mod tests {
use super::*;
- use ai_memory_core::{AgentKind, NewObservation, NewSession, ObservationKind, SessionId};
+ use ai_memory_core::{AgentKind, NewObservation, ObservationKind, SessionId};
use rusqlite::{Connection, params};
/// A store migrated by a newer build (an applied version above anything
@@ -363,15 +363,21 @@ mod tests {
let project_id =
crate::ops::get_or_create_project(&mut conn, &workspace_id, "project", None).unwrap();
let session_id = SessionId::new();
- crate::ops::begin_session(
- &mut conn,
- &NewSession {
- id: session_id,
- workspace_id,
- project_id,
- agent_kind: AgentKind::Codex,
- cwd: None,
- },
+ // Era-appropriate raw insert. This fixture deliberately stops at V33
+ // and then migrates forward, so it must not go through `begin_session`:
+ // that writes whatever columns the CURRENT schema has, and every later
+ // migration that adds one would break a test about an older era.
+ conn.execute(
+ "INSERT INTO sessions \
+ (id, workspace_id, project_id, agent_kind, cwd, started_at) \
+ VALUES (?1, ?2, ?3, ?4, NULL, ?5)",
+ params![
+ session_id.as_bytes(),
+ workspace_id.as_bytes(),
+ project_id.as_bytes(),
+ AgentKind::Codex.as_str(),
+ jiff::Timestamp::now().as_microsecond(),
+ ],
)
.unwrap();
crate::ops::insert_observation(
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index f652d824..537a747e 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -8,7 +8,8 @@ use std::collections::BTreeSet;
use ai_memory_core::{
AgentKind, EntityId, HandoffId, LinkTarget, NewHandoff, NewObservation, NewPage, NewSession,
- ObservationId, ObservationKind, PageId, PagePath, ProjectId, SessionId, WorkspaceId,
+ ObservationId, ObservationKind, OwnerFilter, PageId, PagePath, ProjectId, SessionId,
+ WorkspaceId,
};
/// Summary returned by [`reorg_sessions`] and exposed via
@@ -858,8 +859,9 @@ pub fn begin_session(conn: &mut Connection, session: &NewSession) -> StoreResult
.as_ref()
.map(|p| p.to_string_lossy().into_owned());
conn.execute(
- "INSERT INTO sessions (id, workspace_id, project_id, agent_kind, cwd, started_at) \
- VALUES (?1, ?2, ?3, ?4, ?5, ?6) \
+ "INSERT INTO sessions \
+ (id, workspace_id, project_id, agent_kind, cwd, started_at, actor_user) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) \
ON CONFLICT(id) DO NOTHING",
params![
session.id.as_bytes(),
@@ -868,6 +870,7 @@ pub fn begin_session(conn: &mut Connection, session: &NewSession) -> StoreResult
agent,
cwd,
now,
+ session.actor_user.as_deref(),
],
)?;
Ok(())
@@ -1441,14 +1444,23 @@ fn insert_handoff_row(conn: &Transaction<'_>, h: &NewHandoff) -> StoreResult<Han
// A newer automatic handoff from the exact same cwd is the only one that
// can ever win there, even before a SessionStart occurs. Bound abandoned
// same-directory sessions without touching deliberate manual handoffs or
- // independent parent/sibling cwd scopes.
+ // independent parent/sibling cwd scopes — and without crossing an operator
+ // boundary: the same directory inside a shared container is the norm, so
+ // owner equality is the only thing keeping one operator's SessionEnd from
+ // retiring another's pending baton.
if from_session.is_some() {
let expired = conn.execute(
"UPDATE handoffs SET state = 'expired' \
WHERE workspace_id = ?1 AND project_id = ?2 \
AND state = 'open' AND from_session_id IS NOT NULL \
- AND (cwd = ?3 OR (cwd IS NULL AND ?3 IS NULL))",
- params![h.workspace_id.as_bytes(), h.project_id.as_bytes(), cwd],
+ AND (cwd = ?3 OR (cwd IS NULL AND ?3 IS NULL)) \
+ AND owner_user IS ?4",
+ params![
+ h.workspace_id.as_bytes(),
+ h.project_id.as_bytes(),
+ cwd,
+ h.owner_user.as_deref()
+ ],
)?;
if expired > 0 {
audit(
@@ -1468,8 +1480,8 @@ fn insert_handoff_row(conn: &Transaction<'_>, h: &NewHandoff) -> StoreResult<Han
conn.execute(
"INSERT INTO handoffs \
(id, workspace_id, project_id, from_session_id, from_agent, to_agent, cwd, summary, \
- open_questions, next_steps, files_touched, state, created_at) \
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, 'open', ?12)",
+ open_questions, next_steps, files_touched, state, created_at, owner_user) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, 'open', ?12, ?13)",
params![
id.as_bytes(),
h.workspace_id.as_bytes(),
@@ -1483,6 +1495,9 @@ fn insert_handoff_row(conn: &Transaction<'_>, h: &NewHandoff) -> StoreResult<Han
next_s,
files,
now,
+ // NULL owner = shared with the whole project: what a caller with no
+ // actor writes, and what every pre-V39 row already looks like.
+ h.owner_user.as_deref(),
],
)?;
audit(
@@ -1524,23 +1539,36 @@ fn handoff_scope(
}
/// Mark a handoff accepted by `accepting_agent` / `accepting_session`.
+///
+/// Returns whether this call is the one that actually claimed it: `false` means
+/// the row was already accepted/expired, or its owner does not admit this
+/// caller. Callers must not hand the body to the agent on `false`, or a lost
+/// race delivers the same baton twice.
+///
+/// `receiving_cwd` is where the *claiming* session is starting, not where the
+/// claimed handoff came from; it bounds the post-claim sweep of stale automatic
+/// handoffs.
pub fn accept_handoff(
conn: &mut Connection,
handoff_id: &HandoffId,
accepting_agent: AgentKind,
accepting_session: Option<&SessionId>,
+ accepting_user: Option<&str>,
+ owner_filter: &OwnerFilter,
receiving_cwd: Option<&str>,
-) -> StoreResult<()> {
+) -> StoreResult<bool> {
let tx = conn.transaction()?;
- accept_handoff_in_transaction(
+ let claimed = accept_handoff_in_transaction(
&tx,
handoff_id,
accepting_agent,
accepting_session,
+ accepting_user,
+ owner_filter,
receiving_cwd,
)?;
tx.commit()?;
- Ok(())
+ Ok(claimed)
}
pub(crate) fn accept_handoff_in_transaction(
@@ -1548,6 +1576,8 @@ pub(crate) fn accept_handoff_in_transaction(
handoff_id: &HandoffId,
accepting_agent: AgentKind,
accepting_session: Option<&SessionId>,
+ accepting_user: Option<&str>,
+ owner_filter: &OwnerFilter,
receiving_cwd: Option<&str>,
) -> StoreResult<bool> {
let now = Timestamp::now().as_microsecond();
@@ -1555,7 +1585,8 @@ pub(crate) fn accept_handoff_in_transaction(
let session: Option<&[u8]> = accepting_session.map(|s| &s.as_bytes()[..]);
let metadata = tx
.query_row(
- "SELECT workspace_id, project_id, from_session_id IS NOT NULL, cwd, created_at \
+ "SELECT workspace_id, project_id, from_session_id IS NOT NULL, cwd, created_at, \
+ owner_user \
FROM handoffs WHERE id = ?1 AND state = 'open'",
params![handoff_id.as_bytes()],
|row| {
@@ -1565,20 +1596,46 @@ pub(crate) fn accept_handoff_in_transaction(
row.get::<_, bool>(2)?,
row.get::<_, Option<String>>(3)?,
row.get::<_, i64>(4)?,
+ row.get::<_, Option<String>>(5)?,
))
},
)
.optional()?;
- let Some((workspace_id, project_id, automatic, cwd, created_at)) = metadata else {
+ let Some((workspace_id, project_id, automatic, cwd, created_at, owner_user)) = metadata else {
return Ok(false);
};
let (ws, proj) = handoff_scope(tx, handoff_id)?;
- let changed = tx.execute(
+ // The ownership check rides along in the UPDATE's WHERE rather than being a
+ // separate read: the claim stays a single atomic compare-and-set (only one
+ // racing session can flip 'open' -> 'accepted'), and a caller who is not
+ // allowed to take this baton simply changes 0 rows.
+ let owner_clause = match owner_filter {
+ OwnerFilter::Any => "",
+ OwnerFilter::User(_) => " AND (owner_user IS NULL OR owner_user = ?6)",
+ OwnerFilter::Unattributed => " AND owner_user IS NULL",
+ };
+ let sql = format!(
"UPDATE handoffs SET state = 'accepted', accepted_by = ?1, accepted_at = ?2, \
- accepted_by_session = ?3 \
- WHERE id = ?4 AND state = 'open'",
- params![agent, now, session, handoff_id.as_bytes()],
- )?;
+ accepted_by_session = ?3, accepted_by_user = ?5 \
+ WHERE id = ?4 AND state = 'open'{owner_clause}"
+ );
+ let changed = match owner_filter {
+ OwnerFilter::User(user) => tx.execute(
+ &sql,
+ params![
+ agent,
+ now,
+ session,
+ handoff_id.as_bytes(),
+ accepting_user,
+ user
+ ],
+ )?,
+ _ => tx.execute(
+ &sql,
+ params![agent, now, session, handoff_id.as_bytes(), accepting_user],
+ )?,
+ };
// Only a real state transition ('open' -> 'accepted') is audited.
if changed > 0 {
audit(
@@ -1591,6 +1648,11 @@ pub(crate) fn accept_handoff_in_transaction(
now,
)?;
if automatic {
+ // The sweep inherits the claimed handoff's owner: retiring stale
+ // batons must never reach across an operator boundary, or one
+ // person's session start silently destroys another's pending
+ // handoff — a worse failure than the misdelivery ownership exists
+ // to prevent, because nothing is delivered at all.
let expired = expire_superseded_auto_handoffs(
tx,
handoff_id,
@@ -1599,6 +1661,7 @@ pub(crate) fn accept_handoff_in_transaction(
cwd.as_deref(),
created_at,
receiving_cwd,
+ owner_user.as_deref(),
)?;
if expired > 0 {
audit(
@@ -1618,7 +1681,12 @@ pub(crate) fn accept_handoff_in_transaction(
/// Expire older automatic handoffs that were eligible for the same receiving
/// cwd as the accepted handoff. Manual and sibling-directory handoffs are
-/// deliberately excluded.
+/// deliberately excluded, and so is every handoff belonging to a different
+/// operator: a NULL owner is visible to *everyone*, so expiring one on Alice's
+/// behalf would take it away from Bob too. Equality on `owner_user` keeps the
+/// unattributed single-operator case (every row NULL) behaving exactly as it
+/// does without ownership.
+#[allow(clippy::too_many_arguments)]
fn expire_superseded_auto_handoffs(
tx: &Transaction<'_>,
accepted_id: &HandoffId,
@@ -1627,6 +1695,7 @@ fn expire_superseded_auto_handoffs(
accepted_cwd: Option<&str>,
accepted_created_at: i64,
receiving_cwd: Option<&str>,
+ accepted_owner: Option<&str>,
) -> StoreResult<usize> {
let receiving_cwd = receiving_cwd.or(accepted_cwd);
let accepted_key = crate::reader::handoff_selection_key(
@@ -1638,9 +1707,10 @@ fn expire_superseded_auto_handoffs(
let mut stmt = tx.prepare(
"SELECT id, cwd, created_at FROM handoffs \
WHERE workspace_id = ?1 AND project_id = ?2 \
- AND state = 'open' AND from_session_id IS NOT NULL",
+ AND state = 'open' AND from_session_id IS NOT NULL \
+ AND owner_user IS ?3",
)?;
- let rows = stmt.query_map(params![workspace_id, project_id], |row| {
+ let rows = stmt.query_map(params![workspace_id, project_id, accepted_owner], |row| {
Ok((
row.get::<_, Vec<u8>>(0)?,
row.get::<_, Option<String>>(1)?,
@@ -1677,14 +1747,29 @@ fn expire_superseded_auto_handoffs(
}
/// Mark an open handoff expired so it will no longer be consumed.
-pub fn cancel_handoff(conn: &mut Connection, handoff_id: &HandoffId) -> StoreResult<bool> {
+pub fn cancel_handoff(
+ conn: &mut Connection,
+ handoff_id: &HandoffId,
+ owner_filter: &OwnerFilter,
+) -> StoreResult<bool> {
let now = Timestamp::now().as_microsecond();
let tx = conn.transaction()?;
let (ws, proj) = handoff_scope(&tx, handoff_id)?;
- let changed = tx.execute(
- "UPDATE handoffs SET state = 'expired' WHERE id = ?1 AND state = 'open'",
- params![handoff_id.as_bytes()],
- )?;
+ // Same reasoning as the accept path: the owner predicate lives in the
+ // UPDATE so cancelling somebody else's baton is a 0-row no-op instead of a
+ // read-then-write race.
+ let owner_clause = match owner_filter {
+ OwnerFilter::Any => "",
+ OwnerFilter::User(_) => " AND (owner_user IS NULL OR owner_user = ?2)",
+ OwnerFilter::Unattributed => " AND owner_user IS NULL",
+ };
+ let sql = format!(
+ "UPDATE handoffs SET state = 'expired' WHERE id = ?1 AND state = 'open'{owner_clause}"
+ );
+ let changed = match owner_filter {
+ OwnerFilter::User(user) => tx.execute(&sql, params![handoff_id.as_bytes(), user])?,
+ _ => tx.execute(&sql, params![handoff_id.as_bytes()])?,
+ };
if changed > 0 {
audit(
&tx,
@@ -2445,6 +2530,7 @@ pub(crate) mod tests {
project_id: proj,
agent_kind: kind,
cwd: None,
+ actor_user: None,
};
begin_session(&mut conn, &session).unwrap_or_else(|e| {
panic!(
@@ -3211,6 +3297,7 @@ pub(crate) mod tests {
open_questions: vec![],
next_steps: vec![],
files_touched: vec![],
+ owner_user: None,
};
let id = insert_handoff(&mut conn, &new).unwrap();
@@ -3225,7 +3312,16 @@ pub(crate) mod tests {
assert_eq!(state, "open");
assert!(accepted_by.is_none());
- accept_handoff(&mut conn, &id, AgentKind::Codex, None, None).unwrap();
+ accept_handoff(
+ &mut conn,
+ &id,
+ AgentKind::Codex,
+ None,
+ None,
+ &OwnerFilter::Any,
+ None,
+ )
+ .unwrap();
let (state, accepted_by): (String, Option<String>) = conn
.query_row(
"SELECT state, accepted_by FROM handoffs WHERE id = ?1",
@@ -3240,7 +3336,15 @@ pub(crate) mod tests {
// either succeed silently or fail clearly, never corrupt
// the row. (Current impl is a no-op UPDATE with a state
// guard.)
- let second = accept_handoff(&mut conn, &id, AgentKind::Codex, None, None);
+ let second = accept_handoff(
+ &mut conn,
+ &id,
+ AgentKind::Codex,
+ None,
+ None,
+ &OwnerFilter::Any,
+ None,
+ );
assert!(second.is_ok(), "double-accept must not error");
}
@@ -3256,6 +3360,7 @@ pub(crate) mod tests {
project_id: proj,
agent_kind: AgentKind::ClaudeCode,
cwd: Some("/repo".into()),
+ actor_user: None,
},
)
.unwrap();
@@ -3270,6 +3375,7 @@ pub(crate) mod tests {
open_questions: vec![],
next_steps: vec![],
files_touched: vec![],
+ owner_user: None,
};
let first = insert_handoff(&mut conn, &handoff(first_session)).unwrap();
@@ -3311,11 +3417,21 @@ pub(crate) mod tests {
open_questions: vec![],
next_steps: vec![],
files_touched: vec![],
+ owner_user: None,
};
let id = insert_handoff(&mut conn, &new()).unwrap();
- accept_handoff(&mut conn, &id, AgentKind::Codex, None, None).unwrap();
+ accept_handoff(
+ &mut conn,
+ &id,
+ AgentKind::Codex,
+ None,
+ None,
+ &OwnerFilter::Any,
+ None,
+ )
+ .unwrap();
let id2 = insert_handoff(&mut conn, &new()).unwrap();
- assert!(cancel_handoff(&mut conn, &id2).unwrap());
+ assert!(cancel_handoff(&mut conn, &id2, &OwnerFilter::Any).unwrap());
for op in ["insert_handoff", "accept_handoff", "cancel_handoff"] {
let (count, author) = audit_row_for(&conn, op);
@@ -3329,8 +3445,17 @@ pub(crate) mod tests {
);
// Idempotent misses stay out of the trail: a double-accept and a
// cancel of an already-accepted handoff change no row, audit nothing.
- accept_handoff(&mut conn, &id, AgentKind::Codex, None, None).unwrap();
- assert!(!cancel_handoff(&mut conn, &id).unwrap());
+ accept_handoff(
+ &mut conn,
+ &id,
+ AgentKind::Codex,
+ None,
+ None,
+ &OwnerFilter::Any,
+ None,
+ )
+ .unwrap();
+ assert!(!cancel_handoff(&mut conn, &id, &OwnerFilter::Any).unwrap());
assert_eq!(
audit_row_for(&conn, "accept_handoff").0,
1,
@@ -3373,6 +3498,7 @@ pub(crate) mod tests {
open_questions: vec![],
next_steps: vec![],
files_touched: vec![],
+ owner_user: None,
};
let id = insert_handoff(&mut conn, &new).unwrap();
let cwd: Option<String> = conn
@@ -3395,6 +3521,7 @@ pub(crate) mod tests {
open_questions: vec![],
next_steps: vec![],
files_touched: vec![],
+ owner_user: None,
};
let id = insert_handoff(&mut conn, &windows).unwrap();
let cwd: Option<String> = conn
@@ -3421,10 +3548,11 @@ pub(crate) mod tests {
open_questions: vec![],
next_steps: vec![],
files_touched: vec![],
+ owner_user: None,
};
let id = insert_handoff(&mut conn, &new).unwrap();
- assert!(cancel_handoff(&mut conn, &id).unwrap());
+ assert!(cancel_handoff(&mut conn, &id, &OwnerFilter::Any).unwrap());
let state: String = conn
.query_row(
"SELECT state FROM handoffs WHERE id = ?1",
@@ -3435,7 +3563,7 @@ pub(crate) mod tests {
assert_eq!(state, "expired");
assert!(
- !cancel_handoff(&mut conn, &id).unwrap(),
+ !cancel_handoff(&mut conn, &id, &OwnerFilter::Any).unwrap(),
"double-cancel should be a no-op"
);
}
@@ -3455,6 +3583,7 @@ pub(crate) mod tests {
project_id: proj,
agent_kind,
cwd: Some(std::path::PathBuf::from(r"C:\GIT\ai-memory")),
+ actor_user: None,
},
)
.unwrap();
@@ -3484,6 +3613,7 @@ pub(crate) mod tests {
project_id: proj,
agent_kind: AgentKind::ClaudeCode,
cwd: None,
+ actor_user: None,
},
)
.unwrap();
@@ -3526,6 +3656,7 @@ pub(crate) mod tests {
project_id: proj,
agent_kind: AgentKind::ClaudeCode,
cwd: None,
+ actor_user: None,
},
)
.unwrap();
@@ -3811,6 +3942,7 @@ pub(crate) mod tests {
project_id: proj,
agent_kind: AgentKind::ClaudeCode,
cwd: None,
+ actor_user: None,
},
)
.unwrap();
@@ -3997,7 +4129,7 @@ pub(crate) mod tests {
/// on a repaired DB updates / deletes nothing.
#[test]
fn v19_repairs_orphan_observation_attribution_and_purges_empty_projects() {
- use ai_memory_core::{AgentKind, NewObservation, NewSession, ObservationKind, SessionId};
+ use ai_memory_core::{NewObservation, ObservationKind, SessionId};
// Apply migrations through V18 (not V19) so we can seed the
// orphaned-attribution state V19 is designed to repair. If we
@@ -4031,17 +4163,16 @@ pub(crate) mod tests {
.unwrap();
let sid = SessionId::new();
- begin_session(
- &mut conn,
- &NewSession {
- id: sid,
- workspace_id: ws,
- project_id: parent,
- agent_kind: AgentKind::ClaudeCode,
- cwd: Some("/mnt/data/Projects/manga-plus".into()),
- },
- )
- .unwrap();
+ // Era-appropriate raw insert: this fixture stops at an older
+ // schema on purpose (see `seed_historical_session`).
+ seed_historical_session(
+ &conn,
+ &sid,
+ &ws,
+ &parent,
+ ai_memory_core::AgentKind::ClaudeCode,
+ Some("/mnt/data/Projects/manga-plus"),
+ );
// Three misattributed observations on the fragment.
for i in 0..3 {
@@ -4137,6 +4268,7 @@ pub(crate) mod tests {
project_id: with_data,
agent_kind: AgentKind::ClaudeCode,
cwd: None,
+ actor_user: None,
},
)
.unwrap();
@@ -4183,6 +4315,35 @@ pub(crate) mod tests {
assert!(sweep_hollow_projects(&mut conn, 7).unwrap().is_empty());
}
+ /// Insert a `sessions` row using only the columns that have existed since
+ /// V01, for fixtures that deliberately stop at an older schema version.
+ /// The production `begin_session` writes whatever columns the CURRENT
+ /// schema has — including V40's `actor_user`, which these fixtures'
+ /// `sessions` tables do not have yet.
+ fn seed_historical_session(
+ conn: &Connection,
+ id: &ai_memory_core::SessionId,
+ workspace_id: &WorkspaceId,
+ project_id: &ProjectId,
+ agent_kind: ai_memory_core::AgentKind,
+ cwd: Option<&str>,
+ ) {
+ conn.execute(
+ "INSERT INTO sessions \
+ (id, workspace_id, project_id, agent_kind, cwd, started_at) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
+ params![
+ id.as_bytes(),
+ workspace_id.as_bytes(),
+ project_id.as_bytes(),
+ agent_kind.as_str(),
+ cwd,
+ Timestamp::now().as_microsecond(),
+ ],
+ )
+ .unwrap();
+ }
+
/// V27 re-runs the V19 repair for the fragments that accumulated
/// after V19: non-git parents have no repo_path, so the v0.12.2
/// prefix guard couldn't anchor subdirectory cwds and per-event
@@ -4190,7 +4351,7 @@ pub(crate) mod tests {
/// a second pass repairs nothing.
#[test]
fn v27_reattributes_nongit_fragments_and_preserves_reserved_projects() {
- use ai_memory_core::{AgentKind, NewObservation, NewSession, ObservationKind, SessionId};
+ use ai_memory_core::{NewObservation, ObservationKind, SessionId};
let tmp = TempDir::new().unwrap();
let db_path = tmp.path().join("test.sqlite");
@@ -4208,17 +4369,17 @@ pub(crate) mod tests {
let global = get_or_create_project(&mut conn, &ws, "_global", None).unwrap();
let sid = SessionId::new();
- begin_session(
- &mut conn,
- &NewSession {
- id: sid,
- workspace_id: ws,
- project_id: parent,
- agent_kind: AgentKind::ClaudeCode,
- cwd: Some("/home/user/tiktok_analysis".into()),
- },
- )
- .unwrap();
+ // Seeded with era-appropriate SQL rather than `begin_session`: this
+ // fixture stops at an older schema on purpose, and the production
+ // helper writes whatever columns the CURRENT schema has.
+ seed_historical_session(
+ &conn,
+ &sid,
+ &ws,
+ &parent,
+ ai_memory_core::AgentKind::ClaudeCode,
+ Some("/home/user/tiktok_analysis"),
+ );
for i in 0..4 {
insert_observation(
&mut conn,
@@ -4286,7 +4447,7 @@ pub(crate) mod tests {
#[test]
fn v20_adds_grok_and_preserves_sessions_invariants_on_upgraded_db() {
- use ai_memory_core::{AgentKind, NewObservation, NewSession, ObservationKind, SessionId};
+ use ai_memory_core::{NewObservation, ObservationKind, SessionId};
let tmp = TempDir::new().unwrap();
let db_path = tmp.path().join("test.sqlite");
@@ -4301,17 +4462,16 @@ pub(crate) mod tests {
conn.pragma_update(None, "foreign_keys", "ON").unwrap();
ws = get_or_create_workspace(&mut conn, "default").unwrap();
proj = get_or_create_project(&mut conn, &ws, "scratch", None).unwrap();
- begin_session(
- &mut conn,
- &NewSession {
- id: existing_sid,
- workspace_id: ws,
- project_id: proj,
- agent_kind: AgentKind::ClaudeCode,
- cwd: None,
- },
- )
- .unwrap();
+ // Era-appropriate raw insert: this fixture stops at an older
+ // schema on purpose (see `seed_historical_session`).
+ seed_historical_session(
+ &conn,
+ &existing_sid,
+ &ws,
+ &proj,
+ ai_memory_core::AgentKind::ClaudeCode,
+ None,
+ );
insert_observation(
&mut conn,
&NewObservation {
@@ -4334,17 +4494,17 @@ pub(crate) mod tests {
crate::migrations::run_to(&mut conn, 20).unwrap();
conn.pragma_update(None, "foreign_keys", "ON").unwrap();
- begin_session(
- &mut conn,
- &NewSession {
- id: SessionId::new(),
- workspace_id: ws,
- project_id: proj,
- agent_kind: AgentKind::Grok,
- cwd: None,
- },
- )
- .unwrap();
+ // Era-appropriate raw insert (see `seed_historical_session`):
+ // this fixture asserts the migration's widened CHECK accepts the
+ // newly added agent kind on an upgraded database.
+ seed_historical_session(
+ &conn,
+ &SessionId::new(),
+ &ws,
+ &proj,
+ ai_memory_core::AgentKind::Grok,
+ None,
+ );
let obs_count: i64 = conn
.query_row(
@@ -4382,17 +4542,23 @@ pub(crate) mod tests {
let other_ws = get_or_create_workspace(&mut conn, "other").unwrap();
let other_proj =
get_or_create_project(&mut conn, &other_ws, "other-project", None).unwrap();
- let err = begin_session(
- &mut conn,
- &NewSession {
- id: SessionId::new(),
- workspace_id: ws,
- project_id: other_proj,
- agent_kind: AgentKind::Grok,
- cwd: None,
- },
- )
- .unwrap_err();
+ // Raw insert on purpose: the fixture sits on an older schema, and
+ // what is under test is the pairing TRIGGER rejecting a session
+ // whose workspace does not own its project.
+ let err = conn
+ .execute(
+ "INSERT INTO sessions \
+ (id, workspace_id, project_id, agent_kind, cwd, started_at) \
+ VALUES (?1, ?2, ?3, ?4, NULL, ?5)",
+ params![
+ SessionId::new().as_bytes(),
+ ws.as_bytes(),
+ other_proj.as_bytes(),
+ ai_memory_core::AgentKind::Grok.as_str(),
+ Timestamp::now().as_microsecond(),
+ ],
+ )
+ .unwrap_err();
assert!(
err.to_string()
.contains("sessions.workspace_id does not match"),
@@ -4409,7 +4575,7 @@ pub(crate) mod tests {
#[test]
fn v25_adds_pi_and_preserves_sessions_invariants_on_upgraded_db() {
- use ai_memory_core::{AgentKind, NewSession, SessionId};
+ use ai_memory_core::SessionId;
let tmp = TempDir::new().unwrap();
let db_path = tmp.path().join("test.sqlite");
@@ -4424,17 +4590,16 @@ pub(crate) mod tests {
conn.pragma_update(None, "foreign_keys", "ON").unwrap();
ws = get_or_create_workspace(&mut conn, "default").unwrap();
proj = get_or_create_project(&mut conn, &ws, "scratch", None).unwrap();
- begin_session(
- &mut conn,
- &NewSession {
- id: existing_sid,
- workspace_id: ws,
- project_id: proj,
- agent_kind: AgentKind::ClaudeCode,
- cwd: None,
- },
- )
- .unwrap();
+ // Era-appropriate raw insert: this fixture stops at an older
+ // schema on purpose (see `seed_historical_session`).
+ seed_historical_session(
+ &conn,
+ &existing_sid,
+ &ws,
+ &proj,
+ ai_memory_core::AgentKind::ClaudeCode,
+ None,
+ );
}
let mut conn = Connection::open(&db_path).unwrap();
@@ -4442,17 +4607,17 @@ pub(crate) mod tests {
crate::migrations::run_to(&mut conn, 25).unwrap();
conn.pragma_update(None, "foreign_keys", "ON").unwrap();
- begin_session(
- &mut conn,
- &NewSession {
- id: SessionId::new(),
- workspace_id: ws,
- project_id: proj,
- agent_kind: AgentKind::Pi,
- cwd: None,
- },
- )
- .unwrap();
+ // Era-appropriate raw insert (see `seed_historical_session`):
+ // this fixture asserts the migration's widened CHECK accepts the
+ // newly added agent kind on an upgraded database.
+ seed_historical_session(
+ &conn,
+ &SessionId::new(),
+ &ws,
+ &proj,
+ ai_memory_core::AgentKind::Pi,
+ None,
+ );
let session_count: i64 = conn
.query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))
@@ -4506,7 +4671,7 @@ pub(crate) mod tests {
#[test]
fn v28_adds_devin_and_preserves_sessions_invariants_on_upgraded_db() {
- use ai_memory_core::{AgentKind, NewSession, SessionId};
+ use ai_memory_core::SessionId;
let tmp = TempDir::new().unwrap();
let db_path = tmp.path().join("test.sqlite");
@@ -4521,17 +4686,16 @@ pub(crate) mod tests {
conn.pragma_update(None, "foreign_keys", "ON").unwrap();
ws = get_or_create_workspace(&mut conn, "default").unwrap();
proj = get_or_create_project(&mut conn, &ws, "scratch", None).unwrap();
- begin_session(
- &mut conn,
- &NewSession {
- id: existing_sid,
- workspace_id: ws,
- project_id: proj,
- agent_kind: AgentKind::ClaudeCode,
- cwd: None,
- },
- )
- .unwrap();
+ // Era-appropriate raw insert: this fixture stops at an older
+ // schema on purpose (see `seed_historical_session`).
+ seed_historical_session(
+ &conn,
+ &existing_sid,
+ &ws,
+ &proj,
+ ai_memory_core::AgentKind::ClaudeCode,
+ None,
+ );
}
// Run through V26 (Zero) and V27 (unrelated data repair) too, not
@@ -4542,17 +4706,17 @@ pub(crate) mod tests {
crate::migrations::run_to(&mut conn, 28).unwrap();
conn.pragma_update(None, "foreign_keys", "ON").unwrap();
- begin_session(
- &mut conn,
- &NewSession {
- id: SessionId::new(),
- workspace_id: ws,
- project_id: proj,
- agent_kind: AgentKind::Devin,
- cwd: None,
- },
- )
- .unwrap();
+ // Era-appropriate raw insert (see `seed_historical_session`):
+ // this fixture asserts the migration's widened CHECK accepts the
+ // newly added agent kind on an upgraded database.
+ seed_historical_session(
+ &conn,
+ &SessionId::new(),
+ &ws,
+ &proj,
+ ai_memory_core::AgentKind::Devin,
+ None,
+ );
let session_count: i64 = conn
.query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))
@@ -4606,17 +4770,23 @@ pub(crate) mod tests {
let other_ws = get_or_create_workspace(&mut conn, "other").unwrap();
let other_proj =
get_or_create_project(&mut conn, &other_ws, "other-project", None).unwrap();
- let err = begin_session(
- &mut conn,
- &NewSession {
- id: SessionId::new(),
- workspace_id: ws,
- project_id: other_proj,
- agent_kind: AgentKind::Devin,
- cwd: None,
- },
- )
- .unwrap_err();
+ // Raw insert on purpose: the fixture sits on an older schema, and
+ // what is under test is the pairing TRIGGER rejecting a session
+ // whose workspace does not own its project.
+ let err = conn
+ .execute(
+ "INSERT INTO sessions \
+ (id, workspace_id, project_id, agent_kind, cwd, started_at) \
+ VALUES (?1, ?2, ?3, ?4, NULL, ?5)",
+ params![
+ SessionId::new().as_bytes(),
+ ws.as_bytes(),
+ other_proj.as_bytes(),
+ ai_memory_core::AgentKind::Devin.as_str(),
+ Timestamp::now().as_microsecond(),
+ ],
+ )
+ .unwrap_err();
assert!(
err.to_string()
.contains("sessions.workspace_id does not match"),
@@ -4692,6 +4862,7 @@ pub(crate) mod tests {
open_questions: vec![],
next_steps: vec![],
files_touched: vec![],
+ owner_user: None,
},
)
.unwrap();
@@ -4807,6 +4978,7 @@ pub(crate) mod tests {
project_id: proj,
agent_kind: AgentKind::ClaudeCode,
cwd: None,
+ actor_user: None,
},
)
.is_err(),
@@ -4822,6 +4994,7 @@ pub(crate) mod tests {
project_id: proj,
agent_kind: AgentKind::ClaudeCode,
cwd: None,
+ actor_user: None,
},
)
.unwrap();
@@ -4867,6 +5040,7 @@ pub(crate) mod tests {
open_questions: vec![],
next_steps: vec![],
files_touched: vec![],
+ owner_user: None,
};
assert!(
insert_handoff(&mut conn, &mismatched_handoff).is_err(),
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index af1bb5ed..ff7843ee 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -12,8 +12,8 @@ use std::sync::Arc;
use ai_memory_core::{
AgentKind, AutoImproveProposalId, AutoImproveRunId, Handoff, HandoffId, HandoffState,
- ManagedRunId, Observation, ObservationId, ObservationKind, PageId, PagePath, ProjectId,
- SessionId, User, UserId, WorkspaceId, WorkstreamEvent, WorkstreamId,
+ ManagedRunId, Observation, ObservationId, ObservationKind, OwnerFilter, PageId, PagePath,
+ ProjectId, SessionId, User, UserId, WorkspaceId, WorkstreamEvent, WorkstreamId,
};
use jiff::Timestamp;
use parking_lot::Mutex;
@@ -1660,26 +1660,42 @@ impl ReaderPool {
workspace_id: WorkspaceId,
project_id: ProjectId,
agent_kind: AgentKind,
+ owner_filter: OwnerFilter,
limit: Option<usize>,
) -> StoreResult<Vec<OpenSession>> {
let agent = agent_kind.as_str().to_string();
self.with_conn(move |conn| {
let limit_clause = limit.map_or(String::new(), |n| format!(" LIMIT {}", n.max(1)));
+ // Without the owner predicate this returns whichever session in the
+ // scope started last — frequently a teammate's live one — and the
+ // callers act on it destructively.
+ let owner_clause = match &owner_filter {
+ OwnerFilter::Any => "",
+ OwnerFilter::User(_) => " AND (actor_user IS NULL OR actor_user = ?4)",
+ OwnerFilter::Unattributed => " AND actor_user IS NULL",
+ };
let sql = format!(
"SELECT id, cwd FROM sessions \
WHERE workspace_id = ?1 AND project_id = ?2 \
- AND agent_kind = ?3 AND ended_at IS NULL \
+ AND agent_kind = ?3 AND ended_at IS NULL{owner_clause} \
ORDER BY started_at DESC, id DESC{limit_clause}"
);
let mut stmt = conn.prepare_cached(&sql)?;
- let rows = stmt.query_map(
- params![workspace_id.as_bytes(), project_id.as_bytes(), agent],
- |row| {
- let id_bytes: Vec<u8> = row.get(0)?;
- let cwd: Option<String> = row.get(1)?;
- Ok((id_bytes, cwd))
- },
- )?;
+ let row_map = |row: &rusqlite::Row<'_>| {
+ let id_bytes: Vec<u8> = row.get(0)?;
+ let cwd: Option<String> = row.get(1)?;
+ Ok((id_bytes, cwd))
+ };
+ let rows = match &owner_filter {
+ OwnerFilter::User(user) => stmt.query_map(
+ params![workspace_id.as_bytes(), project_id.as_bytes(), agent, user],
+ row_map,
+ )?,
+ _ => stmt.query_map(
+ params![workspace_id.as_bytes(), project_id.as_bytes(), agent],
+ row_map,
+ )?,
+ };
let mut out = Vec::new();
for row in rows {
let (id_bytes, cwd) = row?;
@@ -1905,6 +1921,32 @@ impl ReaderPool {
.await
}
+ /// The operator a session belongs to (an
+ /// [`ai_memory_core::IdentityKey::storage_key`] string), as recorded at
+ /// session start.
+ ///
+ /// The identity carrying a SessionEnd is not necessarily the identity that
+ /// owned the session: a spool drain, an operator finalizing a stuck
+ /// session, or a shared static hook token can all deliver it. Attribution
+ /// for the session's page and the baton it leaves must follow the session,
+ /// not the request.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn session_actor_user(&self, session_id: SessionId) -> StoreResult<Option<String>> {
+ self.with_conn(move |conn| {
+ let owner: Option<Option<String>> = conn
+ .query_row(
+ "SELECT actor_user FROM sessions WHERE id = ?1",
+ params![session_id.as_bytes()],
+ |row| row.get(0),
+ )
+ .optional()?;
+ Ok(owner.flatten())
+ })
+ .await
+ }
+
/// Resolve the `(workspace, project)` where a session's observations
/// actually landed, independent of the (possibly stale) `sessions` row.
///
@@ -2924,12 +2966,14 @@ impl ReaderPool {
workspace_id: WorkspaceId,
project_id: ProjectId,
cwd_filter: Option<String>,
+ owner_filter: OwnerFilter,
) -> StoreResult<Option<Handoff>> {
self.with_conn(move |conn| {
let mut stmt = conn.prepare(
"SELECT id, workspace_id, project_id, from_session_id, from_agent, to_agent, \
cwd, summary, open_questions, next_steps, files_touched, state, \
- created_at, accepted_by, accepted_at, accepted_by_session \
+ created_at, accepted_by, accepted_at, accepted_by_session, \
+ owner_user, accepted_by_user \
FROM handoffs \
WHERE workspace_id = ?1 AND project_id = ?2 AND state = 'open' \
ORDER BY created_at DESC",
@@ -2941,7 +2985,7 @@ impl ReaderPool {
let mut selected: Option<Handoff> = None;
for r in rows {
let handoff = r??;
- if is_handoff_candidate(&handoff, cwd_filter.as_deref())
+ if is_handoff_candidate(&handoff, cwd_filter.as_deref(), &owner_filter)
&& selected
.as_ref()
.is_none_or(|current| prefer_handoff(&handoff, current).is_gt())
@@ -2954,6 +2998,71 @@ impl ReaderPool {
.await
}
+ /// List a project's handoffs, newest first.
+ ///
+ /// The system had no handoff listing at all: every reader fetched "the
+ /// single open one" and consumed it. That made a mis-delivered or
+ /// prematurely consumed baton unrecoverable and invisible — there was no
+ /// way to ask what happened to it. `state = None` returns every state so an
+ /// operator can find an already-accepted handoff and read it back.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn list_handoffs(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ state: Option<HandoffState>,
+ owner_filter: OwnerFilter,
+ limit: usize,
+ ) -> StoreResult<Vec<Handoff>> {
+ let state = state.map(|s| s.as_str().to_string());
+ self.with_conn(move |conn| {
+ let state_clause = if state.is_some() {
+ " AND state = ?3"
+ } else {
+ ""
+ };
+ // Push the owner predicate and the limit into SQL rather than
+ // filtering a fully materialised result set in Rust: without them
+ // this reads (and sorts) every handoff the project has ever
+ // accumulated, and the caller's limit provides no protection
+ // because it is applied after the rows are already loaded.
+ // The owner key takes the first index the state filter left free, so
+ // the two optional predicates cannot claim the same slot.
+ let owner_index = if state.is_some() { 4 } else { 3 };
+ let (owner_clause, owner_param) = handoff_owner_sql(&owner_filter, owner_index);
+ // Bounded even when the caller asks for a large page.
+ let sql_limit = limit.clamp(1, 500);
+ let sql = format!(
+ "SELECT id, workspace_id, project_id, from_session_id, from_agent, to_agent, \
+ cwd, summary, open_questions, next_steps, files_touched, state, \
+ created_at, accepted_by, accepted_at, accepted_by_session, \
+ owner_user, accepted_by_user \
+ FROM handoffs \
+ WHERE workspace_id = ?1 AND project_id = ?2{state_clause}{owner_clause} \
+ ORDER BY created_at DESC \
+ LIMIT {sql_limit}"
+ );
+ let mut stmt = conn.prepare(&sql)?;
+ let mut binds: Vec<&dyn rusqlite::ToSql> =
+ vec![workspace_id.as_bytes(), project_id.as_bytes()];
+ if let Some(state) = state.as_ref() {
+ binds.push(state);
+ }
+ if let Some(owner) = owner_param.as_ref() {
+ binds.push(owner);
+ }
+ let rows = stmt.query_map(binds.as_slice(), row_to_handoff)?;
+ let mut out = Vec::new();
+ for row in rows {
+ out.push(row??);
+ }
+ Ok(out)
+ })
+ .await
+ }
+
/// Look up a handoff by id.
///
/// # Errors
@@ -2964,7 +3073,8 @@ impl ReaderPool {
.query_row(
"SELECT id, workspace_id, project_id, from_session_id, from_agent, to_agent, \
cwd, summary, open_questions, next_steps, files_touched, state, \
- created_at, accepted_by, accepted_at, accepted_by_session \
+ created_at, accepted_by, accepted_at, accepted_by_session, \
+ owner_user, accepted_by_user \
FROM handoffs WHERE id = ?1",
params![handoff_id.as_bytes()],
row_to_handoff,
@@ -2999,7 +3109,11 @@ impl ReaderPool {
/// # Errors
/// Propagates any SQL or pool error.
#[allow(clippy::too_many_lines)]
- pub async fn briefing(&self, recent_pages_limit: usize) -> StoreResult<BriefingSnapshot> {
+ pub async fn briefing(
+ &self,
+ recent_pages_limit: usize,
+ owner_filter: OwnerFilter,
+ ) -> StoreResult<BriefingSnapshot> {
let recent_limit = recent_pages_limit.clamp(1, 100) as i64;
self.with_conn(move |conn| {
let kind_expr = page_kind_expr("path", "frontmatter_json");
@@ -3028,8 +3142,16 @@ impl ReaderPool {
.and_then(|us| jiff::Timestamp::from_microsecond(us).ok())
.map(|ts| ts.to_string());
- let pending_handoff_count: u64 =
- count(conn, "SELECT COUNT(*) FROM handoffs WHERE state = 'open'")?;
+ let (owner_clause, owner_param) = handoff_owner_sql(&owner_filter, 1);
+ let mut owner_binds: Vec<&dyn rusqlite::ToSql> = Vec::new();
+ if let Some(owner) = owner_param.as_ref() {
+ owner_binds.push(owner);
+ }
+ let pending_handoff_count: u64 = count_bound(
+ conn,
+ &format!("SELECT COUNT(*) FROM handoffs WHERE state = 'open'{owner_clause}"),
+ &owner_binds,
+ )?;
// Rules: any `is_latest = 1` page under `_rules/`.
// Routed there automatically by the consolidator when
@@ -3103,6 +3225,7 @@ impl ReaderPool {
workspace_id: WorkspaceId,
project_id: ProjectId,
recent_pages_limit: usize,
+ owner_filter: OwnerFilter,
) -> StoreResult<BriefingSnapshot> {
let recent_limit = recent_pages_limit.clamp(1, 100) as i64;
self.with_conn(move |conn| {
@@ -3154,11 +3277,19 @@ impl ReaderPool {
.and_then(|us| jiff::Timestamp::from_microsecond(us).ok())
.map(|ts| ts.to_string());
- let pending_handoff_count = count_project(
+ let (owner_clause, owner_param) = handoff_owner_sql(&owner_filter, 3);
+ let mut owner_binds: Vec<&dyn rusqlite::ToSql> =
+ vec![workspace_id.as_bytes(), project_id.as_bytes()];
+ if let Some(owner) = owner_param.as_ref() {
+ owner_binds.push(owner);
+ }
+ let pending_handoff_count = count_bound(
conn,
- "SELECT COUNT(*) FROM handoffs WHERE workspace_id = ?1 AND project_id = ?2 AND state = 'open'",
- workspace_id,
- project_id,
+ &format!(
+ "SELECT COUNT(*) FROM handoffs \
+ WHERE workspace_id = ?1 AND project_id = ?2 AND state = 'open'{owner_clause}"
+ ),
+ &owner_binds,
)?;
let mut rules_stmt = conn.prepare_cached(&format!(
@@ -3330,20 +3461,36 @@ impl ReaderPool {
pub async fn latest_open_handoff_for_workspace(
&self,
workspace_id: WorkspaceId,
+ owner_filter: OwnerFilter,
) -> StoreResult<Option<Handoff>> {
self.with_conn(move |conn| {
- let row_opt = conn
- .query_row(
- "SELECT id, workspace_id, project_id, from_session_id, from_agent, to_agent, \
- cwd, summary, open_questions, next_steps, files_touched, state, \
- created_at, accepted_by, accepted_at, accepted_by_session \
- FROM handoffs \
- WHERE workspace_id = ?1 AND state = 'open' \
- ORDER BY created_at DESC LIMIT 1",
- params![workspace_id.as_bytes()],
- row_to_handoff,
- )
- .optional()?;
+ // The owner predicate is pushed into SQL (rather than filtered after
+ // the fact like the project-scoped lookup) because this query keeps
+ // its `LIMIT 1`: filtering afterwards would return nothing whenever
+ // the newest open handoff in the workspace happened to belong to
+ // somebody else.
+ let owner_clause = match &owner_filter {
+ OwnerFilter::Any => "",
+ OwnerFilter::User(_) => " AND (owner_user IS NULL OR owner_user = ?2)",
+ OwnerFilter::Unattributed => " AND owner_user IS NULL",
+ };
+ let sql = format!(
+ "SELECT id, workspace_id, project_id, from_session_id, from_agent, to_agent, \
+ cwd, summary, open_questions, next_steps, files_touched, state, \
+ created_at, accepted_by, accepted_at, accepted_by_session, \
+ owner_user, accepted_by_user \
+ FROM handoffs \
+ WHERE workspace_id = ?1 AND state = 'open'{owner_clause} \
+ ORDER BY created_at DESC LIMIT 1"
+ );
+ let row_opt = match &owner_filter {
+ OwnerFilter::User(user) => conn
+ .query_row(&sql, params![workspace_id.as_bytes(), user], row_to_handoff)
+ .optional()?,
+ _ => conn
+ .query_row(&sql, params![workspace_id.as_bytes()], row_to_handoff)
+ .optional()?,
+ };
row_opt.transpose()
})
.await
@@ -3411,6 +3558,7 @@ impl ReaderPool {
&self,
workspace_id: WorkspaceId,
recent_pages_limit: usize,
+ owner_filter: OwnerFilter,
) -> StoreResult<BriefingSnapshot> {
let recent_limit = recent_pages_limit.clamp(1, 100) as i64;
self.with_conn(move |conn| {
@@ -3458,10 +3606,18 @@ impl ReaderPool {
.and_then(|us| jiff::Timestamp::from_microsecond(us).ok())
.map(|ts| ts.to_string());
- let pending_handoff_count = count_workspace(
+ let (owner_clause, owner_param) = handoff_owner_sql(&owner_filter, 2);
+ let mut owner_binds: Vec<&dyn rusqlite::ToSql> = vec![workspace_id.as_bytes()];
+ if let Some(owner) = owner_param.as_ref() {
+ owner_binds.push(owner);
+ }
+ let pending_handoff_count = count_bound(
conn,
- "SELECT COUNT(*) FROM handoffs WHERE workspace_id = ?1 AND state = 'open'",
- workspace_id,
+ &format!(
+ "SELECT COUNT(*) FROM handoffs \
+ WHERE workspace_id = ?1 AND state = 'open'{owner_clause}"
+ ),
+ &owner_binds,
)?;
let mut rules_stmt = conn.prepare_cached(&format!(
@@ -5818,7 +5974,41 @@ pub(crate) fn cwd_within(ancestor: &str, descendant: &str) -> bool {
d.starts_with(a.as_ref()) && d.as_bytes().get(a.len()) == Some(&b'/')
}
-fn is_handoff_candidate(h: &Handoff, cwd_filter: Option<&str>) -> bool {
+/// SQL fragment restricting a handoff query to what `filter` can actually see,
+/// plus the owner key it expects bound at `?{param_index}` — the first free
+/// positional parameter of the statement it is spliced into.
+///
+/// The count and the fetch must agree: a briefing that advertises a pending
+/// baton the same caller cannot retrieve is worse than no count at all, because
+/// the agent keeps asking for something that will always come back empty.
+///
+/// The owner key is BOUND, never interpolated. It is not a validated
+/// identifier: it is [`ai_memory_core::IdentityKey::storage_key`] TEXT, and on
+/// a server behind a trusted proxy what follows the prefix is whatever
+/// `X-Memory-Actor-Sub` carried — an OIDC subject the engine never parses — so
+/// nothing upstream constrains its characters.
+fn handoff_owner_sql(filter: &OwnerFilter, param_index: usize) -> (String, Option<String>) {
+ match filter {
+ OwnerFilter::Any => (String::new(), None),
+ OwnerFilter::Unattributed => (" AND owner_user IS NULL".to_string(), None),
+ OwnerFilter::User(user) => (
+ format!(" AND (owner_user IS NULL OR owner_user = ?{param_index})"),
+ Some(user.clone()),
+ ),
+ }
+}
+
+fn is_handoff_candidate(h: &Handoff, cwd_filter: Option<&str>, owner_filter: &OwnerFilter) -> bool {
+ // Ownership is checked FIRST, before the manual short-circuit below.
+ // Order matters: a manual handoff is project-wide by cwd, so checking the
+ // owner afterwards would let one operator's `memory_handoff_begin` be
+ // claimed by the next session to start, whoever it belongs to — the exact
+ // cross-operator mixing this filter exists to stop. Handoffs with no owner
+ // (every pre-V39 row, and anything written without an actor) stay visible
+ // to everyone, which preserves single-operator behaviour untouched.
+ if !owner_filter.admits(h.owner_user.as_deref()) {
+ return false;
+ }
// Manual handoffs (memory_handoff_begin always sets from_session_id = None)
// are project-wide and always candidates, whatever cwd they carry. Only auto
// SessionEnd handoffs are cwd-path-boundary scoped. This makes "a manual
@@ -5895,10 +6085,16 @@ fn prefer_handoff(a: &Handoff, b: &Handoff) -> std::cmp::Ordering {
fn select_open_handoff(candidates: Vec<Handoff>, cwd_filter: Option<&str>) -> Option<Handoff> {
candidates
.into_iter()
- .filter(|h| is_handoff_candidate(h, cwd_filter))
+ .filter(|h| is_handoff_candidate(h, cwd_filter, &OwnerFilter::Any))
.max_by(prefer_handoff)
}
+/// Build a [`Handoff`] from a row selected with the 18-column handoff SELECT
+/// every handoff query in this file shares.
+///
+/// Reading the row here (instead of destructuring it into a long positional
+/// argument list) keeps the column order defined in exactly one place next to
+/// the `SELECT`s that produce it.
fn row_to_handoff(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoreResult<Handoff>> {
let id_bytes: Vec<u8> = row.get(0)?;
let ws_bytes: Vec<u8> = row.get(1)?;
@@ -5916,85 +6112,53 @@ fn row_to_handoff(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoreResult<Hando
let accepted_by: Option<String> = row.get(13)?;
let accepted_at_us: Option<i64> = row.get(14)?;
let accepted_by_session_bytes: Option<Vec<u8>> = row.get(15)?;
- Ok(materialise_handoff(
- id_bytes,
- ws_bytes,
- pj_bytes,
- from_session_bytes,
- from_agent,
- to_agent,
- cwd,
- summary,
- open_q_json,
- next_s_json,
- files_json,
- state,
- created_us,
- accepted_by,
- accepted_at_us,
- accepted_by_session_bytes,
- ))
-}
-
-#[allow(clippy::too_many_arguments)]
-fn materialise_handoff(
- id_bytes: Vec<u8>,
- ws_bytes: Vec<u8>,
- pj_bytes: Vec<u8>,
- from_session_bytes: Option<Vec<u8>>,
- from_agent: String,
- to_agent: Option<String>,
- cwd: Option<String>,
- summary: String,
- open_q_json: String,
- next_s_json: String,
- files_json: String,
- state: String,
- created_us: i64,
- accepted_by: Option<String>,
- accepted_at_us: Option<i64>,
- accepted_by_session_bytes: Option<Vec<u8>>,
-) -> StoreResult<Handoff> {
- let open_questions: Vec<String> = serde_json::from_str(&open_q_json)?;
- let next_steps: Vec<String> = serde_json::from_str(&next_s_json)?;
- let files_touched: Vec<String> = serde_json::from_str(&files_json)?;
- let from_session = from_session_bytes
- .as_deref()
- .map(SessionId::from_slice)
- .transpose()?;
- let accepted_session = accepted_by_session_bytes
- .as_deref()
- .map(SessionId::from_slice)
- .transpose()?;
- Ok(Handoff {
- id: HandoffId::from_slice(&id_bytes)?,
- workspace_id: WorkspaceId::from_slice(&ws_bytes)?,
- project_id: ProjectId::from_slice(&pj_bytes)?,
- from_session_id: from_session,
- from_agent: parse_agent(&from_agent),
- to_agent: to_agent.as_deref().map(parse_agent),
- cwd,
- summary,
- open_questions,
- next_steps,
- files_touched,
- state: state.parse::<HandoffState>().map_err(StoreError::from)?,
- created_at: jiff::Timestamp::from_microsecond(created_us).map_err(|e| {
- StoreError::Memory(ai_memory_core::MemoryError::MalformedRecord(format!(
- "bad created_at: {e}"
- )))
- })?,
- accepted_by: accepted_by.as_deref().map(parse_agent),
- accepted_at: accepted_at_us
- .map(jiff::Timestamp::from_microsecond)
- .transpose()
- .map_err(|e| {
+ let owner_user: Option<String> = row.get(16)?;
+ let accepted_by_user: Option<String> = row.get(17)?;
+
+ Ok((|| {
+ let open_questions: Vec<String> = serde_json::from_str(&open_q_json)?;
+ let next_steps: Vec<String> = serde_json::from_str(&next_s_json)?;
+ let files_touched: Vec<String> = serde_json::from_str(&files_json)?;
+ let from_session = from_session_bytes
+ .as_deref()
+ .map(SessionId::from_slice)
+ .transpose()?;
+ let accepted_session = accepted_by_session_bytes
+ .as_deref()
+ .map(SessionId::from_slice)
+ .transpose()?;
+ Ok(Handoff {
+ id: HandoffId::from_slice(&id_bytes)?,
+ workspace_id: WorkspaceId::from_slice(&ws_bytes)?,
+ project_id: ProjectId::from_slice(&pj_bytes)?,
+ from_session_id: from_session,
+ from_agent: parse_agent(&from_agent),
+ to_agent: to_agent.as_deref().map(parse_agent),
+ cwd,
+ summary,
+ open_questions,
+ next_steps,
+ files_touched,
+ state: state.parse::<HandoffState>().map_err(StoreError::from)?,
+ created_at: jiff::Timestamp::from_microsecond(created_us).map_err(|e| {
StoreError::Memory(ai_memory_core::MemoryError::MalformedRecord(format!(
- "bad accepted_at: {e}"
+ "bad created_at: {e}"
)))
})?,
- accepted_by_session: accepted_session,
- })
+ accepted_by: accepted_by.as_deref().map(parse_agent),
+ accepted_at: accepted_at_us
+ .map(jiff::Timestamp::from_microsecond)
+ .transpose()
+ .map_err(|e| {
+ StoreError::Memory(ai_memory_core::MemoryError::MalformedRecord(format!(
+ "bad accepted_at: {e}"
+ )))
+ })?,
+ accepted_by_session: accepted_session,
+ owner_user,
+ accepted_by_user,
+ })
+ })())
}
fn parse_agent(s: &str) -> AgentKind {
@@ -6002,7 +6166,17 @@ fn parse_agent(s: &str) -> AgentKind {
}
fn count(conn: &Connection, sql: &str) -> StoreResult<u64> {
- let n: Option<i64> = conn.query_row(sql, [], |row| row.get(0)).optional()?;
+ count_bound(conn, sql, &[])
+}
+
+/// `COUNT(*)` with an explicit parameter list.
+///
+/// The scope-less [`count`] and the scoped `count_project` / `count_workspace`
+/// helpers each bind a fixed shape; a predicate spliced in by the caller (the
+/// handoff owner filter) adds one more parameter to whichever shape it lands in,
+/// so it needs a helper that takes the whole list.
+fn count_bound(conn: &Connection, sql: &str, params: &[&dyn rusqlite::ToSql]) -> StoreResult<u64> {
+ let n: Option<i64> = conn.query_row(sql, params, |row| row.get(0)).optional()?;
Ok(u64::try_from(n.unwrap_or(0)).unwrap_or(0))
}
@@ -6266,6 +6440,8 @@ mod tests {
accepted_by: None,
accepted_at: None,
accepted_by_session: None,
+ owner_user: None,
+ accepted_by_user: None,
}
}
@@ -6464,6 +6640,7 @@ mod tests {
open_questions: vec![],
next_steps: vec![],
files_touched: vec![],
+ owner_user: None,
})
.await
.unwrap();
@@ -6480,13 +6657,19 @@ mod tests {
open_questions: vec![],
next_steps: vec![],
files_touched: vec![],
+ owner_user: None,
})
.await
.unwrap();
let handoff = store
.reader
- .latest_open_handoff(ws_a, proj_a, Some("/repo".into()))
+ .latest_open_handoff(
+ ws_a,
+ proj_a,
+ Some("/repo".into()),
+ ai_memory_core::OwnerFilter::Any,
+ )
.await
.unwrap()
.unwrap();
@@ -6524,6 +6707,7 @@ mod tests {
project_id,
agent_kind: AgentKind::ClaudeCode,
cwd: Some(cwd.into()),
+ actor_user: None,
})
.await
.unwrap();
@@ -6540,6 +6724,7 @@ mod tests {
open_questions: vec![],
next_steps: vec![],
files_touched: vec![],
+ owner_user: None,
})
.await
.unwrap()
@@ -6566,7 +6751,12 @@ mod tests {
let selected = store
.reader
- .latest_open_handoff(ws, proj, Some("/repo/api/src".into()))
+ .latest_open_handoff(
+ ws,
+ proj,
+ Some("/repo/api/src".into()),
+ ai_memory_core::OwnerFilter::Any,
+ )
.await
.unwrap()
.unwrap();
@@ -6587,6 +6777,7 @@ mod tests {
open_questions: vec![],
next_steps: vec![],
files_touched: vec![],
+ owner_user: None,
})
.await
.unwrap();
@@ -6596,6 +6787,8 @@ mod tests {
selected.id,
AgentKind::Codex,
None,
+ None,
+ ai_memory_core::OwnerFilter::Any,
Some("/repo/api/src".into()),
)
.await
diff --git a/crates/ai-memory-store/src/session_consolidation.rs b/crates/ai-memory-store/src/session_consolidation.rs
index 7454e9e4..46d4e2a3 100644
--- a/crates/ai-memory-store/src/session_consolidation.rs
+++ b/crates/ai-memory-store/src/session_consolidation.rs
@@ -341,6 +341,7 @@ mod tests {
project_id,
agent_kind: AgentKind::Codex,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index 6111c0be..4a9695c9 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -12,7 +12,8 @@ use std::thread::{self, JoinHandle};
use ai_memory_core::{
AgentKind, HandoffId, ManagedRunId, NewHandoff, NewObservation, NewPage, NewSession, NewUser,
- ObservationId, PageId, PagePath, ProjectId, Sanitized, SessionId, UserId, WorkspaceId,
+ ObservationId, OwnerFilter, PageId, PagePath, ProjectId, Sanitized, SessionId, UserId,
+ WorkspaceId,
};
use rusqlite::Connection;
use tokio::sync::{mpsc, oneshot};
@@ -165,11 +166,14 @@ pub(crate) enum WriteCmd {
handoff_id: HandoffId,
accepting_agent: AgentKind,
accepting_session: Option<SessionId>,
+ accepting_user: Option<String>,
+ owner_filter: OwnerFilter,
receiving_cwd: Option<String>,
- reply: oneshot::Sender<StoreResult<()>>,
+ reply: oneshot::Sender<StoreResult<bool>>,
},
CancelHandoff {
handoff_id: HandoffId,
+ owner_filter: OwnerFilter,
reply: oneshot::Sender<StoreResult<bool>>,
},
/// Retro-fit sessions + observations to per-cwd projects and graveyard
@@ -366,6 +370,8 @@ pub(crate) enum WriteCmd {
handoff_id: Option<HandoffId>,
accepting_agent: AgentKind,
accepting_session: Option<SessionId>,
+ accepting_user: Option<String>,
+ owner_filter: OwnerFilter,
managed_run_id: Option<ManagedRunId>,
receiving_cwd: Option<String>,
reply: oneshot::Sender<StoreResult<StartupContextAcceptance>>,
@@ -751,6 +757,12 @@ impl WriterHandle {
/// Mark a handoff accepted by the given agent / session.
///
+ /// Returns whether this call is the one that claimed it; `false` means the
+ /// row was already taken or its owner does not admit this caller, and the
+ /// body must not reach the agent. `receiving_cwd` is where the claiming
+ /// session is starting, and bounds the sweep of superseded automatic
+ /// handoffs.
+ ///
/// # Errors
/// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
pub async fn accept_handoff(
@@ -758,13 +770,17 @@ impl WriterHandle {
handoff_id: HandoffId,
accepting_agent: AgentKind,
accepting_session: Option<SessionId>,
+ accepting_user: Option<String>,
+ owner_filter: OwnerFilter,
receiving_cwd: Option<String>,
- ) -> StoreResult<()> {
+ ) -> StoreResult<bool> {
let (tx, rx) = oneshot::channel();
self.send(WriteCmd::AcceptHandoff {
handoff_id,
accepting_agent,
accepting_session,
+ accepting_user,
+ owner_filter,
receiving_cwd,
reply: tx,
})
@@ -779,10 +795,15 @@ impl WriterHandle {
///
/// # Errors
/// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
- pub async fn cancel_handoff(&self, handoff_id: HandoffId) -> StoreResult<bool> {
+ pub async fn cancel_handoff(
+ &self,
+ handoff_id: HandoffId,
+ owner_filter: OwnerFilter,
+ ) -> StoreResult<bool> {
let (tx, rx) = oneshot::channel();
self.send(WriteCmd::CancelHandoff {
handoff_id,
+ owner_filter,
reply: tx,
})
.await?;
@@ -1440,11 +1461,14 @@ impl WriterHandle {
///
/// When a managed run was requested but is no longer claimable, the
/// handoff remains open and both result fields are false.
+ #[allow(clippy::too_many_arguments)]
pub async fn accept_startup_context(
&self,
handoff_id: Option<HandoffId>,
accepting_agent: AgentKind,
accepting_session: Option<SessionId>,
+ accepting_user: Option<String>,
+ owner_filter: OwnerFilter,
managed_run_id: Option<ManagedRunId>,
receiving_cwd: Option<String>,
) -> StoreResult<StartupContextAcceptance> {
@@ -1453,6 +1477,8 @@ impl WriterHandle {
handoff_id,
accepting_agent,
accepting_session,
+ accepting_user,
+ owner_filter,
managed_run_id,
receiving_cwd,
reply: tx,
@@ -1703,6 +1729,8 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
handoff_id,
accepting_agent,
accepting_session,
+ accepting_user,
+ owner_filter,
receiving_cwd,
reply,
} => {
@@ -1711,12 +1739,18 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
&handoff_id,
accepting_agent,
accepting_session.as_ref(),
+ accepting_user.as_deref(),
+ &owner_filter,
receiving_cwd.as_deref(),
);
send_or_warn(reply, result, "accept_handoff");
}
- WriteCmd::CancelHandoff { handoff_id, reply } => {
- let result = ops::cancel_handoff(&mut conn, &handoff_id);
+ WriteCmd::CancelHandoff {
+ handoff_id,
+ owner_filter,
+ reply,
+ } => {
+ let result = ops::cancel_handoff(&mut conn, &handoff_id, &owner_filter);
send_or_warn(reply, result, "cancel_handoff");
}
WriteCmd::Reorg {
@@ -1997,6 +2031,8 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
handoff_id,
accepting_agent,
accepting_session,
+ accepting_user,
+ owner_filter,
managed_run_id,
receiving_cwd,
reply,
@@ -2018,6 +2054,8 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
&handoff_id,
accepting_agent,
accepting_session.as_ref(),
+ accepting_user.as_deref(),
+ &owner_filter,
receiving_cwd.as_deref(),
)?,
None => false,
diff --git a/crates/ai-memory-store/tests/handoff_ownership.rs b/crates/ai-memory-store/tests/handoff_ownership.rs
new file mode 100644
index 00000000..21c00d88
--- /dev/null
+++ b/crates/ai-memory-store/tests/handoff_ownership.rs
@@ -0,0 +1,731 @@
+//! Integration tests for per-operator handoff ownership (V39).
+//!
+//! The behaviour these pin down is the one that breaks a shared server: the
+//! open-handoff lookup used to be scoped by `(workspace, project, state)` only,
+//! so the next session to start — whoever it belonged to — consumed the pending
+//! baton, and its author never received it. Delivery is destructive, so the
+//! handoff was simply lost.
+//!
+//! Owners are stored as qualified [`IdentityKey::storage_key`] TEXT
+//! (`user:alice`, `sub:…`), never raw names. Every owner and filter here is
+//! built through the contract's own API — `owner_stamp`,
+//! [`OwnerFilter::for_actor_context`], [`IdentityKey::storage_key`] — so these
+//! tests exercise the same encoding production uses rather than a hand-written
+//! string that could drift from it.
+
+use ai_memory_core::{
+ ActorContext, AgentKind, IdentityKey, NewHandoff, OwnerFilter, ProjectId, WorkspaceId,
+ owner_stamp,
+};
+use ai_memory_store::Store;
+
+/// The qualified storage key a username-identified operator owns rows under.
+fn operator(name: &str) -> String {
+ IdentityKey::User(name.into()).storage_key()
+}
+
+/// The read filter the same operator's requests resolve to, built through the
+/// one identity rule instead of a hand-assembled variant.
+fn filter_for(name: &str) -> OwnerFilter {
+ OwnerFilter::for_actor_context(&ActorContext {
+ user: Some(name.into()),
+ ..ActorContext::default()
+ })
+}
+
+/// Build an open handoff, optionally owned by the named operator.
+fn handoff(
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ summary: &str,
+ owner: Option<&str>,
+) -> NewHandoff {
+ NewHandoff {
+ workspace_id,
+ project_id,
+ // `None` is what `memory_handoff_begin` writes: a manual handoff. It is
+ // the shape that used to be project-wide AND top of the ranking, so it
+ // is the one that leaked across operators.
+ from_session_id: None,
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: None,
+ summary: summary.into(),
+ open_questions: Vec::new(),
+ next_steps: Vec::new(),
+ files_touched: Vec::new(),
+ // The write-side gate, exactly as a distinguishing deployment applies
+ // it: identity in, storage key out.
+ owner_user: owner.and_then(|name| owner_stamp(Some(&IdentityKey::User(name.into())), true)),
+ }
+}
+
+async fn scope(store: &Store) -> (WorkspaceId, ProjectId) {
+ let ws = store
+ .writer
+ .get_or_create_workspace("acme-hml".to_string())
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "team-app".to_string(), None)
+ .await
+ .unwrap();
+ (ws, proj)
+}
+
+/// The core regression: Alice leaves a baton, Bob starts a session in the same
+/// project, and Bob must not receive — or consume — it.
+#[tokio::test]
+async fn one_operators_handoff_is_not_delivered_to_another() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+
+ store
+ .writer
+ .insert_handoff(handoff(
+ ws,
+ proj,
+ "resume the OAuth refactor",
+ Some("alice"),
+ ))
+ .await
+ .unwrap();
+
+ // Bob's session start finds nothing: the only open handoff is Alice's.
+ assert!(
+ store
+ .reader
+ .latest_open_handoff(ws, proj, None, filter_for("bob"))
+ .await
+ .unwrap()
+ .is_none(),
+ "Bob must not be offered Alice's handoff"
+ );
+
+ // And Alice still has hers — the point is that it was never consumed.
+ let alice = store
+ .reader
+ .latest_open_handoff(ws, proj, None, filter_for("alice"))
+ .await
+ .unwrap()
+ .expect("Alice keeps her own handoff");
+ assert_eq!(alice.summary, "resume the OAuth refactor");
+ assert_eq!(alice.owner_user, Some(operator("alice")));
+}
+
+/// The variant is part of the identity: a username equal to somebody else's
+/// OIDC subject is a DIFFERENT operator, and neither may drain the other's
+/// baton. Raw TEXT owners would have merged these two people.
+#[tokio::test]
+async fn a_username_does_not_alias_an_equal_subject() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+
+ let by_subject = IdentityKey::Subject("alice".into());
+ let mut owned = handoff(ws, proj, "the subject's baton", None);
+ owned.owner_user = owner_stamp(Some(&by_subject), true);
+ store.writer.insert_handoff(owned).await.unwrap();
+
+ // The USERNAME alice — same raw string, different name space.
+ assert!(
+ store
+ .reader
+ .latest_open_handoff(ws, proj, None, filter_for("alice"))
+ .await
+ .unwrap()
+ .is_none(),
+ "user:alice must not receive sub:alice's baton"
+ );
+ // The subject-identified caller — the filter the auth layer builds for an
+ // ingress that forwards only the `sub` claim.
+ let sub_filter = OwnerFilter::for_actor_context(&ActorContext {
+ sub: Some("alice".into()),
+ ..ActorContext::default()
+ });
+ assert!(
+ store
+ .reader
+ .latest_open_handoff(ws, proj, None, sub_filter)
+ .await
+ .unwrap()
+ .is_some(),
+ "the subject-identified operator keeps their own baton"
+ );
+}
+
+/// Backwards compatibility, and the single-operator path: a handoff with no
+/// owner (every pre-V39 row, anything written without an actor, and an explicit
+/// `shared: true`) is still delivered to anybody.
+#[tokio::test]
+async fn shared_handoffs_are_delivered_to_everyone() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+
+ store
+ .writer
+ .insert_handoff(handoff(ws, proj, "team baton", None))
+ .await
+ .unwrap();
+
+ for filter in [
+ filter_for("alice"),
+ filter_for("bob"),
+ OwnerFilter::Unattributed,
+ OwnerFilter::Any,
+ ] {
+ let got = store
+ .reader
+ .latest_open_handoff(ws, proj, None, filter.clone())
+ .await
+ .unwrap();
+ assert!(
+ got.is_some(),
+ "an unowned handoff must stay visible to {filter:?}"
+ );
+ }
+}
+
+/// Claiming is guarded in the same UPDATE that flips the state, so a caller who
+/// is not admitted changes zero rows and is told so — the body must not be
+/// handed over on `false`.
+#[tokio::test]
+async fn another_operator_cannot_claim_the_handoff() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+
+ let id = store
+ .writer
+ .insert_handoff(handoff(ws, proj, "alice's baton", Some("alice")))
+ .await
+ .unwrap();
+
+ let stolen = store
+ .writer
+ .accept_handoff(
+ id,
+ AgentKind::ClaudeCode,
+ None,
+ Some(operator("bob")),
+ filter_for("bob"),
+ None,
+ )
+ .await
+ .unwrap();
+ assert!(!stolen, "Bob must not be able to claim Alice's handoff");
+
+ // Still open for its owner, and now claimable by her exactly once.
+ let claimed = store
+ .writer
+ .accept_handoff(
+ id,
+ AgentKind::ClaudeCode,
+ None,
+ Some(operator("alice")),
+ filter_for("alice"),
+ None,
+ )
+ .await
+ .unwrap();
+ assert!(claimed, "the owner claims her own handoff");
+
+ let twice = store
+ .writer
+ .accept_handoff(
+ id,
+ AgentKind::ClaudeCode,
+ None,
+ Some(operator("alice")),
+ filter_for("alice"),
+ None,
+ )
+ .await
+ .unwrap();
+ assert!(!twice, "a handoff is single-use even for its owner");
+
+ // The acceptance is attributed to a person, not just an agent kind, so
+ // "who took my baton" is answerable after the fact.
+ let row = store.reader.handoff_by_id(id).await.unwrap().unwrap();
+ assert_eq!(row.accepted_by_user, Some(operator("alice")));
+}
+
+/// An unattributed reader — the read-only `/api/v1` surface a browser reaches —
+/// must not see a baton that belongs to somebody, because rendering it leaks the
+/// raw prompt text it was built from.
+#[tokio::test]
+async fn unattributed_readers_do_not_see_owned_handoffs() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+
+ store
+ .writer
+ .insert_handoff(handoff(ws, proj, "private context", Some("alice")))
+ .await
+ .unwrap();
+
+ assert!(
+ store
+ .reader
+ .latest_open_handoff(ws, proj, None, OwnerFilter::Unattributed)
+ .await
+ .unwrap()
+ .is_none()
+ );
+ // The workspace-wide overview query takes the same filter.
+ assert!(
+ store
+ .reader
+ .latest_open_handoff_for_workspace(ws, OwnerFilter::Unattributed)
+ .await
+ .unwrap()
+ .is_none()
+ );
+ // …while an explicit recovery read still finds it.
+ assert!(
+ store
+ .reader
+ .latest_open_handoff_for_workspace(ws, OwnerFilter::Any)
+ .await
+ .unwrap()
+ .is_some()
+ );
+}
+
+/// Cancelling is scoped like accepting: you can discard your own baton, not a
+/// teammate's.
+#[tokio::test]
+async fn another_operator_cannot_cancel_the_handoff() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+
+ let id = store
+ .writer
+ .insert_handoff(handoff(ws, proj, "alice's baton", Some("alice")))
+ .await
+ .unwrap();
+
+ assert!(
+ !store
+ .writer
+ .cancel_handoff(id, filter_for("bob"))
+ .await
+ .unwrap(),
+ "Bob must not cancel Alice's handoff"
+ );
+ assert!(
+ store
+ .writer
+ .cancel_handoff(id, filter_for("alice"))
+ .await
+ .unwrap(),
+ "the owner can cancel her own"
+ );
+}
+
+/// An owned handoff must not be reachable just because the caller asks with a
+/// different cwd: ownership is checked BEFORE the manual/cwd rules, which is
+/// what stops `memory_handoff_begin` rows (always manual, always project-wide by
+/// cwd) from crossing operators.
+#[tokio::test]
+async fn ownership_is_checked_before_the_manual_cwd_shortcut() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+
+ let mut owned = handoff(ws, proj, "alice's manual baton", Some("alice"));
+ owned.cwd = Some("/home/alice/src/team-app".into());
+ store.writer.insert_handoff(owned).await.unwrap();
+
+ // Bob asks from his own checkout; the manual short-circuit would have
+ // matched regardless of cwd before ownership existed.
+ assert!(
+ store
+ .reader
+ .latest_open_handoff(
+ ws,
+ proj,
+ Some("/home/bob/src/team-app".into()),
+ filter_for("bob"),
+ )
+ .await
+ .unwrap()
+ .is_none()
+ );
+}
+
+/// Handoffs had no listing anywhere in the system — every reader fetched the
+/// single pending one and consumed it, so a baton delivered to the wrong place
+/// simply vanished with no way to look it up. The listing is what makes that
+/// recoverable, and it is owner-scoped so it does not become a way to read
+/// other operators' context.
+#[tokio::test]
+async fn handoff_listing_is_owner_scoped_and_covers_every_state() {
+ use ai_memory_core::HandoffState;
+
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+
+ let alice = store
+ .writer
+ .insert_handoff(handoff(ws, proj, "alice's", Some("alice")))
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_handoff(handoff(ws, proj, "bob's", Some("bob")))
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_handoff(handoff(ws, proj, "team", None))
+ .await
+ .unwrap();
+
+ // Alice sees hers + the shared one, never Bob's.
+ let summaries = |filter: OwnerFilter, state: Option<HandoffState>| {
+ let store = &store;
+ async move {
+ store
+ .reader
+ .list_handoffs(ws, proj, state, filter, 50)
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|h| h.summary)
+ .collect::<Vec<_>>()
+ }
+ };
+ let seen = summaries(filter_for("alice"), None).await;
+ assert!(seen.contains(&"alice's".to_string()));
+ assert!(seen.contains(&"team".to_string()));
+ assert!(!seen.contains(&"bob's".to_string()));
+
+ // Consume Alice's, then find it again by state — the recovery path.
+ store
+ .writer
+ .accept_handoff(
+ alice,
+ AgentKind::ClaudeCode,
+ None,
+ Some(operator("alice")),
+ filter_for("alice"),
+ None,
+ )
+ .await
+ .unwrap();
+ let open = summaries(filter_for("alice"), Some(HandoffState::Open)).await;
+ assert!(!open.contains(&"alice's".to_string()), "no longer pending");
+ let accepted = summaries(filter_for("alice"), Some(HandoffState::Accepted)).await;
+ assert_eq!(
+ accepted,
+ vec!["alice's".to_string()],
+ "a consumed handoff is still findable, which is what makes it recoverable"
+ );
+}
+
+/// The owner key is not a validated identifier: behind a trusted proxy what
+/// follows the `sub:` prefix is whatever `X-Memory-Actor-Sub` carried, an OIDC
+/// subject the engine never parses. A value carrying a single quote therefore
+/// has to filter exactly like any other one, on every surface that splices the
+/// owner predicate into SQL — the listing (with and without a state filter) and
+/// all three briefing counts.
+#[tokio::test]
+async fn an_owner_name_with_a_quote_filters_like_any_other() {
+ use ai_memory_core::HandoffState;
+
+ let quoted = "o'brien";
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+
+ store
+ .writer
+ .insert_handoff(handoff(ws, proj, "quoted", Some(quoted)))
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_handoff(handoff(ws, proj, "bob's", Some("bob")))
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_handoff(handoff(ws, proj, "team", None))
+ .await
+ .unwrap();
+
+ let filter = || filter_for(quoted);
+
+ let seen = store
+ .reader
+ .list_handoffs(ws, proj, None, filter(), 50)
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|h| h.summary)
+ .collect::<Vec<_>>();
+ assert!(seen.contains(&"quoted".to_string()), "own row: {seen:?}");
+ assert!(seen.contains(&"team".to_string()), "shared row: {seen:?}");
+ assert!(!seen.contains(&"bob's".to_string()), "leak: {seen:?}");
+
+ // The state filter shifts the owner parameter one slot along, so it is the
+ // arm most likely to bind the key into the wrong placeholder.
+ let open = store
+ .reader
+ .list_handoffs(ws, proj, Some(HandoffState::Open), filter(), 50)
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|h| h.summary)
+ .collect::<Vec<_>>();
+ assert_eq!(open.len(), 2, "own + shared, still no leak: {open:?}");
+
+ for count in [
+ store
+ .reader
+ .briefing(5, filter())
+ .await
+ .unwrap()
+ .pending_handoff_count,
+ store
+ .reader
+ .briefing_for_project(ws, proj, 5, filter())
+ .await
+ .unwrap()
+ .pending_handoff_count,
+ store
+ .reader
+ .briefing_for_workspace(ws, 5, filter())
+ .await
+ .unwrap()
+ .pending_handoff_count,
+ ] {
+ assert_eq!(count, 2, "count must agree with the listing");
+ }
+}
+
+/// Automatic handoffs are retired in bulk — once when a new SessionEnd handoff
+/// lands in the same directory, and again after a claim supersedes older
+/// eligible ones. Both sweeps are cwd-scoped, and on a shared server several
+/// operators work in the SAME directory (frequently the same container path),
+/// so cwd separates nothing between them. Without an owner predicate the sweeps
+/// destroy another operator's pending baton outright, which is worse than the
+/// misdelivery ownership exists to prevent: nothing is delivered at all.
+#[tokio::test]
+async fn automatic_supersession_does_not_reach_across_operators() {
+ use ai_memory_core::{HandoffState, NewSession, SessionId};
+
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+
+ // Same project, same cwd, one handoff each — the shape upstream's sweeps
+ // treat as a single stream of supersedable batons. Session and baton carry
+ // the SAME stamped key, exactly as the SessionEnd path writes them.
+ async fn auto_handoff(
+ store: &Store,
+ ws: WorkspaceId,
+ proj: ProjectId,
+ owner: &str,
+ summary: &str,
+ ) -> ai_memory_core::HandoffId {
+ let session_id = SessionId::new();
+ let stamp = owner_stamp(Some(&IdentityKey::User(owner.into())), true);
+ store
+ .writer
+ .begin_session(NewSession {
+ id: session_id,
+ workspace_id: ws,
+ project_id: proj,
+ agent_kind: AgentKind::ClaudeCode,
+ cwd: Some("/repo".into()),
+ actor_user: stamp.clone(),
+ })
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_handoff(NewHandoff {
+ workspace_id: ws,
+ project_id: proj,
+ from_session_id: Some(session_id),
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: Some("/repo".into()),
+ summary: summary.into(),
+ open_questions: Vec::new(),
+ next_steps: Vec::new(),
+ files_touched: Vec::new(),
+ owner_user: stamp,
+ })
+ .await
+ .unwrap()
+ }
+
+ let bob = auto_handoff(&store, ws, proj, "bob", "bob's baton").await;
+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;
+ // Alice ending a session in /repo must not expire Bob's open handoff from
+ // the same directory (`insert_handoff_row`'s same-cwd sweep).
+ let alice_older = auto_handoff(&store, ws, proj, "alice", "alice's older").await;
+ assert_eq!(
+ store
+ .reader
+ .handoff_by_id(bob)
+ .await
+ .unwrap()
+ .unwrap()
+ .state,
+ HandoffState::Open,
+ "another operator's SessionEnd must not expire Bob's baton"
+ );
+
+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;
+ let alice_newest = auto_handoff(&store, ws, proj, "alice", "alice's newest").await;
+ assert_eq!(
+ store
+ .reader
+ .handoff_by_id(alice_older)
+ .await
+ .unwrap()
+ .unwrap()
+ .state,
+ HandoffState::Expired,
+ "within one operator, the same-cwd sweep still bounds accumulation"
+ );
+
+ // And the post-claim sweep is bounded the same way: Alice claiming her own
+ // baton retires nothing of Bob's, even though his row matches the cwd rule
+ // and ranks below hers.
+ let claimed = store
+ .writer
+ .accept_handoff(
+ alice_newest,
+ AgentKind::ClaudeCode,
+ None,
+ Some(operator("alice")),
+ filter_for("alice"),
+ Some("/repo".into()),
+ )
+ .await
+ .unwrap();
+ assert!(claimed, "Alice claims her own handoff");
+ assert_eq!(
+ store
+ .reader
+ .handoff_by_id(bob)
+ .await
+ .unwrap()
+ .unwrap()
+ .state,
+ HandoffState::Open,
+ "Alice's session start must not expire Bob's pending baton"
+ );
+
+ // Bob still receives it, which is the whole point.
+ let bobs = store
+ .reader
+ .latest_open_handoff(ws, proj, Some("/repo".into()), filter_for("bob"))
+ .await
+ .unwrap()
+ .expect("Bob's baton survives another operator's accept");
+ assert_eq!(bobs.summary, "bob's baton");
+}
+
+/// Sessions record their operator (V40), and the open-session lookup behind
+/// `finalize-session` is scoped the same way. The callers act destructively on
+/// what this returns — ending the session, synthesising a page from its
+/// observations, minting a handoff from its raw prompts — so "the newest open
+/// session in the scope" across everyone would do all of that to a colleague's
+/// live session. A session with no recorded operator stays visible to every
+/// filter, which is the single-operator behaviour.
+#[tokio::test]
+async fn open_session_lookup_is_owner_scoped() {
+ use ai_memory_core::{NewSession, SessionId};
+
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+
+ let alice_session = SessionId::new();
+ let shared_session = SessionId::new();
+ for (id, owner) in [
+ (
+ alice_session,
+ owner_stamp(Some(&IdentityKey::User("alice".into())), true),
+ ),
+ (shared_session, None),
+ ] {
+ store
+ .writer
+ .begin_session(NewSession {
+ id,
+ workspace_id: ws,
+ project_id: proj,
+ agent_kind: AgentKind::ClaudeCode,
+ cwd: None,
+ actor_user: owner,
+ })
+ .await
+ .unwrap();
+ }
+
+ let ids = |sessions: Vec<ai_memory_store::OpenSession>| {
+ sessions
+ .into_iter()
+ .map(|s| s.session_id)
+ .collect::<Vec<_>>()
+ };
+
+ // Bob sees only the shared session — never Alice's live one.
+ let bobs = ids(store
+ .reader
+ .open_sessions_for_scope_agent(ws, proj, AgentKind::ClaudeCode, filter_for("bob"), None)
+ .await
+ .unwrap());
+ assert_eq!(
+ bobs,
+ vec![shared_session],
+ "Bob must not see Alice's session"
+ );
+
+ // Alice sees her own plus the shared one.
+ let alices = ids(store
+ .reader
+ .open_sessions_for_scope_agent(ws, proj, AgentKind::ClaudeCode, filter_for("alice"), None)
+ .await
+ .unwrap());
+ assert!(alices.contains(&alice_session) && alices.contains(&shared_session));
+
+ // The recovery switch (`all_owners=true` on /admin/open-sessions) sees all.
+ let all = ids(store
+ .reader
+ .open_sessions_for_scope_agent(ws, proj, AgentKind::ClaudeCode, OwnerFilter::Any, None)
+ .await
+ .unwrap());
+ assert_eq!(all.len(), 2);
+
+ // The owner travels to the SessionEnd attribution path via the same row.
+ assert_eq!(
+ store
+ .reader
+ .session_actor_user(alice_session)
+ .await
+ .unwrap(),
+ Some(operator("alice")),
+ );
+ assert_eq!(
+ store
+ .reader
+ .session_actor_user(shared_session)
+ .await
+ .unwrap(),
+ None,
+ );
+}
diff --git a/crates/ai-memory-web/src/routes/api.rs b/crates/ai-memory-web/src/routes/api.rs
index d0421db5..8b14e18d 100644
--- a/crates/ai-memory-web/src/routes/api.rs
+++ b/crates/ai-memory-web/src/routes/api.rs
@@ -57,6 +57,10 @@ pub(crate) fn build(state: Arc<WebState>) -> Router {
"/workspaces/{workspace}/projects/{project}/overview",
axum::routing::get(project_overview_handler),
)
+ .route(
+ "/workspaces/{workspace}/projects/{project}/handoffs",
+ axum::routing::get(handoffs_handler),
+ )
.route("/graph", axum::routing::get(graph_handler))
.with_state(state)
}
@@ -414,13 +418,19 @@ async fn recent_handler(
async fn briefing_handler(
State(state): State<Arc<WebState>>,
+ actor: Option<axum::Extension<ai_memory_core::ActorContext>>,
Path((workspace, project)): Path<(String, String)>,
Query(query): Query<LimitQuery>,
) -> Result<Response, Response> {
let (workspace_id, project_id) = lookup_project(&state, &workspace, &project).await?;
let briefing = state
.reader
- .briefing_for_project(workspace_id, project_id, query.limit.clamp(1, 100))
+ .briefing_for_project(
+ workspace_id,
+ project_id,
+ query.limit.clamp(1, 100),
+ owner_filter_for(actor),
+ )
.await
.map_err(internal_error)?;
Ok(with_cache(
@@ -431,6 +441,7 @@ async fn briefing_handler(
async fn overview_handler(
State(state): State<Arc<WebState>>,
+ actor: Option<axum::Extension<ai_memory_core::ActorContext>>,
Path(workspace): Path<String>,
Query(query): Query<LimitQuery>,
) -> Result<Response, Response> {
@@ -441,9 +452,18 @@ async fn overview_handler(
.map_err(internal_error)?
.ok_or_else(|| not_found(format!("workspace '{workspace}' not found")))?;
+ // Scoped to the requesting actor, like the briefing below and like
+ // `project_overview_handler`: an identified caller sees their own baton plus
+ // the shared ones, a browser the server cannot attribute sees only the
+ // shared ones — so an owned handoff, and the raw prompt text inside it, is
+ // never rendered to someone it does not belong to. Pinning this to
+ // "unattributed" instead would make the card permanently empty on any server
+ // that stamps an owner, while `pending_handoff_count` in the briefing beside
+ // it — which does apply the actor's filter — kept counting the same row.
+ let owner_filter = owner_filter_for(actor);
let handoff = match state
.reader
- .latest_open_handoff_for_workspace(workspace_id)
+ .latest_open_handoff_for_workspace(workspace_id, owner_filter.clone())
.await
.map_err(internal_error)?
{
@@ -468,7 +488,7 @@ async fn overview_handler(
let briefing = state
.reader
- .briefing_for_workspace(workspace_id, query.limit.clamp(1, 100))
+ .briefing_for_workspace(workspace_id, query.limit.clamp(1, 100), owner_filter)
.await
.map_err(internal_error)?;
@@ -504,17 +524,228 @@ async fn overview_handler(
))
}
+/// Build the owner filter for a read-only API request.
+///
+/// A caller the server can name sees their own rows plus the shared ones; a
+/// caller it cannot sees only shared ones, so an owned handoff — and the
+/// prompt-derived text inside it — never reaches someone it does not belong to.
+///
+/// "Can name" is [`ai_memory_core::ActorContext::identity_key`], not
+/// `actor.user`: an ingress that forwards only the OIDC subject claim asserts
+/// `sub` alone, and reading `user` here would file every such operator as
+/// unattributed while the auth layer calls them a user — hiding their own
+/// handoffs, and the bodies of the shared ones, from them in their own UI.
+fn owner_filter_for(
+ actor: Option<axum::Extension<ai_memory_core::ActorContext>>,
+) -> ai_memory_core::OwnerFilter {
+ ai_memory_core::OwnerFilter::for_actor_context(
+ &actor.map_or_else(ai_memory_core::ActorContext::anonymous, |ext| ext.0),
+ )
+}
+
+/// May this request read the prompt-derived body of a handoff?
+///
+/// Three ways to qualify: the caller resolved to an identity and is reading rows
+/// that are their own or shared; the caller holds root, which is the operator —
+/// they already read every page body through the wiki API, so redacting their
+/// own handoffs from their own UI costs them and protects nobody; or the server
+/// does not authenticate at all and the whole wiki is open by design.
+/// `require_bearer` stamps [`ai_memory_core::AuthLevel::Anonymous`] on every
+/// request of a server with no configured token; the extension is missing only
+/// when the API is mounted with no auth layer whatsoever, which is the same open
+/// posture. What is left — an auth-configured server, a caller it can neither
+/// name nor recognise as root — is the only case that redacts. See
+/// [`handoffs_handler`] for why the body is treated differently from the
+/// metadata beside it.
+///
+/// [`ai_memory_core::OwnerFilter::Any`] is the cross-owner recovery filter, so
+/// it is root-only here. Nothing on this route produces it today, but the
+/// sibling recovery switches exist elsewhere; making the check local to this
+/// gate means adding an `all_owners` query parameter later cannot quietly hand
+/// every operator's prompt trail to a caller the server cannot name.
+///
+/// # What actually reaches the `Unattributed` arm
+///
+/// Two live cases, both served, and one that redacts and has no producer today.
+/// `Unattributed` + [`ai_memory_core::AuthLevel::Anonymous`] is rung 0 — no
+/// `[auth].bearer_token`, the default — which stamps
+/// [`ai_memory_core::ActorContext::anonymous`] on **every** request; and
+/// `Unattributed` + [`ai_memory_core::AuthLevel::Root`] is an authenticating
+/// server with no `[auth].root_username`, where the root template names nobody.
+/// Both are open postures and the arm serves them.
+///
+/// What has no producer is `Unattributed` at a NAMED tier: the DB-user rung
+/// fills `user` from the row, and the proxy downgrade only reaches
+/// [`ai_memory_core::AuthLevel::User`] when the proxy asserted `user` *or*
+/// `sub` — both of which [`ai_memory_core::ActorContext::identity_key`]
+/// resolves, so the filter is `User(_)` and the body is served by the arm
+/// above. That gap is the fail-safe: a future rung, or a mount that injects a
+/// tier without an actor, redacts by default instead of leaking. Weakening the
+/// arm because "nothing produces it" removes the fail-safe, not dead code.
+fn serves_handoff_body(
+ owner_filter: &ai_memory_core::OwnerFilter,
+ auth: Option<axum::Extension<ai_memory_core::AuthLevel>>,
+) -> bool {
+ let level = auth.map(|axum::Extension(level)| level);
+ let root = level == Some(ai_memory_core::AuthLevel::Root);
+ match owner_filter {
+ ai_memory_core::OwnerFilter::User(_) => true,
+ ai_memory_core::OwnerFilter::Any => root,
+ ai_memory_core::OwnerFilter::Unattributed => {
+ root || matches!(level, None | Some(ai_memory_core::AuthLevel::Anonymous))
+ }
+ }
+}
+
+/// One handoff in the listing. Richer than [`ApiHandoff`] (the single "pending"
+/// card): it carries the state and ownership needed to answer "where did my
+/// baton go".
+#[derive(Serialize)]
+struct ApiHandoffEntry {
+ id: String,
+ agent: String,
+ at: String,
+ state: String,
+ /// Prompt-derived text, withheld from a caller the server can neither name
+ /// nor recognise as root — see [`handoffs_handler`]. Absent together with
+ /// `open_questions` and `next_steps` whenever `redacted` is true.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ summary: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ open_questions: Option<Vec<String>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ next_steps: Option<Vec<String>>,
+ /// True when the three fields above were withheld, so a frontend can say
+ /// "sign in to read this" instead of rendering a blank card.
+ redacted: bool,
+ files_touched: Vec<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ cwd: Option<String>,
+ /// Operator the handoff belongs to (qualified `sub:`/`user:` storage key);
+ /// absent when shared with the project.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ owner: Option<String>,
+ /// Operator that consumed it, when it has been accepted.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ accepted_by: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ accepted_at: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct HandoffListQuery {
+ /// `open` | `accepted` | `expired`. Omit for every state — which is how an
+ /// operator finds a baton that was already consumed.
+ #[serde(default)]
+ state: Option<String>,
+ #[serde(default = "default_handoff_limit")]
+ limit: usize,
+}
+
+const fn default_handoff_limit() -> usize {
+ 50
+}
+
+/// List a project's handoffs.
+///
+/// Before this there was no way to enumerate handoffs anywhere in the system:
+/// readers only ever fetched the single pending one and consumed it, so a baton
+/// that went to the wrong place simply vanished. Scoped by owner, so this does
+/// not become a way to read other operators' context.
+///
+/// # The prompt-derived body needs a caller the server can vouch for
+///
+/// The metadata — state, timestamps, agent, cwd, touched files, ownership — is
+/// what makes the listing useful and is served to anyone who may call it.
+/// `summary`, `open_questions` and `next_steps` are not metadata: an automatic
+/// SessionEnd handoff synthesises them verbatim from the operator's prompts, and
+/// the listing returns the project's whole history rather than the single newest
+/// open row the overview card shows. A caller with no identity matches every
+/// *shared* handoff — which is all of them on a server that stamps no owner — so
+/// serving those three fields to one would hand the entire prompt trail to
+/// whoever can reach the endpoint.
+///
+/// [`serves_handoff_body`] therefore withholds them from exactly one caller: an
+/// auth-configured server's request that resolved to neither an identity nor
+/// root. Root is the operator — `[auth].root_username` is optional, so the
+/// ordinary single-operator deployment authenticates as root while stamping no
+/// owner on anything, and redacting there would blank out the operator's own
+/// handoffs in their own UI while the overview card beside it, which never
+/// gated the same three fields, kept rendering them.
+///
+/// A server with no auth configured is the other open case: it already serves
+/// every page body unauthenticated, so withholding here would narrow nothing
+/// while making the listing useless. The rule is about not widening what a
+/// server that *does* authenticate shows to a caller it cannot place.
+async fn handoffs_handler(
+ State(state): State<Arc<WebState>>,
+ 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<HandoffListQuery>,
+) -> Result<Response, Response> {
+ let (workspace_id, project_id) = lookup_project(&state, &workspace, &project).await?;
+ let handoff_state = match query.state.as_deref().map(str::trim) {
+ None | Some("") => None,
+ Some(raw) => Some(raw.parse::<ai_memory_core::HandoffState>().map_err(|_| {
+ json_error(
+ StatusCode::BAD_REQUEST,
+ format!("unknown handoff state: {raw}"),
+ )
+ })?),
+ };
+ let owner_filter = owner_filter_for(actor);
+ let with_body = serves_handoff_body(&owner_filter, auth);
+ let handoffs = state
+ .reader
+ .list_handoffs(
+ workspace_id,
+ project_id,
+ handoff_state,
+ owner_filter,
+ query.limit.clamp(1, 200),
+ )
+ .await
+ .map_err(internal_error)?;
+ let entries: Vec<ApiHandoffEntry> = handoffs
+ .into_iter()
+ .map(|h| ApiHandoffEntry {
+ id: h.id.to_string(),
+ agent: h.from_agent.as_str().to_owned(),
+ at: h.created_at.to_string(),
+ state: h.state.as_str().to_owned(),
+ summary: with_body.then_some(h.summary),
+ open_questions: with_body.then_some(h.open_questions),
+ next_steps: with_body.then_some(h.next_steps),
+ redacted: !with_body,
+ files_touched: h.files_touched,
+ cwd: h.cwd,
+ owner: h.owner_user,
+ accepted_by: h.accepted_by_user,
+ accepted_at: h.accepted_at.map(|t| t.to_string()),
+ })
+ .collect();
+ Ok(with_cache(
+ Json(serde_json::json!({ "handoffs": entries })).into_response(),
+ LIST_CACHE_MAX_AGE,
+ ))
+}
+
async fn project_overview_handler(
State(state): State<Arc<WebState>>,
+ actor: Option<axum::Extension<ai_memory_core::ActorContext>>,
Path((workspace, project)): Path<(String, String)>,
Query(query): Query<LimitQuery>,
) -> Result<Response, Response> {
let (workspace_id, project_id) = lookup_project(&state, &workspace, &project).await?;
let limit = query.limit.clamp(1, 100);
+ // Same scoping as `overview_handler`; computed once and reused for the
+ // briefing below so both halves of the response agree on visibility.
+ let owner_filter = owner_filter_for(actor);
let handoff = state
.reader
- .latest_open_handoff(workspace_id, project_id, None)
+ .latest_open_handoff(workspace_id, project_id, None, owner_filter.clone())
.await
.map_err(internal_error)?
.map(|h| ApiHandoff {
@@ -528,7 +759,7 @@ async fn project_overview_handler(
let briefing = state
.reader
- .briefing_for_project(workspace_id, project_id, limit)
+ .briefing_for_project(workspace_id, project_id, limit, owner_filter)
.await
.map_err(internal_error)?;
@@ -896,3 +1127,44 @@ fn hex_value(byte: u8) -> Option<u8> {
_ => None,
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::serves_handoff_body;
+ use ai_memory_core::{AuthLevel, OwnerFilter};
+ use axum::Extension;
+
+ /// Nothing routes an `Any` filter into the listing today; this is the trap
+ /// check for whoever wires the `all_owners` recovery switch onto it. Reading
+ /// past ownership must cost root — not merely a token the server accepted,
+ /// and not a name the request happens to carry, since the rows returned then
+ /// belong to other operators.
+ #[test]
+ fn cross_owner_filter_serves_body_only_to_root() {
+ for level in [None, Some(AuthLevel::Anonymous), Some(AuthLevel::User)] {
+ assert!(
+ !serves_handoff_body(&OwnerFilter::Any, level.map(Extension)),
+ "cross-owner body served at {level:?}"
+ );
+ }
+ assert!(serves_handoff_body(
+ &OwnerFilter::Any,
+ Some(Extension(AuthLevel::Root))
+ ));
+ }
+
+ /// The operator of the ordinary authenticated deployment: root bearer, no
+ /// `[auth].root_username`, so nothing names them and every handoff they
+ /// wrote is shared. Redacting there hides their own data from them.
+ #[test]
+ fn root_reads_the_body_it_wrote_unattributed() {
+ assert!(serves_handoff_body(
+ &OwnerFilter::Unattributed,
+ Some(Extension(AuthLevel::Root))
+ ));
+ assert!(!serves_handoff_body(
+ &OwnerFilter::Unattributed,
+ Some(Extension(AuthLevel::User))
+ ));
+ }
+}
diff --git a/crates/ai-memory-web/tests/routes.rs b/crates/ai-memory-web/tests/routes.rs
index ba6cee7a..2eb4dbb5 100644
--- a/crates/ai-memory-web/tests/routes.rs
+++ b/crates/ai-memory-web/tests/routes.rs
@@ -1239,6 +1239,7 @@ async fn api_workspace_overview_includes_open_handoff() {
open_questions: vec!["open_question_marker".into()],
next_steps: vec!["next_step_marker".into()],
files_touched: vec![],
+ owner_user: None,
})
.await
.unwrap();
@@ -1309,6 +1310,7 @@ async fn api_project_overview_aggregates_handoff_briefing_health() {
open_questions: vec![],
next_steps: vec![],
files_touched: vec![],
+ owner_user: None,
})
.await
.unwrap();
@@ -1343,6 +1345,475 @@ async fn api_project_overview_aggregates_handoff_briefing_health() {
);
}
+/// Replay the extensions `require_bearer` injects, so a test can build the
+/// request the way a real server hands it to the handler: `actor` is the
+/// identity the middleware resolved (`None` = a caller the server cannot name)
+/// and `auth` is the tier (`None` = the API mounted with no auth layer).
+fn api_req(
+ uri: &str,
+ actor: Option<&str>,
+ auth: Option<ai_memory_core::AuthLevel>,
+) -> Request<Body> {
+ api_req_actor(
+ uri,
+ actor.map(|user| ai_memory_core::ActorContext {
+ user: Some(user.to_owned()),
+ ..ai_memory_core::ActorContext::default()
+ }),
+ auth,
+ )
+}
+
+/// Same, for a rung whose identity is not a plain username — the proxy that
+/// asserts only an OIDC subject claim.
+fn api_req_actor(
+ uri: &str,
+ actor: Option<ai_memory_core::ActorContext>,
+ auth: Option<ai_memory_core::AuthLevel>,
+) -> Request<Body> {
+ let mut builder = Request::builder().uri(uri);
+ if let Some(actor) = actor {
+ builder = builder.extension(actor);
+ }
+ if let Some(level) = auth {
+ builder = builder.extension(level);
+ }
+ builder.body(Body::empty()).unwrap()
+}
+
+/// Owners are stored as the contract's qualified storage keys, so the fixtures
+/// stamp them through `owner_stamp` rather than hand-writing the TEXT.
+fn handoff_for(
+ ws: ai_memory_core::WorkspaceId,
+ proj: ai_memory_core::ProjectId,
+ summary: &str,
+ owner: Option<&ai_memory_core::IdentityKey>,
+) -> NewHandoff {
+ NewHandoff {
+ workspace_id: ws,
+ project_id: proj,
+ from_session_id: None,
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: Some("/tmp/scratch".into()),
+ summary: summary.into(),
+ open_questions: vec![format!("{summary}_question")],
+ next_steps: vec![format!("{summary}_step")],
+ files_touched: vec!["alpha.md".into()],
+ owner_user: ai_memory_core::owner_stamp(owner, true),
+ }
+}
+
+fn user_key(name: &str) -> ai_memory_core::IdentityKey {
+ ai_memory_core::IdentityKey::User(name.into())
+}
+
+fn sub_key(sub: &str) -> ai_memory_core::IdentityKey {
+ ai_memory_core::IdentityKey::Subject(sub.into())
+}
+
+/// The sub-only proxy rung, end to end through the browser's own endpoint.
+///
+/// An ingress that terminates OIDC and forwards only the subject claim resolves
+/// to `AuthLevel::User` with `actor.user = None`. Keying ownership on `.user`
+/// made that caller `OwnerFilter::Unattributed`, which drops their own owned
+/// rows from the listing entirely AND trips the redaction gate on the shared
+/// ones — so on a sub-only deployment every operator lost every handoff body in
+/// the web UI, including their own.
+#[tokio::test]
+async fn api_handoff_listing_serves_a_sub_only_proxy_caller_their_own_rows() {
+ let (_tmp, store, wiki) = setup().await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ // Their own row, a colleague's, and a legacy unowned one.
+ for (summary, owner) in [
+ ("mine_handoff_marker", Some(sub_key("oidc-subject-alice"))),
+ ("theirs_handoff_marker", Some(sub_key("oidc-subject-bob"))),
+ ("shared_handoff_marker", None),
+ ] {
+ store
+ .writer
+ .insert_handoff(handoff_for(ws, proj, summary, owner.as_ref()))
+ .await
+ .unwrap();
+ }
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let resp = app
+ .oneshot(api_req_actor(
+ "/workspaces/default/projects/scratch/handoffs",
+ Some(ai_memory_core::ActorContext {
+ sub: Some("oidc-subject-alice".into()),
+ ..ai_memory_core::ActorContext::default()
+ }),
+ Some(ai_memory_core::AuthLevel::User),
+ ))
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let raw = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let text = String::from_utf8(raw.to_vec()).unwrap();
+ let json: Value = serde_json::from_str(&text).unwrap();
+ let entries = json["handoffs"].as_array().unwrap();
+
+ let summaries: Vec<&str> = entries
+ .iter()
+ .filter_map(|e| e["summary"].as_str())
+ .collect();
+ assert!(
+ summaries.contains(&"mine_handoff_marker"),
+ "the proxied operator cannot read the body of their own handoff: {text}",
+ );
+ assert!(
+ summaries.contains(&"shared_handoff_marker"),
+ "a legacy unowned handoff must stay readable by everyone: {text}",
+ );
+ assert!(
+ entries.iter().all(|e| e["redacted"] == false),
+ "a caller the server can name must not be redacted: {text}",
+ );
+ // …and naming them did not widen anything: the colleague's row is neither
+ // listed nor leaked.
+ assert!(
+ !text.contains("theirs_handoff_marker"),
+ "another operator's handoff reached this caller: {text}",
+ );
+}
+
+/// With `[auth].root_username` set every automatic handoff carries an owner, so
+/// the card must use the caller's filter — otherwise it serialises `null` while
+/// `pending_handoff_count` beside it, which does apply that filter, reports 1.
+#[tokio::test]
+async fn api_workspace_overview_card_agrees_with_pending_count_for_owner() {
+ let (_tmp, store, wiki) = setup().await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_handoff(handoff_for(
+ ws,
+ proj,
+ "owned_handoff_marker",
+ Some(&user_key("alice")),
+ ))
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let resp = app
+ .oneshot(api_req(
+ "/workspaces/default/overview",
+ Some("alice"),
+ Some(ai_memory_core::AuthLevel::Root),
+ ))
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(json["briefing"]["pending_handoff_count"], 1);
+ assert_eq!(
+ json["handoff"]["summary"], "owned_handoff_marker",
+ "card must show the same handoff the count advertises: {json}"
+ );
+}
+
+/// The other half of the same invariant: a browser the server cannot name still
+/// sees neither the owned card nor a count promising one.
+#[tokio::test]
+async fn api_workspace_overview_hides_owned_handoff_from_unnamed_caller() {
+ let (_tmp, store, wiki) = setup().await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_handoff(handoff_for(
+ ws,
+ proj,
+ "owned_handoff_marker",
+ Some(&user_key("alice")),
+ ))
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let resp = app
+ .oneshot(api_req("/workspaces/default/overview", None, None))
+ .await
+ .unwrap();
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+
+ assert!(json["handoff"].is_null(), "expected no card: {json}");
+ assert_eq!(json["briefing"]["pending_handoff_count"], 0);
+}
+
+/// Default config — no `[auth]` at all — behaves exactly as it did: the whole
+/// wiki is open, so the listing carries its prompt-derived body, and a legacy
+/// handoff with no owner stays visible.
+#[tokio::test]
+async fn api_handoff_listing_serves_body_when_auth_is_off() {
+ let (_tmp, store, wiki) = setup().await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_handoff(handoff_for(ws, proj, "shared_handoff_marker", None))
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let resp = app
+ .oneshot(api_req(
+ "/workspaces/default/projects/scratch/handoffs",
+ None,
+ Some(ai_memory_core::AuthLevel::Anonymous),
+ ))
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+
+ let entry = &json["handoffs"][0];
+ assert_eq!(entry["summary"], "shared_handoff_marker");
+ assert_eq!(entry["open_questions"][0], "shared_handoff_marker_question");
+ assert_eq!(entry["next_steps"][0], "shared_handoff_marker_step");
+ assert_eq!(entry["redacted"], false);
+}
+
+/// On a server that DOES authenticate, a caller it can neither name nor place
+/// as root gets the metadata — that is what makes the listing useful — but not
+/// the text an automatic handoff synthesises from the operator's prompts.
+///
+/// No rung of `require_bearer` actually produces this pair: the DB-user rung
+/// fills `user` from the row, and the proxy downgrade only reaches
+/// `AuthLevel::User` when the proxy asserted `user` **or** `sub` — both of which
+/// `ActorContext::identity_key` resolves, so those callers get `OwnerFilter::
+/// User(_)` and the body. What this pins is the gate's own floor: whatever
+/// hands the handler a tier below root without an identity — a future rung, or
+/// a mount that injects a level and no actor — gets the fail-safe answer. Do
+/// not weaken the arm on the grounds that nothing reaches it.
+#[tokio::test]
+async fn api_handoff_listing_withholds_body_from_unnamed_nonroot_caller() {
+ let (_tmp, store, wiki) = setup().await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_handoff(handoff_for(ws, proj, "shared_handoff_marker", None))
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let resp = app
+ .oneshot(api_req(
+ "/workspaces/default/projects/scratch/handoffs",
+ None,
+ Some(ai_memory_core::AuthLevel::User),
+ ))
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let raw = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let text = String::from_utf8(raw.to_vec()).unwrap();
+ let json: Value = serde_json::from_str(&text).unwrap();
+
+ let entry = &json["handoffs"][0];
+ // Metadata: still there, and the row itself is still listed — a legacy
+ // unowned handoff stays visible to everyone.
+ assert_eq!(entry["state"], "open");
+ assert_eq!(entry["agent"], "claude-code");
+ assert_eq!(entry["cwd"], "/tmp/scratch");
+ assert_eq!(entry["files_touched"][0], "alpha.md");
+ assert_eq!(entry["redacted"], true);
+ // Body: gone, and nowhere else in the payload either.
+ assert!(entry.get("summary").is_none(), "summary served: {text}");
+ assert!(entry.get("open_questions").is_none());
+ assert!(entry.get("next_steps").is_none());
+ assert!(
+ !text.contains("shared_handoff_marker"),
+ "prompt-derived text leaked: {text}"
+ );
+}
+
+/// The commonest authenticated deployment: `[auth].bearer_token` set,
+/// `[auth].root_username` left out. Handoffs carry no owner and the operator's
+/// own browser authenticates as root without a name, so a gate that asked only
+/// for a name redacted the operator's data from the operator — while the
+/// overview card next to it served the same three fields ungated.
+#[tokio::test]
+async fn api_handoff_listing_serves_body_to_root_without_root_username() {
+ let (_tmp, store, wiki) = setup().await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_handoff(handoff_for(ws, proj, "shared_handoff_marker", None))
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let resp = app
+ .oneshot(api_req(
+ "/workspaces/default/projects/scratch/handoffs",
+ None,
+ Some(ai_memory_core::AuthLevel::Root),
+ ))
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let raw = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let text = String::from_utf8(raw.to_vec()).unwrap();
+ let json: Value = serde_json::from_str(&text).unwrap();
+
+ let entry = &json["handoffs"][0];
+ assert_eq!(
+ entry["redacted"], false,
+ "root redacted from itself: {text}"
+ );
+ assert_eq!(entry["summary"], "shared_handoff_marker");
+ assert_eq!(entry["open_questions"][0], "shared_handoff_marker_question");
+ assert_eq!(entry["next_steps"][0], "shared_handoff_marker_step");
+
+ // The overview card is the same operator's other view of the same row; the
+ // two endpoints must not disagree about whether it may read it.
+ let overview = api_router(store.reader.clone(), wiki.clone())
+ .oneshot(api_req(
+ "/workspaces/default/projects/scratch/overview",
+ None,
+ Some(ai_memory_core::AuthLevel::Root),
+ ))
+ .await
+ .unwrap();
+ let overview: Value = serde_json::from_slice(
+ &axum::body::to_bytes(overview.into_body(), usize::MAX)
+ .await
+ .unwrap(),
+ )
+ .unwrap();
+ assert_eq!(overview["handoff"]["summary"], "shared_handoff_marker");
+}
+
+/// A named caller gets their own handoffs in full — and still never sees
+/// somebody else's.
+#[tokio::test]
+async fn api_handoff_listing_serves_body_to_named_caller() {
+ let (_tmp, store, wiki) = setup().await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ for handoff in [
+ handoff_for(ws, proj, "alice_handoff_marker", Some(&user_key("alice"))),
+ handoff_for(ws, proj, "bob_handoff_marker", Some(&user_key("bob"))),
+ handoff_for(ws, proj, "shared_handoff_marker", None),
+ ] {
+ store.writer.insert_handoff(handoff).await.unwrap();
+ }
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let resp = app
+ .oneshot(api_req(
+ "/workspaces/default/projects/scratch/handoffs",
+ Some("alice"),
+ Some(ai_memory_core::AuthLevel::User),
+ ))
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let raw = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let text = String::from_utf8(raw.to_vec()).unwrap();
+ let json: Value = serde_json::from_str(&text).unwrap();
+
+ let mut summaries: Vec<&str> = json["handoffs"]
+ .as_array()
+ .expect("handoffs")
+ .iter()
+ .map(|e| {
+ assert_eq!(e["redacted"], false, "body withheld from its owner: {text}");
+ e["summary"].as_str().expect("summary")
+ })
+ .collect();
+ summaries.sort_unstable();
+ // Own + shared (absent owner = shared), never bob's.
+ assert_eq!(
+ summaries,
+ vec!["alice_handoff_marker", "shared_handoff_marker"],
+ "{text}"
+ );
+ assert!(!text.contains("bob_handoff_marker"), "{text}");
+}
+
#[tokio::test]
async fn api_workspace_overview_health_detail_lists_pages() {
let (_tmp, store, wiki) = setup().await;
diff --git a/crates/ai-memory-wiki/src/admission.rs b/crates/ai-memory-wiki/src/admission.rs
index 05dad75c..05f8803a 100644
--- a/crates/ai-memory-wiki/src/admission.rs
+++ b/crates/ai-memory-wiki/src/admission.rs
@@ -63,6 +63,18 @@ pub enum AdmissionOp {
/// project id. Carries source names in `workspace`/`project` and
/// destination names in `destination_workspace`/`destination_project`.
MoveProject,
+ /// A handoff is being created. Carries the workspace/project; no page path,
+ /// since handoffs live in their own table rather than the wiki tree.
+ ///
+ /// The handoff lifecycle never touched `Wiki::write_page`, so an admission
+ /// webhook could not see — let alone refuse — any of it. A deployment that
+ /// authorizes writes per operator had a blind spot exactly on the rows that
+ /// carry prompt-derived text between operators.
+ HandoffBegin,
+ /// A pending handoff is being consumed.
+ HandoffAccept,
+ /// A pending handoff is being discarded.
+ HandoffCancel,
}
impl AdmissionOp {
@@ -76,6 +88,9 @@ impl AdmissionOp {
AdmissionOp::PurgeProject => "purge_project",
AdmissionOp::PurgeWorkspace => "purge_workspace",
AdmissionOp::MoveProject => "move_project",
+ AdmissionOp::HandoffBegin => "handoff_begin",
+ AdmissionOp::HandoffAccept => "handoff_accept",
+ AdmissionOp::HandoffCancel => "handoff_cancel",
}
}
}
@@ -225,9 +240,17 @@ pub const MAX_ADMISSION_WEBHOOKS: usize = 16;
/// pin write-path or async admission work indefinitely.
pub const MAX_WEBHOOK_TIMEOUT_MS: u64 = 30_000;
-/// Maximum non-blocking webhook requests in flight for one process. Beyond this
-/// cap observer hooks are dropped with a warning; the durable wiki write has
-/// already completed, so backpressure here should never stall the caller.
+/// Maximum fire-and-forget webhook requests in flight for one process. Beyond
+/// this cap the request is dropped with a log line; the durable operation has
+/// already completed, so backpressure here never stalls the caller.
+///
+/// Every spawned webhook shares the permits, not just the `blocking = false`
+/// ones: [`AdmissionChain::dispatch_notify_observers`] spawns any subscriber
+/// that cannot refuse the op, which on the handoff lifecycle ops includes a
+/// `blocking = true, failure_policy = ignore` hook. So a hook an operator marked
+/// blocking can be dropped under load — it is an observer there whatever its
+/// `blocking` flag says, since only `reject` policy is awaited. Dropping one is
+/// logged at ERROR precisely because that configuration reads as "must run".
pub const MAX_ASYNC_ADMISSION_IN_FLIGHT: usize = 256;
/// Maximum bytes read from a single webhook response body. Webhooks
@@ -407,57 +430,120 @@ impl AdmissionChain {
/// # Errors
/// Returns an error only when a `Reject`-policy webhook fails.
pub async fn notify(&self, page_path: Option<&str>, ctx: &AdmissionContext) -> WikiResult<()> {
- let empty_frontmatter = serde_json::Value::Object(serde_json::Map::new());
for hook in self.webhooks.iter() {
- if ctx.skip_webhooks.iter().any(|n| n == &hook.name) {
- tracing::debug!(webhook = %hook.name, "admission skip (caller opt-out)");
+ if !self.subscribed(hook, ctx) {
continue;
}
- if !hook.events.contains(&ctx.op) {
+ if !hook.blocking {
continue;
}
- if !hook.blocking {
+ self.notify_once(hook, page_path, ctx).await?;
+ }
+ Ok(())
+ }
+
+ /// Run only the webhooks that can actually refuse `ctx.op` — the blocking
+ /// ones the operator set to [`FailurePolicy::Reject`].
+ ///
+ /// For a caller whose own latency is bounded (the session-start hook path),
+ /// an `Ignore` webhook is dead weight in front of the operation: its answer
+ /// cannot change the outcome, yet waiting for it spends the caller's whole
+ /// budget, and cutting it short mid-chain would abandon an operation a
+ /// webhook earlier in the chain has already been told succeeded. Those
+ /// hooks belong on [`Self::dispatch_notify_observers`], AFTER the operation
+ /// has actually landed.
+ ///
+ /// # Errors
+ /// Returns an error only when a `Reject`-policy webhook fails.
+ pub async fn authorize(
+ &self,
+ page_path: Option<&str>,
+ ctx: &AdmissionContext,
+ ) -> WikiResult<()> {
+ for hook in self.webhooks.iter() {
+ if !self.subscribed(hook, ctx) {
continue;
}
- let payload = WebhookRequestBody {
- page: WebhookPagePayload {
- path: page_path.unwrap_or(""),
- frontmatter: &empty_frontmatter,
- body: "",
- },
- ctx,
- };
- let result = self
- .client
- .post(&hook.url)
- .header("X-Memory-Op", ctx.op.as_header_value())
- .timeout(webhook_timeout(hook.timeout_ms))
- .json(&payload)
- .send()
- .await;
- match result {
- Ok(resp) if resp.status().is_success() => {
- tracing::debug!(webhook = %hook.name, op = ctx.op.as_header_value(), "admission notify ok");
- }
- Ok(resp) => {
- let status = resp.status();
- let body_txt = response_text_limited(resp).await;
- tracing::warn!(webhook = %hook.name, status = %status, body = %body_txt, "admission notify error response");
- if matches!(hook.failure_policy, FailurePolicy::Reject) {
- return Err(WikiError::Io(std::io::Error::other(format!(
- "admission webhook {} status {}: {}",
- hook.name, status, body_txt
- ))));
- }
+ if !decides(hook) {
+ continue;
+ }
+ self.notify_once(hook, page_path, ctx).await?;
+ }
+ Ok(())
+ }
+
+ /// Fire-and-forget the notify-style webhooks [`Self::authorize`] did not
+ /// run: observers, which have nothing to decide. Call it once the operation
+ /// is durable, so no webhook is ever told about work the engine then
+ /// abandons.
+ pub fn dispatch_notify_observers(&self, page_path: Option<&str>, ctx: &AdmissionContext) {
+ let empty_frontmatter = serde_json::Value::Object(serde_json::Map::new());
+ for hook in self.webhooks.iter() {
+ if !self.subscribed(hook, ctx) {
+ continue;
+ }
+ if decides(hook) {
+ continue;
+ }
+ self.spawn_webhook(hook, page_path, &empty_frontmatter, "", ctx);
+ }
+ }
+
+ /// Shared filter: caller opt-out (loop prevention) plus op subscription.
+ fn subscribed(&self, hook: &WebhookConfig, ctx: &AdmissionContext) -> bool {
+ if ctx.skip_webhooks.iter().any(|n| n == &hook.name) {
+ tracing::debug!(webhook = %hook.name, "admission skip (caller opt-out)");
+ return false;
+ }
+ hook.events.contains(&ctx.op)
+ }
+
+ /// One notify-style POST (no body to send or mutate).
+ async fn notify_once(
+ &self,
+ hook: &WebhookConfig,
+ page_path: Option<&str>,
+ ctx: &AdmissionContext,
+ ) -> WikiResult<()> {
+ let empty_frontmatter = serde_json::Value::Object(serde_json::Map::new());
+ let payload = WebhookRequestBody {
+ page: WebhookPagePayload {
+ path: page_path.unwrap_or(""),
+ frontmatter: &empty_frontmatter,
+ body: "",
+ },
+ ctx,
+ };
+ let result = self
+ .client
+ .post(&hook.url)
+ .header("X-Memory-Op", ctx.op.as_header_value())
+ .timeout(webhook_timeout(hook.timeout_ms))
+ .json(&payload)
+ .send()
+ .await;
+ match result {
+ Ok(resp) if resp.status().is_success() => {
+ tracing::debug!(webhook = %hook.name, op = ctx.op.as_header_value(), "admission notify ok");
+ }
+ Ok(resp) => {
+ let status = resp.status();
+ let body_txt = response_text_limited(resp).await;
+ tracing::warn!(webhook = %hook.name, status = %status, body = %body_txt, "admission notify error response");
+ if matches!(hook.failure_policy, FailurePolicy::Reject) {
+ return Err(WikiError::Io(std::io::Error::other(format!(
+ "admission webhook {} status {}: {}",
+ hook.name, status, body_txt
+ ))));
}
- Err(e) => {
- tracing::warn!(webhook = %hook.name, error = %e, "admission notify request failed");
- if matches!(hook.failure_policy, FailurePolicy::Reject) {
- return Err(WikiError::Io(std::io::Error::other(format!(
- "admission webhook {} request failed: {}",
- hook.name, e
- ))));
- }
+ }
+ Err(e) => {
+ tracing::warn!(webhook = %hook.name, error = %e, "admission notify request failed");
+ if matches!(hook.failure_policy, FailurePolicy::Reject) {
+ return Err(WikiError::Io(std::io::Error::other(format!(
+ "admission webhook {} request failed: {}",
+ hook.name, e
+ ))));
}
}
}
@@ -487,56 +573,91 @@ impl AdmissionChain {
if !hook.events.contains(&ctx.op) {
continue;
}
- let Ok(permit) = self.async_semaphore.clone().try_acquire_owned() else {
+ self.spawn_webhook(hook, page_path, frontmatter, body, ctx);
+ }
+ }
+
+ /// Spawn one webhook POST off the caller's path, bounded by the shared
+ /// in-flight permit (hook paths must not fan out unboundedly).
+ fn spawn_webhook(
+ &self,
+ hook: &WebhookConfig,
+ page_path: Option<&str>,
+ frontmatter: &serde_json::Value,
+ body: &str,
+ ctx: &AdmissionContext,
+ ) {
+ let Ok(permit) = self.async_semaphore.clone().try_acquire_owned() else {
+ // A hook the operator marked `blocking` reaches this path too (see
+ // MAX_ASYNC_ADMISSION_IN_FLIGHT), and dropping one contradicts what
+ // that flag reads as, so it is not merely a warning: the operator
+ // has to be able to find it in the log.
+ if hook.blocking {
+ tracing::error!(
+ webhook = %hook.name,
+ op = ctx.op.as_header_value(),
+ cap = MAX_ASYNC_ADMISSION_IN_FLIGHT,
+ "admission async queue saturated; dropping a webhook configured blocking",
+ );
+ } else {
tracing::warn!(
webhook = %hook.name,
+ op = ctx.op.as_header_value(),
cap = MAX_ASYNC_ADMISSION_IN_FLIGHT,
"admission async queue saturated; dropping observer webhook",
);
- continue;
+ }
+ return;
+ };
+ let client = self.client.clone();
+ let url = hook.url.clone();
+ let name = hook.name.clone();
+ let timeout = hook.timeout_ms;
+ let op = ctx.op;
+ let owned_ctx = ctx.clone();
+ let path = page_path.map(str::to_string);
+ let frontmatter = frontmatter.clone();
+ let body = body.to_string();
+ tokio::spawn(async move {
+ let _permit = permit;
+ let payload = WebhookRequestBody {
+ page: WebhookPagePayload {
+ path: path.as_deref().unwrap_or(""),
+ frontmatter: &frontmatter,
+ body: &body,
+ },
+ ctx: &owned_ctx,
};
- let client = self.client.clone();
- let url = hook.url.clone();
- let name = hook.name.clone();
- let timeout = hook.timeout_ms;
- let op = ctx.op;
- let owned_ctx = ctx.clone();
- let path = page_path.map(str::to_string);
- let frontmatter = frontmatter.clone();
- let body = body.to_string();
- tokio::spawn(async move {
- let _permit = permit;
- let payload = WebhookRequestBody {
- page: WebhookPagePayload {
- path: path.as_deref().unwrap_or(""),
- frontmatter: &frontmatter,
- body: &body,
- },
- ctx: &owned_ctx,
- };
- match client
- .post(&url)
- .header("X-Memory-Op", op.as_header_value())
- .timeout(webhook_timeout(timeout))
- .json(&payload)
- .send()
- .await
- {
- Ok(resp) if resp.status().is_success() => {
- tracing::debug!(webhook = %name, op = op.as_header_value(), "admission async ok");
- }
- Ok(resp) => {
- tracing::warn!(webhook = %name, status = %resp.status(), "admission async error response");
- }
- Err(e) => {
- tracing::warn!(webhook = %name, error = %e, "admission async request failed");
- }
+ match client
+ .post(&url)
+ .header("X-Memory-Op", op.as_header_value())
+ .timeout(webhook_timeout(timeout))
+ .json(&payload)
+ .send()
+ .await
+ {
+ Ok(resp) if resp.status().is_success() => {
+ tracing::debug!(webhook = %name, op = op.as_header_value(), "admission async ok");
}
- });
- }
+ Ok(resp) => {
+ tracing::warn!(webhook = %name, status = %resp.status(), "admission async error response");
+ }
+ Err(e) => {
+ tracing::warn!(webhook = %name, error = %e, "admission async request failed");
+ }
+ }
+ });
}
}
+/// `true` when this webhook's answer can change the outcome of an operation —
+/// the operator asked for it to block AND to refuse on failure. Everything else
+/// is an observer: under the default [`FailurePolicy::Ignore`] a non-2xx, a
+/// timeout and an unreachable host all continue the operation unchanged.
+fn decides(hook: &WebhookConfig) -> bool {
+ hook.blocking && matches!(hook.failure_policy, FailurePolicy::Reject)
+}
+
fn webhook_timeout(timeout_ms: u64) -> Duration {
Duration::from_millis(timeout_ms.clamp(1, MAX_WEBHOOK_TIMEOUT_MS))
}
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index 6485bc8e..eff52db0 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -657,6 +657,74 @@ impl Wiki {
}
}
+ /// Ask the admission chain about an operation that has no page and no body
+ /// — a handoff lifecycle event.
+ ///
+ /// Handoffs live outside the wiki tree (they have their own table), so they
+ /// never passed through `write_page` and were invisible to admission
+ /// webhooks. That left the operations that move prompt-derived text between
+ /// operators unauthorizable: a webhook that decides who may touch which
+ /// scope could not see them at all.
+ ///
+ /// Only the webhooks that can refuse the operation are awaited — that is
+ /// what the caller has to know before doing destructive work, and a
+ /// `reject` policy is the operator asking to be waited for. The observers
+ /// are handed back with the resolved context: pass it to
+ /// [`Self::notify_operation_observers`] once the operation is durable, or
+ /// drop it if the operation was abandoned, so no webhook is told about work
+ /// that never happened. Every path that raises one of these ops owes its
+ /// webhooks the same three steps in the same order — decide, act, notify —
+ /// or the same event reaches a mirror from one caller and not from another.
+ ///
+ /// Returns `None` when no chain is attached (nothing left to notify).
+ ///
+ /// # Errors
+ /// Returns [`WikiError`] when a reject-policy webhook refuses.
+ pub async fn authorize_operation(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ op: AdmissionOp,
+ actor: ActorContext,
+ skip_webhooks: Vec<String>,
+ ) -> WikiResult<Option<AdmissionContext>> {
+ let Some(chain) = &self.admission_chain else {
+ return Ok(None);
+ };
+ let ctx = self
+ .operation_admission_ctx(workspace_id, project_id, op, actor, skip_webhooks)
+ .await;
+ chain.authorize(None, &ctx).await?;
+ Ok(Some(ctx))
+ }
+
+ /// Fire-and-forget the observer webhooks for an operation previously gated
+ /// by [`Self::authorize_operation`] and since committed.
+ pub fn notify_operation_observers(&self, ctx: &AdmissionContext) {
+ if let Some(chain) = &self.admission_chain {
+ chain.dispatch_notify_observers(None, ctx);
+ }
+ }
+
+ async fn operation_admission_ctx(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ op: AdmissionOp,
+ actor: ActorContext,
+ skip_webhooks: Vec<String>,
+ ) -> AdmissionContext {
+ let mut ctx = AdmissionContext {
+ op,
+ actor,
+ skip_webhooks,
+ ..Default::default()
+ };
+ self.resolve_admission_names(workspace_id, project_id, &mut ctx)
+ .await;
+ ctx
+ }
+
/// Run just the blocking admission chain for a would-be write, without
/// touching the store, disk, or any upstream cost (e.g. an LLM call). A
/// `failure_policy = reject` webhook can still abort here, so callers use
diff --git a/docs/admission-webhooks.md b/docs/admission-webhooks.md
index e73d0d0d..35c4b69b 100644
--- a/docs/admission-webhooks.md
+++ b/docs/admission-webhooks.md
@@ -70,6 +70,51 @@ Webhooks fire on these `op` values today (extensible enum):
`ctx.destination_workspace` / `ctx.destination_project`, and no page path;
fired before the directory rename + DB re-stamp so a mirror can rename or
reject the project move.
+- `handoff_begin` / `handoff_accept` / `handoff_cancel` — a handoff is created,
+ consumed, or discarded. Carries the workspace / project and the acting
+ operator, no page path (handoffs live in their own table, not the wiki tree).
+ Fired by the MCP tools **and** by the automatic hook paths: the SessionEnd
+ baton (`handoff_begin`) and the session-start claim (`handoff_accept`).
+
+The three handoff lifecycle ops are dispatched in one fixed order, the same
+from every path that raises them: the webhooks that can refuse — `blocking`
+with `failure_policy = "reject"` — are awaited **before** the operation, the
+operation then runs, and every other subscriber (observers, blocking or not) is
+dispatched fire-and-forget **after** it, only if it happened. So no observer is
+told about an `accept` that found no pending handoff or a `cancel` another
+operator's ownership refused — an `accept` with nothing pending is not
+announced to a decider either, since the engine knows there is nothing to
+accept before it asks — and an observer subscribed to one of these ops sees the
+same event whether it came from an MCP tool or the hook ingress. (`write_page`
+and the notification ops below are unchanged: there, a `blocking` webhook is
+awaited up front whatever its `failure_policy` — on `write_page` because it can
+still mutate the page.)
+
+What a `reject` costs the caller depends on **which path** raised the op, and
+the difference is deliberate. On the MCP tools — `memory_handoff_begin`,
+`memory_handoff_accept`, `memory_handoff_cancel` — a refusal aborts the tool
+call and is returned to the caller as a JSON-RPC error, exactly like
+`write_page`: there is a caller who asked for the operation, so it is told the
+operation did not happen. On the automatic paths there is no such caller, so a
+refusal degrades the lifecycle event instead of failing it:
+
+- SessionEnd asks before `end_session` commits; a refusal skips the baton, is
+ logged, and the session page / opt-in consolidation / auto-commit still run.
+ The session ends without a handoff rather than ending with no summary at all.
+- The session-start claim is served by the hook path, whose script hard-timeouts
+ at ≤200 ms — which is why only the deciding webhooks are awaited there. A
+ refusal, a timeout or an unreachable host leaves the handoff **open** for the
+ next session; it never fails the session start.
+
+Budgeting the session-start claim: the deciding webhooks are awaited
+**sequentially**, and the chain stops at the first refusal, so what the operator
+waits for in the worst case is the **sum** of the `timeout_ms` of every
+`reject`-policy webhook subscribed to `handoff_accept` — not the largest of them.
+`timeout_ms` **defaults to 2000 ms**, ten times the hook budget, so each such
+webhook needs an explicit value and the values have to add up to the budget: one
+hook can have `150`, but two need roughly `75` each. The engine does not enforce
+the budget for you — nothing server-side knows about the hook script's deadline —
+so a chain that overshoots it is the operator's own configuration to fix.
`delete` / `purge_project` / `purge_workspace` / `move_project` are notifications — there is no
body to mutate; a `Reject`-policy webhook still aborts the operation
@@ -104,7 +149,10 @@ terminal `purge_project` notification is unchanged.
HTTP POST per observation, violating the fire-and-forget hook budget. The
per-event log is a local audit artifact; back it up out-of-band (batched
rsync), not per-line.
-- **Handoffs** — SQLite rows, transient cross-agent state, not wiki pages.
+- **The page bodies behind a handoff** — the `handoff_*` ops above carry only
+ the scope and the acting operator. A handoff is SQLite rows, so a file mirror
+ has no file change to reconcile from one; what it gets is the lifecycle
+ event, not a page.
- **Forget-sweep decay soft-delete and aged-tombstone cleanup** —
project-scoped and DB-only (`is_latest=0` / row delete); the markdown file
stays on disk, so there is nothing for a file mirror to do. This exemption
@@ -128,8 +176,12 @@ terminal `purge_project` notification is unchanged.
POST <webhook.url>
Content-Type: application/json
X-Memory-Op: write_page | consolidate | delete | purge_project | purge_workspace | move_project
+ | handoff_begin | handoff_accept | handoff_cancel
```
+(The header is one of those nine values; the second line is a continuation of
+the list, not a second header.)
+
```jsonc
{
"page": {
@@ -191,7 +243,8 @@ non-2xx:
for persistence (e.g. a future `validate-no-secrets` enforcer).
A webhook that subscribes to multiple ops uses the same policy across
-all of them.
+all of them — including the handoff lifecycle ops above, where "abort" means
+"decline this handoff", not "fail the event".
## 5. Workspace / project names
@@ -212,7 +265,8 @@ webhook fan-out if you wire one.
## 6. Loop prevention
A webhook that turns around and writes back to the engine (e.g. via
-`/admin/write-page` or `memory_write_page`) must include the header
+`/admin/write-page`, `memory_write_page`, or the hook ingress) must include the
+header
```
X-Memory-Skip-Admission-Chain: <name>[,<name>...]
@@ -280,6 +334,17 @@ A webhook is either **blocking** or **non-blocking**:
Since the blocking chain is sequential, total worst-case write latency is
`Σ timeout_ms` over the **blocking** webhooks only; non-blocking ones add none.
+Fire-and-forget dispatch is bounded: **256** such requests may be in flight per
+process, and beyond that the request is dropped and logged rather than queued
+(the durable operation has already completed, so the caller is never stalled).
+On the handoff lifecycle ops — `handoff_begin`, `handoff_accept`,
+`handoff_cancel` — only a `reject`-policy webhook is awaited, so a
+`blocking = true` hook with `failure_policy = "ignore"` is dispatched
+fire-and-forget there and shares that budget: under sustained load it too can be
+dropped. Such a drop is logged at ERROR (a non-blocking one at WARN). A hook that
+must not be dropped on those ops needs `failure_policy = "reject"`, which makes
+it a decider — awaited before the operation, and able to refuse it.
+
Env override:
```bash
diff --git a/docs/frontend-api.md b/docs/frontend-api.md
index 9e3ddcd4..ff35de51 100644
--- a/docs/frontend-api.md
+++ b/docs/frontend-api.md
@@ -296,6 +296,57 @@ pages. No LLM, deterministic.
```http
GET /api/v1/workspaces/{workspace}/overview?limit=10
GET /api/v1/workspaces/{workspace}/projects/{project}/overview?limit=10
+GET /api/v1/workspaces/{workspace}/projects/{project}/handoffs?state=open&limit=50
+```
+
+### Handoff listing
+
+`state` accepts `open` | `accepted` | `expired`; omit it to list every state,
+which is how you find a baton that was already consumed. Results are scoped by
+owner: an authenticated caller sees their own plus the shared handoffs, an
+anonymous browser sees only shared ones — an owned handoff (and the prompt-
+derived text inside it) is never rendered to someone it does not belong to.
+The same scoping applies to the `handoff` field of both overview endpoints and
+to `pending_handoff_count`, so the count and the fetch always agree.
+
+On a server that authenticates, the listing's prompt-derived fields —
+`summary`, `open_questions`, `next_steps` — are served to a caller the server
+can name and to the root operator; an automatic handoff synthesises them
+verbatim from the operator's prompts, and the listing returns the project's
+whole history rather than the single newest open row. A caller that is neither
+named nor root gets the fields absent and `redacted` set to `true`; the metadata
+(state, timestamps, agent, cwd, touched files, ownership) is always served. A
+server with no auth configured serves the bodies, since it already serves every
+page body unauthenticated.
+
+"Can name" means the identity the auth tier itself resolved
+(`ActorContext::identity_key()`): the asserted subject claim when there is one,
+otherwise the username. An ingress that terminates OIDC and forwards only
+`X-Memory-Actor-Sub` therefore reads its own handoffs and the shared ones with
+`redacted: false`, and no rung of the auth chain produces an
+authenticated-but-unnameable caller today — the redacting arm is a fail-safe
+floor, not a live tier. `owner` / `accepted_by` carry the qualified storage key
+(`user:alice`, `sub:…`).
+
+```json
+{
+ "handoffs": [
+ {
+ "id": "01930…",
+ "agent": "claude-code",
+ "at": "2026-07-28T12:00:00Z",
+ "state": "accepted",
+ "summary": "…",
+ "open_questions": [],
+ "next_steps": [],
+ "redacted": false,
+ "files_touched": [],
+ "owner": "user:alice",
+ "accepted_by": "user:alice",
+ "accepted_at": "2026-07-28T13:00:00Z"
+ }
+ ]
+}
```
Bundles what a frontend usually needs on its home view in one round-trip.
diff --git a/docs/users.md b/docs/users.md
index f49f89bd..aba93283 100644
--- a/docs/users.md
+++ b/docs/users.md
@@ -121,6 +121,56 @@ derivation is `IdentityKey::path_segment()`: values made only of
else hex-encodes under a distinct prefix (`sx-…`, `ux-…`) that keeps the
encoding injective.
+## Ownership of handoffs and sessions
+
+Handoffs and sessions record the operator they belong to (`owner_user` /
+`actor_user`, holding the qualified `IdentityKey::storage_key()` TEXT). On a
+shared server this stops one operator's pending handoff from being delivered
+to — and consumed by — the next session to start, whoever it belongs to.
+
+- A `NULL` owner means **shared with the project**: every row written before
+ ownership existed, and anything written without an authenticated actor, stays
+ visible to everyone.
+- **An owner is only stamped where the deployment distinguishes operators.**
+ Single-operator servers are unaffected even when they name their operator via
+ `[auth].root_username`: with no `users` rows and no proxy secret there is
+ nobody to separate, and stamping the one name would separate that operator's
+ *transports* instead — HTTP requests carry the name, while the stdio /
+ in-process MCP transport and the local CLI carry no actor at all and would
+ stop seeing what the HTTP side wrote. Reads are deliberately **not** gated the
+ same way, so a row stamped while the deployment did distinguish operators
+ stays readable by that operator afterwards.
+- The owner is the qualified identity the request names —
+ `ActorContext::identity_key()`, so `sub:<subject>` when a subject claim is
+ asserted and `user:<name>` otherwise. It is the same rule that decides the
+ auth tier, so a proxy that forwards only `X-Memory-Actor-Sub` gets real
+ per-operator isolation rather than one shared bucket.
+- `memory_handoff_begin` takes `shared: true` to publish a baton deliberately.
+- `memory_handoff_accept` / `memory_handoff_cancel` take `any_owner: true` to
+ act on somebody else's baton; that opt-out requires admin authority in
+ multi-user mode.
+- `ai-memory finalize-session --all-owners` does the same for sessions, and
+ `GET /admin/open-sessions?all_owners=true` is the underlying switch.
+- The read-only handoff listing (`GET
+ /api/v1/workspaces/{ws}/projects/{p}/handoffs`) serves its prompt-derived
+ fields — `summary`, `open_questions`, `next_steps` — to a caller the server
+ can name (their own rows plus the shared ones) and to the root operator, who
+ reads every page body through the wiki API anyway. A caller an authenticating
+ server can place as neither gets the metadata with `redacted: true`. A server
+ with no auth configured is unaffected: it already serves every page body
+ unauthenticated.
+- Handoff lifecycle events raise admission ops (`handoff_begin`,
+ `handoff_accept`, `handoff_cancel`), so an admission webhook can observe or —
+ with `failure_policy = "reject"` — refuse them. Only reject-policy hooks are
+ awaited on these ops; observers are notified after the operation is durable.
+
+"Multi-user mode" here means *the deployment distinguishes operators*: either
+`users` rows exist, or `[auth].actor_proxy_secret` is configured. A trusted
+proxy never writes a `users` row, so counting only rows would leave every
+proxied caller on the single-operator escape hatch that waves admin through.
+One question, every gate: the MCP admin tools, the `/admin/*` route layer, and
+the ownership stamped on handoffs and sessions all ask it.
+
## Implementation contract
Request identity and authorization are separate: