Skip to content

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

Rust

Merge main into feat/handoff-session-ownership after audit hardening

AkitaOnRailsa68dd3de8afd
diff --cc CHANGELOG.md
index 73018af5,155aa8b6..867635af
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -31,105 -25,6 +25,129 @@@ and this project adheres to [Semantic V
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 (#334).
+- 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 (#334).
+- 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
++ project's handoffs, filtered by `state` and scoped by owner, backed by new
++ non-partial indexes (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,
++ history. Cross-owner reads require the explicit root-only
++ `all_owners=true` recovery switch. 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 (#334).
+- 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 (#334).
+
+### 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 (#334).
+- 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 (#334).
++ finalizing a stuck session all carry a different identity. The atomic store
++ operation also rejects a handoff whose owner differs from its source session
++ (#334).
+- 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 (#334).
+- 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 (#334).
+- `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` (#334).
+- 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 (#334).
++ that read — so an OIDC-proxied operator's writes and reads land on the same
++ slot instead of silently missing on every read (#334).
++- Owner predicates for pending and exact-id handoff reads now execute in SQL
++ before prompt-derived fields are loaded. Exact-id cancellation returns the
++ same result for absent, wrong-scope and foreign-owner ids, so it no longer
++ discloses another operator's handoff state before authorization. Accept and
++ cancel also recheck the expected workspace and project in the atomic state
++ update, closing a lifecycle race between the scoped read and destructive
++ write (#334).
++- Ownership writes reject malformed identity keys, and malformed non-null
++ session-owner keys already present in the database fail closed during hook
++ processing instead of being converted to the shared `NULL` bucket.
++ Named-user handoff history uses two indexed shared/owned ranges, so a large
++ volume of another operator's rows cannot turn a bounded listing into a
++ project-wide scan (#334).
++- Actor-scoped briefing, overview and handoff-history responses now use
++ `Cache-Control: private, no-store`, preventing a browser from reusing one
++ operator's prompt-derived response after credentials at the same URL change
++ to another operator (#334).
++- Automatic session-start handoff admission is capped at 750 ms, below the
++ shortest shipped client's one-second fetch timeout. A slow deciding webhook
++ leaves the baton open instead of approving and consuming it after the caller
++ has disconnected (#334).
## [1.21.0] - 2026-07-31
diff --cc README.md
index d115a3d4,12cd595b..55235a3f
--- a/README.md
+++ b/README.md
@@@ -151,7 -151,7 +151,9 @@@ priors are at the [bottom](#influences-
provider health from the last real provider call. Server is the
single source of truth. `finalize-session` lists matching open
sessions through `GET /admin/open-sessions`, then posts synthetic
-- `session-end` hooks back to the server.
++ `session-end` hooks back to the server. On shared deployments it defaults to
++ the caller's own plus unattributed sessions; root can pass `--all-owners` for
++ explicit cross-operator recovery.
- **LLM is opt-in.** Zero-LLM mode still gives you FTS5, manually declared
entity, and graph-neighbor search plus rule-based summarisation. Add a
provider when you want consolidated pages, lint contradictions, or staged
@@@ -646,12 -649,12 +651,15 @@@ Useful entry points
GET /api/v1/workspaces/{workspace}/projects/{project}/briefing?limit=...
GET /api/v1/workspaces/{workspace}/overview?limit=...
GET /api/v1/workspaces/{workspace}/projects/{project}/overview?limit=...
++ GET /api/v1/workspaces/{workspace}/projects/{project}/handoffs?state=...&limit=...
GET /api/v1/search?q=...&workspace=...&project=...&limit=...
POST /api/v1/search { "q": "...", "scopes": [{ "workspace": "...", "project": "..." }] }
```
`overview` bundles the open handoff + briefing + memory-health for a workspace
-- or project in one call (the data a project overview screen needs).
++ or project in one call (the data a project overview screen needs). The
++ handoff history defaults to the caller's own plus shared rows; root can use
++ `all_owners=true` for recovery across operators.
**Full integration guide:** see [`docs/frontend-api.md`](docs/frontend-api.md)
for auth setup, response schemas, error model, limits/pagination,
diff --cc crates/ai-memory-core/src/actor.rs
index 596d3d9b,09abb74e..57c2273f
--- a/crates/ai-memory-core/src/actor.rs
+++ b/crates/ai-memory-core/src/actor.rs
@@@ -1,7 -1,7 +1,9 @@@
//! Per-request actor identity — who triggered an operation.
//!
--//! ai-memory's data is single-tenant (no RBAC; everyone with auth sees the
--//! same pages), but writes can be **attributed** to the user who made them.
++//! ai-memory's wiki is single-tenant (no per-page RBAC; everyone with auth sees
++//! the same pages), but writes can be **attributed** to the user who made them.
++//! Operational session and handoff state is owner-scoped so one operator
++//! cannot accidentally finalize or consume another operator's live context.
//! [`ActorContext`] is the typed carrier for that identity, injected once
//! per request by the auth middleware and threaded through to the writer
//! actor so attribution lands in the same SQL transaction as the data.
@@@ -16,11 -16,11 +18,10 @@@
//! from `[auth].root_username` / `root_email` (and optional `root_name`).
//! 3. **Identified multi-user** — bearer token matches an active
//! `users.token_hash` row. Middleware fills the actor from the row.
--//! 4. **External auth proxy** — operator runs an auth sidecar that injects
--//! pre-validated `X-Memory-Actor-*` headers; the middleware overlays
--//! them onto the rung 2/3 actor. (Scaffolding only in v1 — the `sub`
--//! and `client` fields below exist for this use case and the eventual
--//! admission webhook chain payload contract.)
++//! 4. **External auth proxy** — a trusted sidecar authenticates with the
++//! dedicated proxy bearer and asserts a username or complete OIDC
++//! issuer/subject pair in `X-Memory-Actor-*` headers. Proxy callers are users
++//! unless the stable OIDC pair exactly matches the configured root pair.
//!
//! ## Why not RBAC
//!
@@@ -161,13 -163,13 +164,14 @@@ impl AuthzError
impl AuthLevel {
/// Check whether this auth tier can use `capability`.
///
-- /// `multi_user_enabled` is the store-backed presence of any user row:
-- /// operational admin routes keep their historical bootstrap behavior until
-- /// the first user is created, while user-management is always root-only.
++ /// `distinguishes_operators` is true when the deployment has DB users or a
++ /// configured trusted identity proxy. Operational admin routes keep their
++ /// historical bootstrap behavior until either mode is active, while user
++ /// management is always root-only.
pub fn authorize(
self,
capability: Capability,
-- multi_user_enabled: bool,
++ distinguishes_operators: bool,
) -> Result<(), AuthzError> {
match capability {
Capability::NormalRead | Capability::NormalWrite => Ok(()),
@@@ -177,7 -179,7 +181,7 @@@
}
AuthLevel::Anonymous | AuthLevel::Root => Ok(()),
},
-- Capability::Admin if !multi_user_enabled => Ok(()),
++ Capability::Admin if !distinguishes_operators => Ok(()),
Capability::Admin => self.require_root(
"admin operation requires authentication in multi-user mode",
"admin operation is root-only in multi-user mode",
@@@ -293,13 -296,12 +298,12 @@@ impl ActorContext
/// also the direction that stays stable through the common upgrade — an
/// ingress that forwarded only `sub` and later starts forwarding a
/// username keeps the same key. The reverse upgrade (username-only, later
- /// adding `sub`) re-buckets once, at the moment the deployment starts
- /// asserting the stronger identifier; `docs/users.md` tells operators to
- /// forward `sub` from day one exactly so that moment never comes.
+ /// adding the OIDC pair) re-buckets once, at the moment the deployment starts
- /// asserting the stronger identifier; `docs/users.md` tells operators to
- /// forward `sub` from day one exactly so that moment never comes.
++ /// asserting the stronger identifier. Trusted-proxy ingress requires the
++ /// complete issuer/subject pair and rejects either field on its own.
///
- /// Blank and whitespace-only values name nobody — they would otherwise
- /// mint an owner literally called `""` that the next blank-actor caller
- /// would match. Same rule [`OwnerFilter::for_actor_context`] applies.
+ /// Blank and whitespace-only values name nobody. A partial OIDC pair is
+ /// deliberately not an identity; trusted-proxy ingress rejects it.
#[must_use]
pub fn identity_key(&self) -> Option<IdentityKey> {
let trimmed = |v: &Option<String>| {
@@@ -350,168 -355,6 +357,98 @@@ impl IdentityKey
Self::User(user) => format!("user:{user}"),
}
}
+
- /// Inverse of [`Self::storage_key`], for reading a stored owner back into
- /// the typed key.
++ /// Parse the qualified TEXT form produced by [`Self::storage_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.
++ /// Stored owners sometimes need to be turned back into a typed actor. The
++ /// OIDC form uses the encoded issuer byte length, so neither colons nor
++ /// non-ASCII text in the issuer or subject make the split ambiguous.
+ #[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()))
- })
++ let parsed = if let Some(user) = key.strip_prefix("user:") {
++ Self::User(user.to_owned())
++ } else {
++ let encoded = key.strip_prefix("oidc:")?;
++ let (issuer_len, remainder) = encoded.split_once(':')?;
++ let issuer_len = issuer_len.parse::<usize>().ok()?;
++ let issuer = remainder.get(..issuer_len)?;
++ let subject = remainder.get(issuer_len..)?;
++ Self::Subject {
++ issuer: issuer.to_owned(),
++ subject: subject.to_owned(),
++ }
++ };
++ // Production keys originate in `ActorContext::identity_key`, which
++ // trims and rejects blanks. Enforce the same invariant on persisted
++ // data so a corrupt `user:` / partial OIDC key cannot become a new
++ // ownership bucket when a session is finalized.
++ (parsed.to_actor_context().identity_key().as_ref() == Some(&parsed)).then_some(parsed)
+ }
+
- /// 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.
++ /// Build an actor that round-trips through [`ActorContext::identity_key`].
+ #[must_use]
+ pub fn to_actor_context(&self) -> ActorContext {
+ match self {
- Self::Subject(sub) => ActorContext {
- sub: Some(sub.clone()),
++ Self::Subject { issuer, subject } => ActorContext {
++ issuer: Some(issuer.clone()),
++ sub: Some(subject.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>/…`).
- ///
- /// Subjects and usernames may hold anything the IdP or operator chose —
- /// URLs are common subjects — and wiki pages are real files on every
- /// platform the server runs on, so the raw value cannot be a path
- /// component. Values made only of `[A-Za-z0-9._-]` (≤ 64 chars, no
- /// leading dot) pass through readably as `s-<value>` / `u-<value>`;
- /// anything else becomes lowercase hex of its UTF-8 bytes under the
- /// distinct `sx-` / `ux-` prefixes. The prefixes are what keep the
- /// encoding injective: a passthrough value that *looks* like hex
- /// (`s-c3a9`) can never collide with the value that *hexes* to the same
- /// digits (`sx-c3a9`).
- #[must_use]
- pub fn path_segment(&self) -> String {
- fn passthrough(value: &str) -> bool {
- value.len() <= 64
- && !value.starts_with('.')
- && value
- .chars()
- .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
- }
- fn hex(value: &str) -> String {
- value.bytes().fold(String::new(), |mut acc, b| {
- use std::fmt::Write;
- let _ = write!(acc, "{b:02x}");
- acc
- })
- }
- match self {
- Self::Subject(v) if passthrough(v) => format!("s-{v}"),
- Self::Subject(v) => format!("sx-{}", hex(v)),
- Self::User(v) if passthrough(v) => format!("u-{v}"),
- Self::User(v) => format!("ux-{}", hex(v)),
- }
- }
+}
+
+/// Which owned rows a caller is allowed to see or act on.
+///
- /// Used for handoffs and for sessions. A row whose owner is `None` is
- /// *shared*: it predates ownership, was written by a caller with no actor, or
- /// was deliberately published to the whole project. Shared rows stay visible
- /// to everyone, which is what keeps single-operator servers behaving exactly
- /// as before.
++/// A row whose owner is `None` is shared: it predates ownership, was written
++/// without an actor, or was deliberately published to the whole project.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum OwnerFilter {
- /// An identified caller: their own rows plus the shared ones. Holds the
- /// [`IdentityKey::storage_key`] form — the same TEXT that
- /// [`owner_stamp`] writes — so admit checks are exact string equality
- /// with no re-derivation.
++ /// The caller's own rows plus shared rows. The value is a qualified
++ /// [`IdentityKey::storage_key`].
+ User(String),
- /// A caller with no actor: shared rows only. Prevents an unattributed
- /// reader (or a browser hitting a read-only API) from draining or
- /// reading something that belongs to a specific operator.
++ /// A caller with no identity: shared rows only.
+ Unattributed,
- /// Explicit opt-in to every owner, for operator recovery ("give me
- /// whatever is pending here, even if it is not mine").
++ /// Explicit cross-owner access for authorized recovery paths.
+ Any,
+}
+
+impl OwnerFilter {
- /// Build the filter for a caller, applying the one identity rule in
- /// [`ActorContext::identity_key`] instead of re-deriving it at the call
- /// site.
++ /// Build the owner filter from the canonical actor identity.
+ #[must_use]
+ pub fn for_actor_context(actor: &ActorContext) -> Self {
- match actor.identity_key() {
- Some(key) => Self::User(key.storage_key()),
- None => Self::Unattributed,
- }
++ actor.identity_key().map_or(Self::Unattributed, |identity| {
++ Self::User(identity.storage_key())
++ })
+ }
+
- /// Does a row owned by `owner` pass this filter?
++ /// Whether a stored owner passes this filter.
+ #[must_use]
+ pub fn admits(&self, owner: Option<&str>) -> bool {
+ match (self, owner) {
- // Shared rows are visible to everyone (legacy + single-user).
- (_, None) => true,
- (Self::Any, _) => true,
++ (_, None) | (Self::Any, _) => true,
+ (Self::User(me), Some(owner)) => me == owner,
+ (Self::Unattributed, Some(_)) => false,
+ }
+ }
+}
+
- /// The owner to stamp on a row a request creates — the write-side mirror of
- /// [`OwnerFilter::for_actor_context`], which decides what that same request
- /// may read.
- ///
- /// `distinguishes_operators` is the deployment-level question the admin gates
- /// already ask (`users` rows exist, or a trusted proxy asserts identities),
- /// and it is what makes this more than `identity.map(storage_key)`.
++/// Derive the owner stored by an operator-distinguishing deployment.
+///
- /// # Why a deployment that names one operator must still stamp nothing
- ///
- /// On a server with `[auth].bearer_token` + `[auth].root_username` and no
- /// users and no proxy, every HTTP request resolves to that single name.
- /// Stamping it does not separate anybody from anybody — there is only one
- /// operator — but it does split that operator in two, because the transports
- /// disagree about whether a request carries an actor at all: the HTTP write
- /// would land owned, while the SAME person's stdio / in-process MCP transport
- /// carries no actor, filters as [`OwnerFilter::Unattributed`], and could no
- /// longer see what they just wrote. Producing the pre-ownership `NULL` there
- /// is what keeps the transports agreeing.
- ///
- /// The read side deliberately does **not** take this gate: a caller still
- /// filters as `OwnerFilter::User(key)`, which admits both the shared rows and
- /// any row already stamped with that key, so rows written while a deployment
- /// did distinguish operators stay reachable after it stops (the last `users`
- /// row is deleted).
++/// A single-operator server leaves rows shared even when its HTTP root has a
++/// username, because the same operator's stdio transport carries no actor.
+#[must_use]
+pub fn owner_stamp(
+ identity: Option<&IdentityKey>,
+ distinguishes_operators: bool,
+) -> Option<String> {
- if !distinguishes_operators {
- return None;
- }
- identity.map(IdentityKey::storage_key)
++ distinguishes_operators
++ .then(|| identity.map(IdentityKey::storage_key))
++ .flatten()
}
#[cfg(test)]
@@@ -676,106 -525,19 +619,88 @@@ mod tests
);
}
- /// The aliasing the qualified form exists to kill: a username equal to
- /// somebody else's subject is a DIFFERENT identity, in storage and in
- /// admit checks. Raw TEXT keys would have merged these two people.
#[test]
- fn a_username_never_aliases_an_equal_subject() {
+ fn identity_storage_keys_keep_namespaces_and_issuers_distinct() {
let by_name = IdentityKey::User("alice".into());
- let by_subject = IdentityKey::Subject("alice".into());
- assert_ne!(by_name.storage_key(), by_subject.storage_key());
- assert_ne!(by_name.path_segment(), by_subject.path_segment());
-
+ let issuer_a = IdentityKey::Subject {
+ issuer: "https://idp-a.example".into(),
+ subject: "alice".into(),
+ };
+ let issuer_b = IdentityKey::Subject {
+ issuer: "https://idp-b.example".into(),
+ subject: "alice".into(),
+ };
+ assert_ne!(by_name.storage_key(), issuer_a.storage_key());
+ assert_ne!(issuer_a.storage_key(), issuer_b.storage_key());
+ let names_filter = OwnerFilter::User(by_name.storage_key());
- assert!(!names_filter.admits(Some(&by_subject.storage_key())));
++ assert!(!names_filter.admits(Some(&issuer_a.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() {
++ fn storage_key_round_trips_to_actor_without_losing_issuer() {
+ 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()),
++ IdentityKey::User("oidc:4:idpalice".into()),
++ IdentityKey::Subject {
++ issuer: "https://idp.example/é".into(),
++ subject: "subject:42".into(),
++ },
+ ] {
+ assert_eq!(
- IdentityKey::from_storage_key(&key.storage_key()).as_ref(),
- Some(&key)
++ IdentityKey::from_storage_key(&key.storage_key()),
++ Some(key.clone())
+ );
++ assert_eq!(key.to_actor_context().identity_key(), Some(key));
++ }
++ for malformed in [
++ "",
++ "alice",
++ "user:",
++ "user: ",
++ "user: alice ",
++ "oidc:",
++ "oidc:0:subject",
++ "oidc:3:idp",
++ "oidc:3: idsubject",
++ "oidc:x:idpsub",
++ "oidc:99:idpsub",
++ "oidc:1:ésub",
++ ] {
+ assert_eq!(
- key.to_actor_context().identity_key().as_ref(),
- Some(&key),
- "to_actor_context must name the same operator"
++ IdentityKey::from_storage_key(malformed),
++ None,
++ "{malformed}"
+ );
+ }
- 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
- /// the value that hexes to the same digits.
- #[test]
- fn path_segment_is_filesystem_safe_and_injective() {
- assert_eq!(IdentityKey::User("alice".into()).path_segment(), "u-alice");
- assert_eq!(
- IdentityKey::Subject("103459784".into()).path_segment(),
- "s-103459784"
- );
- let url_sub = IdentityKey::Subject("https://idp.example/id/42".into());
- let seg = url_sub.path_segment();
- assert!(seg.starts_with("sx-"), "url subject must hex-encode: {seg}");
- assert!(
- seg.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'),
- "segment must be path-safe: {seg}"
- );
- // The ambiguity the split prefixes prevent: "c3a9" passes through,
- // "é" hexes to c3a9 — different prefixes, no collision.
- assert_eq!(IdentityKey::Subject("c3a9".into()).path_segment(), "s-c3a9");
- assert_eq!(IdentityKey::Subject("é".into()).path_segment(), "sx-c3a9");
+ }
+
- /// The write-side gate: identity alone is not enough to stamp — the
- /// deployment must actually distinguish operators, or a single-operator
- /// server would split its own transports (HTTP names the operator, stdio
- /// carries no actor).
+ #[test]
- fn owner_stamp_requires_both_identity_and_a_distinguishing_deployment() {
- let key = IdentityKey::Subject("oidc-subject-123".into());
++ fn owner_stamp_requires_identity_and_operator_distinction() {
++ let key = IdentityKey::Subject {
++ issuer: "https://idp.example".into(),
++ subject: "oidc-subject-123".into(),
++ };
+ assert_eq!(owner_stamp(Some(&key), false), None);
+ assert_eq!(owner_stamp(None, true), None);
- assert_eq!(
- owner_stamp(Some(&key), true),
- Some("sub:oidc-subject-123".into())
- );
++ assert_eq!(owner_stamp(Some(&key), true), Some(key.storage_key()));
+ }
+
- /// The admit matrix in one place: shared rows reach everyone, owned rows
- /// reach their owner and `Any`, and an unattributed caller sees only the
- /// shared ones.
+ #[test]
+ fn owner_filter_admit_matrix() {
+ let alice = OwnerFilter::for_actor_context(&ActorContext {
+ user: Some("alice".into()),
+ ..ActorContext::default()
+ });
+ let owned = IdentityKey::User("alice".into()).storage_key();
+ let other = IdentityKey::User("bob".into()).storage_key();
+
+ for filter in [&alice, &OwnerFilter::Unattributed, &OwnerFilter::Any] {
- assert!(filter.admits(None), "shared rows reach everyone");
++ assert!(filter.admits(None));
+ }
+ assert!(alice.admits(Some(&owned)));
+ assert!(!alice.admits(Some(&other)));
+ assert!(!OwnerFilter::Unattributed.admits(Some(&owned)));
+ assert!(OwnerFilter::Any.admits(Some(&other)));
}
/// Naming nobody stays naming nobody: an agent/session-only actor carries
diff --cc crates/ai-memory-core/src/routing_skills/ai-memory-handoff/SKILL.md
index bca27f2b,bca27f2b..c1014b93
--- a/crates/ai-memory-core/src/routing_skills/ai-memory-handoff/SKILL.md
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-handoff/SKILL.md
@@@ -26,10 -26,10 +26,14 @@@ Create a handoff only at session end o
Lifecycle hooks already capture routine prompts and tool calls, so do not manually write a handoff just to record normal progress.
++On a shared server, a handoff belongs to the operator who created it. Set `shared: true` only when the user explicitly wants any operator in the project to receive the baton; do not infer sharing from ordinary collaboration prose.
++
## Canceling a handoff
Cancel only when the user asks to discard a handoff or you created one by mistake. Use the exact handoff id returned by the begin tool. Cancellation is idempotent from the user's point of view, but it should still target only the known handoff.
++Accept and cancel normally act only on the caller's own plus shared handoffs. `any_owner: true` is a root-only recovery action over another operator's context; use it only on an explicit user request.
++
## Scope default
Default to the current project. Pass workspace and project together only when the user names a different project. Never pass scope arguments just because the user says this project, here, we, or our work.
diff --cc crates/ai-memory-hooks/src/router.rs
index 7356d686,d4f38828..4662e89e
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@@ -60,6 -60,6 +60,14 @@@ pub const DEFAULT_INGEST_GATE_MAX_ENTRI
/// allocate/process an unbounded vector of hook events.
pub const MAX_HOOK_BATCH_ITEMS: usize = 256;
++/// Upper bound for reject-policy admission on the synchronous `/handoff`
++/// path. The shortest shipped client deadline is the shell hook's one-second
++/// curl timeout, so the server must decide earlier or leave the baton open;
++/// otherwise an approved response can consume context after the client has
++/// already disconnected and can no longer receive it.
++const AUTOMATIC_HANDOFF_ADMISSION_TIMEOUT: std::time::Duration =
++ std::time::Duration::from_millis(750);
++
/// Maximum cwd-resolution cache entries kept per server process. The cache is
/// an optimization only; evicted entries are re-resolved through the writer.
pub const DEFAULT_PROJECT_CACHE_MAX_ENTRIES: usize = 4096;
@@@ -474,85 -474,6 +482,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
++ /// `[auth].actor_proxy_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
++/// the ingress that forwards an OIDC issuer/subject pair 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`
@@@ -591,16 -510,13 +599,16 @@@ 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
- // derive its qualified identity NOW, before the spawn drops the request
- // extensions, so `process()` can key `ActiveProject` consistently with MCP.
- let actor_identity = actor_ext
- .and_then(|axum::Extension(ctx)| ctx.identity_key())
- .map(|identity| identity.storage_key());
+ // 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 = 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_storage_key = actor.as_ref().map(IdentityKey::storage_key);
let actor_key = ActorKey {
- user: actor_user.clone(),
- user: actor_identity.clone(),
++ user: actor_storage_key.clone(),
session_id: env.session_id.clone(),
};
if should_drop_subagent(&state, &env, &actor_key).await {
@@@ -610,7 -526,7 +618,7 @@@
warn!("hook ingest saturated; dropping event with 429");
return (StatusCode::TOO_MANY_REQUESTS, "hook queue full");
};
- let rate_key = ingest_rate_key(&env, actor_user.as_deref());
- let rate_key = ingest_rate_key(&env, actor_identity.as_deref());
++ let rate_key = ingest_rate_key(&env, actor_storage_key.as_deref());
if !state
.ingest_rate
.lock()
@@@ -738,9 -652,9 +746,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_identity = actor_ext
- .and_then(|axum::Extension(ctx)| ctx.identity_key())
- .map(|identity| identity.storage_key());
+ 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 actor_storage_key = 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
@@@ -760,7 -674,7 +768,7 @@@
continue;
};
let actor_key = ActorKey {
- user: actor_user.clone(),
- user: actor_identity.clone(),
++ user: actor_storage_key.clone(),
session_id: env.session_id.clone(),
};
// Accept-but-drop subagent captures (see `handle_hook`): count the item
@@@ -780,7 -694,7 +788,7 @@@
Json(HookBatchAck::indexed(accepted_indices)),
);
};
- let rate_key = ingest_rate_key(&env, actor_user.as_deref());
- let rate_key = ingest_rate_key(&env, actor_identity.as_deref());
++ let rate_key = ingest_rate_key(&env, actor_storage_key.as_deref());
if !state
.ingest_rate
.lock()
@@@ -1225,61 -1128,13 +1233,65 @@@ 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.
++ // - Only a webhook the operator set to `reject` is waited for. An
++ // ignore-policy webhook cannot refuse anything, so observers are notified
++ // below, off the critical path, once the claim is durable. The deciding
++ // chain is also capped by `AUTOMATIC_HANDOFF_ADMISSION_TIMEOUT`, below the
++ // shortest shipped client's one-second deadline. Without that server-side
++ // bound, a slow approval could consume the single-use baton after the
++ // client had disconnected and could no longer receive it.
+ // - 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(
++ let authorized = tokio::time::timeout(
++ AUTOMATIC_HANDOFF_ADMISSION_TIMEOUT,
++ 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;
++ ),
++ )
++ .await;
+ match authorized {
- Ok(ctx) => (Some(pending), ctx),
- Err(e) => {
++ Ok(Ok(ctx)) => (Some(pending), ctx),
++ Ok(Err(e)) => {
+ warn!(error = %e, "handoff claim refused by admission chain; leaving it open");
+ (None, None)
+ }
++ Err(_) => {
++ warn!(
++ timeout_ms = AUTOMATIC_HANDOFF_ADMISSION_TIMEOUT.as_millis(),
++ "handoff admission exceeded the session-start deadline; leaving it open"
++ );
++ (None, None)
++ }
+ }
+ }
+ None => (None, None),
+ };
let acceptance = if handoff.is_some() || managed.is_some() {
state
.writer
.accept_startup_context(
handoff.as_ref().map(|handoff| handoff.id),
++ ws,
++ proj,
agent,
None,
+ actor.as_ref().map(IdentityKey::storage_key),
+ owner_filter,
managed.as_ref().map(|managed| managed.run_id),
query.cwd.clone(),
)
@@@ -2389,36 -2224,8 +2401,28 @@@ 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()
- }
- };
++ // Whose session this is, as recorded at session start (a qualified storage
++ // key). Everything written on its behalf is attributed to that owner, not
++ // to whoever delivered the event. A NULL owner stays shared. V40
++ // deliberately migrated legacy rows to NULL,
++ // and current actorless sessions use the same value; attributing either to
++ // whoever delivers SessionEnd would silently rebucket shared context. A
++ // store failure aborts this event rather than guessing an owner.
++ let session_owner = parse_session_owner(state.reader.session_actor_user(session_id).await?)?;
+ 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");
}
@@@ -2441,27 -2248,14 +2445,24 @@@
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.
++ // identity. NULL stays anonymous/shared, including rows that
++ // predate owner recording.
+ 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.
++ // gate again because even an attributed session remains shared on a
++ // deployment that does not tell its operators apart — otherwise the
++ // baton lands in a bucket the operator's actorless 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,
@@@ -2585,6 -2311,6 +2586,17 @@@
Ok(())
}
++/// Parse the persisted owner without turning corrupt owned data into shared
++/// data. Only SQL NULL has the intentional legacy/shared meaning.
++fn parse_session_owner(owner: Option<String>) -> anyhow::Result<Option<IdentityKey>> {
++ owner
++ .map(|owner| {
++ IdentityKey::from_storage_key(&owner)
++ .ok_or_else(|| anyhow::anyhow!("malformed stored session owner identity"))
++ })
++ .transpose()
++}
++
fn resolve_session_id(env: &HookEnvelope) -> anyhow::Result<SessionId> {
if let Some(raw) = &env.session_id {
// Accept either a UUID (canonical) or any string, hashing the
@@@ -5873,874 -5471,47 +5885,923 @@@ 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
++ /// human the request names. An ingress that forwards an OIDC issuer/subject
++ /// pair 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 sub_only_proxy_session_start_claims_its_own_baton() {
- async fn already_ended_session_end_does_not_create_summary_or_handoff() {
++ async fn oidc_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())),
++ Some(&IdentityKey::Subject {
++ issuer: "https://idp.example".into(),
++ 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 {
++ issuer: Some("https://idp.example".into()),
+ 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)
- .await
- .unwrap();
+ /// 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 shared session stays shared even when a named operator delivers its
++ /// SessionEnd. NULL is both the migration value for pre-V40 sessions and
++ /// the intentional owner of current actorless sessions; neither may be
++ /// reassigned to the finalizer.
++ #[tokio::test]
++ async fn shared_session_end_is_not_rebucketed_to_the_delivery_actor() {
++ let tmp = TempDir::new().unwrap();
++ let mut state = make_state(&tmp).await;
++ state.trusted_proxy_identity = true;
++
++ process(
++ &state,
++ session_envelope("user-prompt-submit", "shared-session", "/tmp/scratch"),
++ None,
++ Vec::new(),
++ )
++ .await
++ .unwrap();
++ process(
++ &state,
++ session_envelope("session-end", "shared-session", "/tmp/scratch"),
++ Some(IdentityKey::User("alice".into())),
++ Vec::new(),
++ )
++ .await
++ .unwrap();
++
++ 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 delivery actor took ownership of a shared session's baton",
++ );
++ }
++
++ #[test]
++ fn malformed_session_owner_does_not_become_shared() {
++ assert_eq!(parse_session_owner(None).unwrap(), None);
++ assert_eq!(
++ parse_session_owner(Some("user:alice".into())).unwrap(),
++ Some(IdentityKey::User("alice".into()))
++ );
++ assert!(parse_session_owner(Some("user: ".into())).is_err());
++ assert!(parse_session_owner(Some("oidc:3:idp".into())).is_err());
++ }
++
+ /// 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
++ /// `GET /handoff` is called synchronously by the session-start hook. 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`].
++ /// The 200 ms below is this test's own webhook timeout choice. It completes
++ /// before the aggregate server deadline, so the webhook's refusal is what
++ /// decides the result.
+ #[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.
++ /// The webhook default is longer than the shortest client deadline. The
++ /// server must stop first and leave the baton open; otherwise a late
++ /// approval can consume context after the client has disconnected.
+ #[tokio::test]
- async fn a_reject_webhook_on_its_default_timeout_outlasts_the_hook_budget() {
++ async fn default_reject_timeout_is_capped_before_the_client_disconnects() {
+ 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:?}",
++ elapsed < Duration::from_millis(1_500),
++ "the server must abandon admission before the shell client is long gone: {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!(
pages
.iter()
diff --cc crates/ai-memory-mcp/src/admin.rs
index 7be3aea3,8daacbea..96adb8f1
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@@ -601,7 -601,7 +601,7 @@@ async fn require_root_for_multiuser_adm
// with no `users` rows would wave a proxy-asserted `AuthLevel::User` caller
// through every operational route below — purge, delete-page, backup — and
// only `/admin/users*` would survive on its own inner root check.
-- let multi_user_enabled = match state
++ let distinguishes_operators = match state
.reader
.distinguishes_operators(state.trusted_proxy_identity)
.await
@@@ -618,7 -618,7 +618,7 @@@
.into_response();
}
};
-- match level.authorize(Capability::Admin, multi_user_enabled) {
++ match level.authorize(Capability::Admin, distinguishes_operators) {
Ok(()) => next.run(req).await,
Err(e) => (
authz_status(e),
@@@ -5110,7 -5091,7 +5110,9 @@@ fn map_user_store_err(e: ai_memory_stor
#[cfg(test)]
mod tests {
use super::*;
-- use ai_memory_core::{AgentKind, NewObservation, NewSession, ObservationKind};
++ use ai_memory_core::{
++ ActorContext, AgentKind, IdentityKey, NewObservation, NewSession, ObservationKind,
++ };
use ai_memory_core::{Sanitized, Sanitizer};
use ai_memory_llm::{ChatRequest, ChatResponse, LlmResult};
use ai_memory_store::Store;
@@@ -5245,6 -5226,6 +5247,8 @@@
let other_agent = SessionId::new();
let other_scope = SessionId::new();
let ended = SessionId::new();
++ let alice = SessionId::new();
++ let bob = SessionId::new();
for (id, project_id, agent) in [
(older, target, AgentKind::Codex),
(other_agent, target, AgentKind::ClaudeCode),
@@@ -5266,6 -5246,6 +5270,20 @@@
.unwrap();
}
store.writer.end_session(ended, None).await.unwrap();
++ for (id, user) in [(alice, "alice"), (bob, "bob")] {
++ store
++ .writer
++ .begin_session(NewSession {
++ id,
++ workspace_id: ws,
++ project_id: target,
++ agent_kind: AgentKind::Codex,
++ cwd: Some(std::path::PathBuf::from("/tmp/target")),
++ actor_user: Some(IdentityKey::User(user.into()).storage_key()),
++ })
++ .await
++ .unwrap();
++ }
let router = admin_router(AdminState {
writer: store.writer.clone(),
@@@ -5331,6 -5311,6 +5349,37 @@@
assert!(ids.contains(&latest.to_string().as_str()));
assert!(ids.contains(&older.to_string().as_str()));
++ // A named operator gets their own open sessions plus shared legacy
++ // sessions, never a colleague's. This is the exact route consumed by
++ // the destructive `finalize-session` command.
++ let resp = router
++ .clone()
++ .oneshot(
++ Request::builder()
++ .uri("/admin/open-sessions?workspace=default&project=target&agent=codex&all=true")
++ .extension(ActorContext {
++ user: Some("alice".into()),
++ ..ActorContext::default()
++ })
++ .body(Body::empty())
++ .unwrap(),
++ )
++ .await
++ .unwrap();
++ assert_eq!(resp.status(), StatusCode::OK);
++ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
++ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
++ let ids = json["sessions"]
++ .as_array()
++ .unwrap()
++ .iter()
++ .map(|session| session["session_id"].as_str().unwrap())
++ .collect::<Vec<_>>();
++ assert!(ids.contains(&alice.to_string().as_str()));
++ assert!(ids.contains(&latest.to_string().as_str()));
++ assert!(ids.contains(&older.to_string().as_str()));
++ assert!(!ids.contains(&bob.to_string().as_str()));
++
// Unknown agent kind fails closed with a 400.
let resp = router
.clone()
diff --cc crates/ai-memory-mcp/src/server.rs
index d7e6a8cf,84f4ccc0..c5088ce3
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@@ -216,7 -216,7 +216,9 @@@ developer, user, and canonical project
THAT is the handoff — answer from it directly, don't re-call \
this tool (it'll return null because handoffs are single-use). Pass \
`workspace` + `project` together only when the user names a handoff \
-- in a sibling workspace/project.\n\
++ in a sibling workspace/project. On shared servers the default is your \
++ own plus deliberately shared handoffs; `any_owner=true` is root-only \
++ recovery and requires an explicit user request.\n\
- `memory_handoff_begin` — ONLY when the user is wrapping up / ending \
the current session and you want to ensure the next agent has context \
(the SessionEnd hook also auto-captures this). DO NOT use this to \
@@@ -224,11 -224,11 +226,14 @@@
for a briefing. Keep the summary terse (2-3 sentences); put detail \
in open_questions + next_steps bullets. Pass `workspace` + `project` \
together only when leaving a handoff for a named sibling \
-- workspace/project.\n\
++ workspace/project. Handoffs belong to their creator by default; pass \
++ `shared=true` only when the user explicitly wants any operator in the \
++ project to receive it.\n\
- `memory_handoff_cancel` — when you realize you mistakenly called \
`memory_handoff_begin`, or the user explicitly asks to discard a \
pending handoff. Requires the exact `handoff_id` from the begin call \
-- and marks it expired so the next session will not consume it.\n\
++ and marks it expired so the next session will not consume it. \
++ `any_owner=true` is root-only recovery and requires an explicit user request.\n\
- `memory_consolidate` — when the user asks to compile session \
observations into wiki pages. Also runs on PreCompact, and at \
session end only when AI_MEMORY_CONSOLIDATE_ON_SESSION_END is set. \
@@@ -1070,14 -1050,9 +1074,14 @@@ impl AiMemoryServer
return ai_memory_core::ActorKey::default();
};
let ctx = parts.extensions.get::<ai_memory_core::ActorContext>();
+ // 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
++ // on the whole qualified identity would put an OIDC-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(|identity| identity.storage_key());
+ .map(|key| key.storage_key());
let header_session = |name: &str| {
parts
.headers
@@@ -1955,12 -1886,12 +1959,12 @@@
let Some(level) = parts.extensions.get::<ai_memory_core::AuthLevel>().copied() else {
return Ok(());
};
-- let multi_user_enabled = self
++ let distinguishes_operators = self
.deployment_distinguishes_operators()
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
level
-- .authorize(ai_memory_core::Capability::Admin, multi_user_enabled)
++ .authorize(ai_memory_core::Capability::Admin, distinguishes_operators)
.map_err(|e| McpError::invalid_request(e.message().to_string(), None))
}
@@@ -2780,11 -2707,6 +2784,16 @@@
"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 owner_user = if args.shared.unwrap_or(false) {
++ None
++ } else {
++ let distinguishes = self
++ .deployment_distinguishes_operators()
++ .await
++ .map_err(|e| McpError::internal_error(e.to_string(), None))?;
++ ai_memory_core::owner_stamp(creator.identity_key().as_ref(), distinguishes)
++ };
let handoff = NewHandoff {
workspace_id: ws,
project_id: proj,
@@@ -2800,21 -2722,7 +2809,17 @@@
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)
- },
++ owner_user,
};
+ let admission = self
+ .authorize_operation(ws, proj, ai_memory_wiki::AdmissionOp::HandoffBegin, &parts)
+ .await?;
let id = self
.writer
.insert_handoff(handoff)
@@@ -2881,43 -2772,11 +2886,45 @@@
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,
++ ws,
++ proj,
+ 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 }))
+ }
}
}
}
@@@ -2946,18 -2805,18 +2953,26 @@@
&aps_actor,
)
.await?;
++ // Resolve the cross-owner escape hatch before reading the object. A
++ // non-admin request must not trigger admission webhooks or learn that
++ // another operator's exact id exists.
++ 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 handoff = self
.reader
-- .handoff_by_id(handoff_id)
++ .handoff_by_id_in_scope(ws, proj, handoff_id, cancel_owner_filter.clone())
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?
-- .ok_or_else(|| McpError::internal_error("handoff not found", None))?;
-- if handoff.workspace_id != ws || handoff.project_id != proj {
-- return Err(McpError::internal_error(
-- "handoff does not belong to the resolved project",
-- None,
-- ));
-- }
++ .ok_or_else(|| {
++ McpError::internal_error(
++ "handoff not found in the resolved project or not visible to this operator",
++ None,
++ )
++ })?;
if handoff.state != HandoffState::Open {
return ok_json(&serde_json::json!({
"handoff_id": handoff_id.to_string(),
@@@ -2965,46 -2824,16 +2980,30 @@@
"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_owner_filter)
- .cancel_handoff(handoff_id)
++ .cancel_handoff(handoff_id, ws, proj, 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!({
++ let 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).
@@@ -8173,6 -7985,6 +8190,106 @@@ mod tests
assert_eq!(stored.state, HandoffState::Expired);
}
++ #[tokio::test]
++ async fn handoff_cancel_hides_foreign_ids_before_object_state_is_read() {
++ let (_tmp, store, server, ws, proj) = setup_server().await;
++ let bob_id = store
++ .writer
++ .insert_handoff(NewHandoff {
++ workspace_id: ws,
++ project_id: proj,
++ from_session_id: None,
++ from_agent: AgentKind::Codex,
++ to_agent: None,
++ cwd: None,
++ summary: "Bob's private prompt-derived context".into(),
++ open_questions: vec!["private question".into()],
++ next_steps: vec!["private next step".into()],
++ files_touched: vec![],
++ owner_user: Some(ai_memory_core::IdentityKey::User("bob".into()).storage_key()),
++ })
++ .await
++ .unwrap();
++
++ let mut alice_parts = test_parts_default();
++ alice_parts.extensions.insert(AuthLevel::User);
++ alice_parts.extensions.insert(ActorContext {
++ user: Some("alice".into()),
++ ..ActorContext::default()
++ });
++ let foreign = server
++ .memory_handoff_cancel(
++ Parameters(HandoffCancelArgs {
++ handoff_id: bob_id.to_string(),
++ project: None,
++ workspace: None,
++ any_owner: None,
++ }),
++ OptionalParts(alice_parts),
++ )
++ .await
++ .expect_err("Alice must not inspect or cancel Bob's handoff");
++
++ let mut alice_parts = test_parts_default();
++ alice_parts.extensions.insert(AuthLevel::User);
++ alice_parts.extensions.insert(ActorContext {
++ user: Some("alice".into()),
++ ..ActorContext::default()
++ });
++ let absent = server
++ .memory_handoff_cancel(
++ Parameters(HandoffCancelArgs {
++ handoff_id: HandoffId::new().to_string(),
++ project: None,
++ workspace: None,
++ any_owner: None,
++ }),
++ OptionalParts(alice_parts),
++ )
++ .await
++ .expect_err("an absent handoff must fail");
++
++ assert_eq!(
++ foreign.to_string(),
++ absent.to_string(),
++ "a known foreign id must be indistinguishable from an absent id"
++ );
++ assert!(!foreign.to_string().contains("Bob"));
++ assert!(!foreign.to_string().contains("state"));
++ assert_eq!(
++ store
++ .reader
++ .handoff_by_id(bob_id)
++ .await
++ .unwrap()
++ .unwrap()
++ .state,
++ HandoffState::Open,
++ );
++
++ let mut root_parts = test_parts_default();
++ root_parts.extensions.insert(AuthLevel::Root);
++ let result = server
++ .memory_handoff_cancel(
++ Parameters(HandoffCancelArgs {
++ handoff_id: bob_id.to_string(),
++ project: None,
++ workspace: None,
++ any_owner: Some(true),
++ }),
++ OptionalParts(root_parts),
++ )
++ .await
++ .expect("root recovery can cancel a foreign handoff");
++ let text = result
++ .content
++ .first()
++ .and_then(|content| content.as_text())
++ .map(|content| content.text.as_str())
++ .unwrap_or_default();
++ assert!(text.contains("\"cancelled\": true"), "{text}");
++ }
++
// ----------------------------------------------------------------
// Error / mis-configured paths — caught at the tool boundary so the
// agent sees a clean McpError instead of a panic.
diff --cc crates/ai-memory-mcp/tests/handoff_admission.rs
index f6e7ee77,00000000..d76ca46f
mode 100644,000000..100644
--- a/crates/ai-memory-mcp/tests/handoff_admission.rs
+++ b/crates/ai-memory-mcp/tests/handoff_admission.rs
@@@ -1,433 -1,0 +1,432 @@@
+//! 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";
++const PROXY_TOKEN: &str = "the-proxy-token";
+
+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.
++/// `[auth].actor_proxy_bearer_token` 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);
++ .with_trusted_proxy_bearer(PROXY_TOKEN);
+ 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),
++ ("authorization", "Bearer the-proxy-token"),
+ ("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 --cc crates/ai-memory-mcp/tests/handoff_identity.rs
index 862e2ce5,00000000..9252affd
mode 100644,000000..100644
--- a/crates/ai-memory-mcp/tests/handoff_identity.rs
+++ b/crates/ai-memory-mcp/tests/handoff_identity.rs
@@@ -1,329 -1,0 +1,328 @@@
+//! 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
++//! that asserts a complete OIDC issuer/subject pair to `AuthLevel::User` —
++//! it named somebody. If ownership keys on `actor.user` alone, that 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";
++const PROXY_TOKEN: &str = "the-proxy-token";
+
+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
++/// `[auth].actor_proxy_bearer_token`, 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);
++ auth_state = auth_state.with_trusted_proxy_bearer(PROXY_TOKEN);
+ }
+ 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),
- ]
++ let mut headers = vec![("authorization", "Bearer the-proxy-token"), (header, value)];
++ if header == "x-memory-actor-sub" {
++ headers.push(("x-memory-actor-issuer", "https://idp.example"));
++ }
++ headers
+}
+
+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.
++/// An ingress that terminates OIDC and forwards the stable issuer/subject pair
++/// names a human. Ownership has to retain both parts or proxied operators can
++/// share a bucket and read batons synthesised from a colleague's prompts.
+#[tokio::test]
- async fn sub_only_proxy_operators_do_not_share_a_bucket() {
++async fn oidc_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",
++ "OIDC 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 --cc crates/ai-memory-store/migrations/V41__handoffs_listing_index.sql
index f4f15ff6,00000000..bbca677c
mode 100644,000000..100644
--- a/crates/ai-memory-store/migrations/V41__handoffs_listing_index.sql
+++ b/crates/ai-memory-store/migrations/V41__handoffs_listing_index.sql
@@@ -1,12 -1,0 +1,19 @@@
+-- 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.
++-- Non-partial and ordered to match the root recovery query's
++-- `ORDER BY created_at DESC`, so that 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);
++
++-- The normal listing is owner-scoped. Keep a separate owner-first index so a
++-- project with a high volume of other operators' rows does not have to scan
++-- their history before finding the caller's own/shared rows.
++CREATE INDEX idx_handoffs_project_owner_recent
++ ON handoffs (workspace_id, project_id, owner_user, created_at DESC);
diff --cc crates/ai-memory-store/src/lib.rs
index 03742a22,3b44e07d..d0c85685
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@@ -2831,11 -2820,10 +2831,11 @@@ mod tests
project_id: proj,
agent_kind: AgentKind::Codex,
cwd: None,
- actor_user: None,
++ actor_user: Some("user:alice".into()),
})
.await
.unwrap();
-- let handoff = |project_id| NewHandoff {
++ let handoff = |project_id, owner: Option<&str>| NewHandoff {
workspace_id: ws,
project_id,
from_session_id: Some(session_id),
@@@ -2846,13 -2834,12 +2846,13 @@@
open_questions: Vec::new(),
next_steps: Vec::new(),
files_touched: Vec::new(),
- owner_user: None,
++ owner_user: owner.map(str::to_string),
};
assert!(
store
.writer
-- .end_session_with_handoff(session_id, None, handoff(other))
++ .end_session_with_handoff(session_id, None, handoff(other, Some("user:alice")),)
.await
.is_err(),
"a mismatched handoff must reject the whole end transition"
@@@ -2867,9 -2854,9 +2867,27 @@@
"failed handoff insertion must leave the session open"
);
++ assert!(
++ store
++ .writer
++ .end_session_with_handoff(session_id, None, handoff(proj, Some("user:bob")),)
++ .await
++ .is_err(),
++ "a mismatched owner must reject the whole end transition"
++ );
++ assert_eq!(
++ store
++ .reader
++ .session_end_disposition(session_id, ws, proj, AgentKind::Codex)
++ .await
++ .unwrap(),
++ SessionEndDisposition::Open,
++ "an owner mismatch must leave the session open"
++ );
++
store
.writer
-- .end_session_with_handoff(session_id, None, handoff(proj))
++ .end_session_with_handoff(session_id, None, handoff(proj, Some("user:alice")))
.await
.unwrap();
let conn = Connection::open(store.db_path()).unwrap();
@@@ -4965,10 -4930,8 +4983,12 @@@
.writer
.accept_startup_context(
Some(first_handoff),
++ ws,
++ proj,
AgentKind::Codex,
None,
+ None,
+ ai_memory_core::OwnerFilter::Any,
Some(run.run_id),
None,
)
@@@ -4995,10 -4958,8 +5015,12 @@@
.writer
.accept_startup_context(
Some(second_handoff),
++ ws,
++ proj,
AgentKind::Codex,
None,
+ None,
+ ai_memory_core::OwnerFilter::Any,
Some(run.run_id),
None,
)
@@@ -5065,10 -5024,8 +5087,12 @@@
.writer
.accept_startup_context(
Some(selected_auto),
++ ws,
++ proj,
AgentKind::Codex,
None,
+ None,
+ ai_memory_core::OwnerFilter::Any,
Some(run.run_id),
Some("/repo/api/src".into()),
)
diff --cc crates/ai-memory-store/src/migrations.rs
index b1c8a513,3c1ec00a..250e0940
--- a/crates/ai-memory-store/src/migrations.rs
+++ b/crates/ai-memory-store/src/migrations.rs
@@@ -52,7 -52,7 +52,7 @@@ pub(crate) fn run_to(conn: &mut rusqlit
#[cfg(test)]
mod tests {
use super::*;
- use ai_memory_core::{AgentKind, NewObservation, ObservationKind, SessionId};
- use ai_memory_core::{AgentKind, NewObservation, NewSession, ObservationKind, SessionId};
++ use ai_memory_core::{AgentKind, HandoffId, NewObservation, ObservationKind, SessionId};
use rusqlite::{Connection, params};
/// A store migrated by a newer build (an applied version above anything
@@@ -433,4 -427,4 +433,73 @@@
.unwrap()
);
}
++
++ #[test]
++ fn v39_to_v41_preserve_existing_rows_as_shared_and_add_listing_indexes() {
++ let mut conn = Connection::open_in_memory().unwrap();
++ run_to(&mut conn, 38).unwrap();
++ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
++ let workspace_id = crate::ops::get_or_create_workspace(&mut conn, "default").unwrap();
++ let project_id =
++ crate::ops::get_or_create_project(&mut conn, &workspace_id, "project", None).unwrap();
++ let session_id = SessionId::new();
++ let handoff_id = HandoffId::new();
++ conn.execute(
++ "INSERT INTO sessions \
++ (id, workspace_id, project_id, agent_kind, cwd, started_at) \
++ VALUES (?1, ?2, ?3, ?4, NULL, 1)",
++ params![
++ session_id.as_bytes(),
++ workspace_id.as_bytes(),
++ project_id.as_bytes(),
++ AgentKind::Codex.as_str(),
++ ],
++ )
++ .unwrap();
++ conn.execute(
++ "INSERT INTO handoffs \
++ (id, workspace_id, project_id, from_agent, summary, created_at) \
++ VALUES (?1, ?2, ?3, ?4, ?5, 1)",
++ params![
++ handoff_id.as_bytes(),
++ workspace_id.as_bytes(),
++ project_id.as_bytes(),
++ AgentKind::Codex.as_str(),
++ "legacy baton",
++ ],
++ )
++ .unwrap();
++
++ run(&mut conn).unwrap();
++
++ let actor_user: Option<String> = conn
++ .query_row(
++ "SELECT actor_user FROM sessions WHERE id = ?1",
++ params![session_id.as_bytes()],
++ |row| row.get(0),
++ )
++ .unwrap();
++ let (owner_user, accepted_by_user): (Option<String>, Option<String>) = conn
++ .query_row(
++ "SELECT owner_user, accepted_by_user FROM handoffs WHERE id = ?1",
++ params![handoff_id.as_bytes()],
++ |row| Ok((row.get(0)?, row.get(1)?)),
++ )
++ .unwrap();
++ assert_eq!(actor_user, None, "legacy sessions remain shared");
++ assert_eq!(owner_user, None, "legacy handoffs remain shared");
++ assert_eq!(accepted_by_user, None);
++ for index in [
++ "idx_handoffs_open_owner",
++ "idx_sessions_open_owner",
++ "idx_handoffs_project_recent",
++ "idx_handoffs_project_owner_recent",
++ ] {
++ assert_eq!(
++ schema_object_count(&conn, "index", index),
++ 1,
++ "missing ownership/listing index {index}",
++ );
++ }
++ }
}
diff --cc crates/ai-memory-store/src/ops.rs
index 537a747e,f652d824..58ff8419
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@@ -7,9 -7,8 +7,9 @@@
use std::collections::BTreeSet;
use ai_memory_core::{
-- AgentKind, EntityId, HandoffId, LinkTarget, NewHandoff, NewObservation, NewPage, NewSession,
- ObservationId, ObservationKind, OwnerFilter, PageId, PagePath, ProjectId, SessionId,
- WorkspaceId,
- ObservationId, ObservationKind, PageId, PagePath, ProjectId, SessionId, WorkspaceId,
++ AgentKind, EntityId, HandoffId, IdentityKey, LinkTarget, NewHandoff, NewObservation, NewPage,
++ NewSession, ObservationId, ObservationKind, OwnerFilter, PageId, PagePath, ProjectId,
++ SessionId, WorkspaceId,
};
/// Summary returned by [`reorg_sessions`] and exposed via
@@@ -852,6 -851,6 +852,7 @@@ fn refresh_incoming_links_for_path
/// Begin (or re-affirm) a session row keyed on the caller-supplied id.
/// Idempotent: a second call with the same id leaves the row untouched.
pub fn begin_session(conn: &mut Connection, session: &NewSession) -> StoreResult<()> {
++ validate_identity_storage_key(session.actor_user.as_deref(), "session owner")?;
let now = Timestamp::now().as_microsecond();
let agent = session.agent_kind.as_str();
let cwd: Option<String> = session
@@@ -1393,14 -1390,14 +1394,14 @@@ pub fn end_session_with_handoff
));
}
let tx = conn.transaction()?;
-- let session_scope: Option<(Vec<u8>, Vec<u8>)> = tx
++ let session_scope: Option<(Vec<u8>, Vec<u8>, Option<String>)> = tx
.query_row(
-- "SELECT workspace_id, project_id FROM sessions WHERE id = ?1",
++ "SELECT workspace_id, project_id, actor_user FROM sessions WHERE id = ?1",
params![session_id.as_bytes()],
-- |row| Ok((row.get(0)?, row.get(1)?)),
++ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
)
.optional()?;
-- let Some((workspace_id, project_id)) = session_scope else {
++ let Some((workspace_id, project_id, actor_user)) = session_scope else {
return Err(StoreError::InvalidState(
"cannot end a missing session with an automatic handoff".into(),
));
@@@ -1412,6 -1409,6 +1413,11 @@@
"automatic handoff scope does not match the ended session".into(),
));
}
++ if actor_user != handoff.owner_user {
++ return Err(StoreError::InvalidState(
++ "automatic handoff owner does not match the ended session".into(),
++ ));
++ }
end_session_row(&tx, session_id, summary_page_id)?;
let id = insert_handoff_row(&tx, handoff)?;
tx.commit()?;
@@@ -1419,6 -1416,6 +1425,7 @@@
}
fn insert_handoff_row(conn: &Transaction<'_>, h: &NewHandoff) -> StoreResult<HandoffId> {
++ validate_identity_storage_key(h.owner_user.as_deref(), "handoff owner")?;
let id = HandoffId::new();
let now = Timestamp::now().as_microsecond();
let open_q = serde_json::to_string(&h.open_questions)?;
@@@ -1512,59 -1497,46 +1519,37 @@@
Ok(id)
}
--/// A handoff's `(workspace_id, project_id)` as raw 16-byte ids, for tagging
--/// its audit rows. Either component is `None` when the handoff row is absent.
--type HandoffScope = (Option<[u8; 16]>, Option<[u8; 16]>);
--
--/// The `(workspace_id, project_id)` a handoff belongs to, for tagging its
--/// audit rows. `(None, None)` when the handoff row is absent.
--fn handoff_scope(
-- tx: &rusqlite::Transaction<'_>,
-- handoff_id: &HandoffId,
--) -> StoreResult<HandoffScope> {
-- let row = tx
-- .query_row(
-- "SELECT workspace_id, project_id FROM handoffs WHERE id = ?1",
-- params![handoff_id.as_bytes()],
-- |r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, Vec<u8>>(1)?)),
-- )
-- .optional()?;
-- Ok(match row {
-- Some((ws, proj)) => (
-- <[u8; 16]>::try_from(ws.as_slice()).ok(),
-- <[u8; 16]>::try_from(proj.as_slice()).ok(),
-- ),
-- None => (None, None),
-- })
--}
--
/// 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,
++ workspace_id: &WorkspaceId,
++ project_id: &ProjectId,
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,
++ workspace_id,
++ project_id,
accepting_agent,
accepting_session,
+ accepting_user,
+ owner_filter,
receiving_cwd,
)?;
tx.commit()?;
@@@ -1574,75 -1546,46 +1559,108 @@@
pub(crate) fn accept_handoff_in_transaction(
tx: &Transaction<'_>,
handoff_id: &HandoffId,
++ workspace_id: &WorkspaceId,
++ project_id: &ProjectId,
accepting_agent: AgentKind,
accepting_session: Option<&SessionId>,
+ accepting_user: Option<&str>,
+ owner_filter: &OwnerFilter,
receiving_cwd: Option<&str>,
) -> StoreResult<bool> {
++ validate_identity_storage_key(accepting_user, "accepting handoff operator")?;
++ match (owner_filter, accepting_user) {
++ (OwnerFilter::User(expected), Some(actual)) if expected != actual => {
++ return Err(StoreError::InvalidState(
++ "accepting handoff operator does not match its owner filter".into(),
++ ));
++ }
++ (OwnerFilter::User(_), None) => {
++ return Err(StoreError::InvalidState(
++ "an owner-scoped handoff claim requires an accepting operator".into(),
++ ));
++ }
++ (OwnerFilter::Unattributed, Some(_)) => {
++ return Err(StoreError::InvalidState(
++ "an unattributed handoff claim cannot record a named operator".into(),
++ ));
++ }
++ _ => {}
++ }
let now = Timestamp::now().as_microsecond();
let agent = accepting_agent.as_str();
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, \
- owner_user \
- "SELECT workspace_id, project_id, from_session_id IS NOT NULL, cwd, created_at \
-- FROM handoffs WHERE id = ?1 AND state = 'open'",
-- params![handoff_id.as_bytes()],
++ "SELECT from_session_id IS NOT NULL, cwd, created_at, owner_user \
++ FROM handoffs \
++ WHERE id = ?1 AND workspace_id = ?2 AND project_id = ?3 AND state = 'open'",
++ params![
++ handoff_id.as_bytes(),
++ workspace_id.as_bytes(),
++ project_id.as_bytes(),
++ ],
|row| {
Ok((
-- row.get::<_, Vec<u8>>(0)?,
-- row.get::<_, Vec<u8>>(1)?,
-- row.get::<_, bool>(2)?,
++ row.get::<_, bool>(0)?,
++ row.get::<_, Option<String>>(1)?,
++ row.get::<_, i64>(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, owner_user)) = metadata else {
- let Some((workspace_id, project_id, automatic, cwd, created_at)) = metadata else {
++ let Some((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::User(_) => " AND (owner_user IS NULL OR owner_user = ?8)",
+ 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, accepted_by_user = ?5 \
- WHERE id = ?4 AND state = 'open'{owner_clause}"
- 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 = ?4 \
++ WHERE id = ?5 AND workspace_id = ?6 AND project_id = ?7 \
++ 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,
++ handoff_id.as_bytes(),
++ workspace_id.as_bytes(),
++ project_id.as_bytes(),
+ user
+ ],
+ )?,
+ _ => tx.execute(
+ &sql,
- params![agent, now, session, handoff_id.as_bytes(), accepting_user],
++ params![
++ agent,
++ now,
++ session,
++ accepting_user,
++ handoff_id.as_bytes(),
++ workspace_id.as_bytes(),
++ project_id.as_bytes(),
++ ],
+ )?,
+ };
// Only a real state transition ('open' -> 'accepted') is audited.
if changed > 0 {
audit(
tx,
"accept_handoff",
-- ws.as_ref(),
-- proj.as_ref(),
++ Some(workspace_id.as_bytes()),
++ Some(project_id.as_bytes()),
None,
None,
now,
@@@ -1656,8 -1594,8 +1674,8 @@@
let expired = expire_superseded_auto_handoffs(
tx,
handoff_id,
-- &workspace_id,
-- &project_id,
++ workspace_id.as_bytes(),
++ project_id.as_bytes(),
cwd.as_deref(),
created_at,
receiving_cwd,
@@@ -1667,8 -1604,8 +1685,8 @@@
audit(
tx,
"expire_superseded_handoffs",
-- ws.as_ref(),
-- proj.as_ref(),
++ Some(workspace_id.as_bytes()),
++ Some(project_id.as_bytes()),
None,
None,
now,
@@@ -1679,14 -1616,9 +1697,23 @@@
Ok(changed > 0)
}
++fn validate_identity_storage_key(value: Option<&str>, label: &str) -> StoreResult<()> {
++ if value.is_some_and(|value| IdentityKey::from_storage_key(value).is_none()) {
++ return Err(StoreError::InvalidState(format!(
++ "{label} is not a qualified identity storage key"
++ )));
++ }
++ Ok(())
++}
++
/// 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,
@@@ -1747,35 -1677,20 +1774,53 @@@
}
/// 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,
++ workspace_id: &WorkspaceId,
++ project_id: &ProjectId,
+ 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::User(_) => " AND (owner_user IS NULL OR owner_user = ?4)",
+ OwnerFilter::Unattributed => " AND owner_user IS NULL",
+ };
+ let sql = format!(
- "UPDATE handoffs SET state = 'expired' WHERE id = ?1 AND state = 'open'{owner_clause}"
++ "UPDATE handoffs SET state = 'expired' \
++ WHERE id = ?1 AND workspace_id = ?2 AND project_id = ?3 \
++ 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()])?,
++ OwnerFilter::User(user) => tx.execute(
++ &sql,
++ params![
++ handoff_id.as_bytes(),
++ workspace_id.as_bytes(),
++ project_id.as_bytes(),
++ user,
++ ],
++ )?,
++ _ => tx.execute(
++ &sql,
++ params![
++ handoff_id.as_bytes(),
++ workspace_id.as_bytes(),
++ project_id.as_bytes(),
++ ],
++ )?,
+ };
if changed > 0 {
audit(
&tx,
"cancel_handoff",
-- ws.as_ref(),
-- proj.as_ref(),
++ Some(workspace_id.as_bytes()),
++ Some(project_id.as_bytes()),
None,
None,
now,
@@@ -3312,16 -3225,7 +3357,18 @@@ 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,
++ &ws,
++ &proj,
+ 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",
@@@ -3336,15 -3240,7 +3383,17 @@@
// 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,
++ &ws,
++ &proj,
+ AgentKind::Codex,
+ None,
+ None,
+ &OwnerFilter::Any,
+ None,
+ );
assert!(second.is_ok(), "double-accept must not error");
}
@@@ -3417,21 -3311,11 +3466,23 @@@
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,
++ &ws,
++ &proj,
+ AgentKind::Codex,
+ None,
+ None,
+ &OwnerFilter::Any,
+ None,
+ )
+ .unwrap();
let id2 = insert_handoff(&mut conn, &new()).unwrap();
- assert!(cancel_handoff(&mut conn, &id2, &OwnerFilter::Any).unwrap());
- assert!(cancel_handoff(&mut conn, &id2).unwrap());
++ assert!(cancel_handoff(&mut conn, &id2, &ws, &proj, &OwnerFilter::Any).unwrap());
for op in ["insert_handoff", "accept_handoff", "cancel_handoff"] {
let (count, author) = audit_row_for(&conn, op);
@@@ -3445,17 -3329,8 +3496,19 @@@
);
// 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,
++ &ws,
++ &proj,
+ AgentKind::Codex,
+ None,
+ None,
+ &OwnerFilter::Any,
+ None,
+ )
+ .unwrap();
- assert!(!cancel_handoff(&mut conn, &id, &OwnerFilter::Any).unwrap());
++ assert!(!cancel_handoff(&mut conn, &id, &ws, &proj, &OwnerFilter::Any).unwrap());
assert_eq!(
audit_row_for(&conn, "accept_handoff").0,
1,
@@@ -3552,7 -3424,7 +3605,7 @@@
};
let id = insert_handoff(&mut conn, &new).unwrap();
- assert!(cancel_handoff(&mut conn, &id, &OwnerFilter::Any).unwrap());
- assert!(cancel_handoff(&mut conn, &id).unwrap());
++ assert!(cancel_handoff(&mut conn, &id, &ws, &proj, &OwnerFilter::Any).unwrap());
let state: String = conn
.query_row(
"SELECT state FROM handoffs WHERE id = ?1",
@@@ -3563,7 -3435,7 +3616,7 @@@
assert_eq!(state, "expired");
assert!(
- !cancel_handoff(&mut conn, &id, &OwnerFilter::Any).unwrap(),
- !cancel_handoff(&mut conn, &id).unwrap(),
++ !cancel_handoff(&mut conn, &id, &ws, &proj, &OwnerFilter::Any).unwrap(),
"double-cancel should be a no-op"
);
}
diff --cc crates/ai-memory-store/src/reader.rs
index ff7843ee,af1bb5ed..91d1852a
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@@ -12,8 -12,8 +12,8 @@@ use std::sync::Arc
use ai_memory_core::{
AgentKind, AutoImproveProposalId, AutoImproveRunId, Handoff, HandoffId, HandoffState,
- ManagedRunId, Observation, ObservationId, ObservationKind, OwnerFilter, PageId, PagePath,
- ProjectId, SessionId, User, UserId, WorkspaceId, WorkstreamEvent, WorkstreamId,
- ManagedRunId, Observation, ObservationId, ObservationKind, PageId, PagePath, ProjectId,
- SessionId, User, UserId, WorkspaceId, WorkstreamEvent, WorkstreamId,
++ IdentityKey, ManagedRunId, Observation, ObservationId, ObservationKind, OwnerFilter, PageId,
++ PagePath, ProjectId, SessionId, User, UserId, WorkspaceId, WorkstreamEvent, WorkstreamId,
};
use jiff::Timestamp;
use parking_lot::Mutex;
@@@ -2966,22 -2924,20 +2966,29 @@@ 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(
++ // Ownership belongs in the query, not just in
++ // `is_handoff_candidate`: prompt-derived fields from another
++ // operator must never be loaded or deserialized for this caller.
++ let (owner_clause, owner_param) = handoff_owner_sql(&owner_filter, 3);
++ 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 \
+ 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",
-- )?;
-- let rows = stmt.query_map(
-- params![workspace_id.as_bytes(), project_id.as_bytes()],
-- row_to_handoff,
-- )?;
++ WHERE workspace_id = ?1 AND project_id = ?2 AND state = 'open'{owner_clause} \
++ ORDER BY created_at DESC"
++ );
++ 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(owner) = owner_param.as_ref() {
++ binds.push(owner);
++ }
++ let rows = stmt.query_map(binds.as_slice(), row_to_handoff)?;
let mut selected: Option<Handoff> = None;
for r in rows {
let handoff = r??;
@@@ -2998,71 -2954,6 +3005,51 @@@
.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 (sql, owner_param) = handoff_listing_sql(state.is_some(), &owner_filter, 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
@@@ -3085,6 -2975,6 +3072,49 @@@
.await
}
++ /// Look up a handoff by id within an exact scope and ownership boundary.
++ ///
++ /// This is the object-authorization form used by exact-id operations. The
++ /// scope and owner predicates run before prompt-derived columns are loaded,
++ /// so callers cannot distinguish a foreign id from an absent one or inspect
++ /// another operator's malformed/private row as a side effect of checking it.
++ ///
++ /// # Errors
++ /// Propagates any SQL or pool error.
++ pub async fn handoff_by_id_in_scope(
++ &self,
++ workspace_id: WorkspaceId,
++ project_id: ProjectId,
++ handoff_id: HandoffId,
++ owner_filter: OwnerFilter,
++ ) -> StoreResult<Option<Handoff>> {
++ self.with_conn(move |conn| {
++ let (owner_clause, owner_param) = handoff_owner_sql(&owner_filter, 4);
++ 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 AND id = ?3{owner_clause}"
++ );
++ let mut stmt = conn.prepare(&sql)?;
++ let mut binds: Vec<&dyn rusqlite::ToSql> = vec![
++ workspace_id.as_bytes(),
++ project_id.as_bytes(),
++ handoff_id.as_bytes(),
++ ];
++ if let Some(owner) = owner_param.as_ref() {
++ binds.push(owner);
++ }
++ let row = stmt
++ .query_row(binds.as_slice(), row_to_handoff)
++ .optional()?;
++ row.transpose()
++ })
++ .await
++ }
++
/// Snapshot the database to `dest_path` using SQLite's online backup
/// API. The source DB stays writable for the duration of the copy.
///
@@@ -5538,6 -5382,6 +5568,56 @@@
}
}
++/// Build the bounded history query and its optional owner binding.
++///
++/// A named operator reads two disjoint ranges: shared (`NULL`) and their own
++/// owner key. Expressing those ranges as `OR` makes SQLite prefer the
++/// project-wide timestamp index to satisfy `ORDER BY`, scanning other users'
++/// history until it finds enough visible rows. `UNION ALL` lets SQLite merge
++/// two already ordered owner-index ranges and stop at the requested limit.
++fn handoff_listing_sql(
++ has_state: bool,
++ owner_filter: &OwnerFilter,
++ limit: usize,
++) -> (String, Option<String>) {
++ const SELECT: &str = "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";
++ let state_clause = if has_state { " AND state = ?3" } else { "" };
++ let owner_index = if has_state { 4 } else { 3 };
++ let sql_limit = limit.clamp(1, 500);
++ match owner_filter {
++ OwnerFilter::User(owner) => (
++ format!(
++ "{SELECT} \
++ WHERE workspace_id = ?1 AND project_id = ?2{state_clause} \
++ AND owner_user IS NULL \
++ UNION ALL \
++ {SELECT} \
++ WHERE workspace_id = ?1 AND project_id = ?2{state_clause} \
++ AND owner_user = ?{owner_index} \
++ ORDER BY created_at DESC \
++ LIMIT {sql_limit}"
++ ),
++ Some(owner.clone()),
++ ),
++ _ => {
++ let (owner_clause, owner_param) = handoff_owner_sql(owner_filter, owner_index);
++ (
++ format!(
++ "{SELECT} \
++ WHERE workspace_id = ?1 AND project_id = ?2{state_clause}{owner_clause} \
++ ORDER BY created_at DESC \
++ LIMIT {sql_limit}"
++ ),
++ owner_param,
++ )
++ }
++ }
++}
++
/// Map a `(workspace, project, path, title, kind)` row to a [`HealthPage`].
fn health_page_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<HealthPage> {
Ok(HealthPage {
@@@ -6112,53 -5916,85 +6192,63 @@@ fn row_to_handoff(row: &rusqlite::Row<'
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((|| {
++ for (label, value) in [
++ ("handoff owner", owner_user.as_deref()),
++ ("accepting handoff operator", accepted_by_user.as_deref()),
++ ] {
++ if value.is_some_and(|value| IdentityKey::from_storage_key(value).is_none()) {
++ return Err(StoreError::MalformedRecord(format!(
++ "{label} is not a qualified identity storage key"
++ )));
++ }
++ }
+ 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 {
@@@ -6399,14 -6225,14 +6489,41 @@@ fn open_read_only(path: &Path) -> Store
#[cfg(test)]
mod tests {
-- use super::{entity_query_tokens, like_escape};
++ use super::{entity_query_tokens, handoff_listing_sql, like_escape};
use crate::Store;
use ai_memory_core::{
-- AgentKind, Handoff, HandoffId, HandoffState, NewHandoff, NewSession, ProjectId, SessionId,
-- WorkspaceId,
++ AgentKind, Handoff, HandoffId, HandoffState, NewHandoff, NewSession, OwnerFilter,
++ ProjectId, SessionId, WorkspaceId,
};
++ #[test]
++ fn named_handoff_listing_uses_owner_index_for_both_ranges() {
++ let tmp = tempfile::TempDir::new().unwrap();
++ let store = Store::open(tmp.path()).unwrap();
++ let conn = rusqlite::Connection::open(store.db_path()).unwrap();
++ let ws = WorkspaceId::new();
++ let proj = ProjectId::new();
++ let (sql, owner) = handoff_listing_sql(false, &OwnerFilter::User("user:alice".into()), 50);
++ let mut stmt = conn.prepare(&format!("EXPLAIN QUERY PLAN {sql}")).unwrap();
++ let details = stmt
++ .query_map(
++ rusqlite::params![ws.as_bytes(), proj.as_bytes(), owner.unwrap()],
++ |row| row.get::<_, String>(3),
++ )
++ .unwrap()
++ .collect::<Result<Vec<_>, _>>()
++ .unwrap();
++ assert_eq!(
++ details
++ .iter()
++ .filter(|detail| detail.contains("idx_handoffs_project_owner_recent"))
++ .count(),
++ 2,
++ "shared and owned ranges must both use the owner index: {details:?}"
++ );
++ }
++
#[test]
fn authority_candidate_window_is_bounded_and_saturating() {
use super::authority_candidate_limit;
@@@ -6785,10 -6594,8 +6902,12 @@@
.writer
.accept_handoff(
selected.id,
++ ws,
++ proj,
AgentKind::Codex,
None,
+ None,
+ ai_memory_core::OwnerFilter::Any,
Some("/repo/api/src".into()),
)
.await
diff --cc crates/ai-memory-store/src/writer.rs
index 4a9695c9,6111c0be..dd11896e
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@@ -164,16 -163,13 +164,20 @@@ pub(crate) enum WriteCmd
},
AcceptHandoff {
handoff_id: HandoffId,
++ workspace_id: WorkspaceId,
++ project_id: ProjectId,
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,
++ workspace_id: WorkspaceId,
++ project_id: ProjectId,
+ owner_filter: OwnerFilter,
reply: oneshot::Sender<StoreResult<bool>>,
},
/// Retro-fit sessions + observations to per-cwd projects and graveyard
@@@ -368,10 -364,8 +372,12 @@@
},
AcceptStartupContext {
handoff_id: Option<HandoffId>,
++ workspace_id: WorkspaceId,
++ project_id: ProjectId,
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>>,
@@@ -757,30 -751,20 +763,34 @@@ 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.
++ /// row was already taken, does not belong to the expected workspace and
++ /// project, or its owner does not admit this caller. The body must not reach
++ /// the agent on `false`. `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(
&self,
handoff_id: HandoffId,
++ workspace_id: WorkspaceId,
++ project_id: ProjectId,
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,
++ workspace_id,
++ project_id,
accepting_agent,
accepting_session,
+ accepting_user,
+ owner_filter,
receiving_cwd,
reply: tx,
})
@@@ -791,19 -775,14 +801,24 @@@
/// Mark an open handoff expired so it will no longer be consumed.
///
/// Returns `true` when an open handoff was changed, `false` when the id was
-- /// already accepted/expired or missing.
++ /// already accepted/expired, outside the expected workspace and project,
++ /// or missing.
///
/// # 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,
++ workspace_id: WorkspaceId,
++ project_id: ProjectId,
+ owner_filter: OwnerFilter,
+ ) -> StoreResult<bool> {
let (tx, rx) = oneshot::channel();
self.send(WriteCmd::CancelHandoff {
handoff_id,
++ workspace_id,
++ project_id,
+ owner_filter,
reply: tx,
})
.await?;
@@@ -1465,20 -1443,16 +1480,24 @@@
pub async fn accept_startup_context(
&self,
handoff_id: Option<HandoffId>,
++ workspace_id: WorkspaceId,
++ project_id: ProjectId,
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> {
let (tx, rx) = oneshot::channel();
self.send(WriteCmd::AcceptStartupContext {
handoff_id,
++ workspace_id,
++ project_id,
accepting_agent,
accepting_session,
+ accepting_user,
+ owner_filter,
managed_run_id,
receiving_cwd,
reply: tx,
@@@ -1727,30 -1701,22 +1746,42 @@@ fn worker_loop(mut conn: Connection, mu
}
WriteCmd::AcceptHandoff {
handoff_id,
++ workspace_id,
++ project_id,
accepting_agent,
accepting_session,
+ accepting_user,
+ owner_filter,
receiving_cwd,
reply,
} => {
let result = ops::accept_handoff(
&mut conn,
&handoff_id,
++ &workspace_id,
++ &project_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,
++ workspace_id,
++ project_id,
+ owner_filter,
+ reply,
+ } => {
- let result = ops::cancel_handoff(&mut conn, &handoff_id, &owner_filter);
++ let result = ops::cancel_handoff(
++ &mut conn,
++ &handoff_id,
++ &workspace_id,
++ &project_id,
++ &owner_filter,
++ );
send_or_warn(reply, result, "cancel_handoff");
}
WriteCmd::Reorg {
@@@ -2029,10 -1995,8 +2060,12 @@@
}
WriteCmd::AcceptStartupContext {
handoff_id,
++ workspace_id,
++ project_id,
accepting_agent,
accepting_session,
+ accepting_user,
+ owner_filter,
managed_run_id,
receiving_cwd,
reply,
@@@ -2052,10 -2016,8 +2085,12 @@@
Some(handoff_id) => ops::accept_handoff_in_transaction(
&tx,
&handoff_id,
++ &workspace_id,
++ &project_id,
accepting_agent,
accepting_session.as_ref(),
+ accepting_user.as_deref(),
+ &owner_filter,
receiving_cwd.as_deref(),
)?,
None => false,
diff --cc crates/ai-memory-store/tests/handoff_ownership.rs
index 21c00d88,00000000..522d48a9
mode 100644,000000..100644
--- a/crates/ai-memory-store/tests/handoff_ownership.rs
+++ b/crates/ai-memory-store/tests/handoff_ownership.rs
@@@ -1,731 -1,0 +1,934 @@@
+//! 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
++//! (`user:alice`, `oidc:…`), 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 SQL query must exclude foreign rows before it deserializes any of their
++/// prompt-derived fields. Besides avoiding unnecessary exposure and work, this
++/// means corruption in Bob's private row cannot deny Alice access to her own
++/// valid baton.
++#[tokio::test]
++async fn latest_lookup_filters_foreign_rows_before_deserialization() {
++ 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, "alice's valid baton", Some("alice")))
++ .await
++ .unwrap();
++ let bob = store
++ .writer
++ .insert_handoff(handoff(ws, proj, "bob's private baton", Some("bob")))
++ .await
++ .unwrap();
++
++ // Simulate a corrupt row without routing invalid JSON through the typed
++ // writer. With post-fetch filtering this row is deserialized first and the
++ // whole lookup fails, even though Alice is not authorized to read it.
++ let conn = rusqlite::Connection::open(tmp.path().join("db/memory.sqlite")).unwrap();
++ conn.execute(
++ "UPDATE handoffs SET open_questions = '{' WHERE id = ?1",
++ rusqlite::params![bob.as_bytes()],
++ )
++ .unwrap();
++ drop(conn);
++
++ let alice = store
++ .reader
++ .latest_open_handoff(ws, proj, None, filter_for("alice"))
++ .await
++ .expect("a foreign corrupt row must not affect Alice's lookup")
++ .expect("Alice keeps her valid baton");
++ assert_eq!(alice.summary, "alice's valid baton");
++}
++
++#[tokio::test]
++async fn ownership_writes_reject_malformed_identity_keys() {
++ let tmp = tempfile::tempdir().unwrap();
++ let store = Store::open(tmp.path()).unwrap();
++ let (ws, proj) = scope(&store).await;
++ let invalid_session = ai_memory_core::SessionId::new();
++ assert!(
++ store
++ .writer
++ .begin_session(ai_memory_core::NewSession {
++ id: invalid_session,
++ workspace_id: ws,
++ project_id: proj,
++ agent_kind: AgentKind::ClaudeCode,
++ cwd: None,
++ actor_user: Some("alice".into()),
++ })
++ .await
++ .is_err()
++ );
++ let mut invalid_handoff = handoff(ws, proj, "invalid", None);
++ invalid_handoff.owner_user = Some("user: ".into());
++ assert!(store.writer.insert_handoff(invalid_handoff).await.is_err());
++
++ let id = store
++ .writer
++ .insert_handoff(handoff(ws, proj, "valid", Some("alice")))
++ .await
++ .unwrap();
++ assert!(
++ store
++ .writer
++ .accept_handoff(
++ id,
++ ws,
++ proj,
++ AgentKind::ClaudeCode,
++ None,
++ Some("alice".into()),
++ filter_for("alice"),
++ None,
++ )
++ .await
++ .is_err()
++ );
++ assert!(
++ store
++ .writer
++ .accept_handoff(
++ id,
++ ws,
++ proj,
++ AgentKind::ClaudeCode,
++ None,
++ Some(operator("bob")),
++ filter_for("alice"),
++ None,
++ )
++ .await
++ .is_err(),
++ "the accepting identity and owner filter must not disagree"
++ );
++ assert_eq!(
++ store.reader.handoff_by_id(id).await.unwrap().unwrap().state,
++ ai_memory_core::HandoffState::Open
++ );
++
++ let conn = rusqlite::Connection::open(store.db_path()).unwrap();
++ conn.execute(
++ "UPDATE handoffs SET owner_user = 'user: ' WHERE id = ?1",
++ rusqlite::params![id.as_bytes()],
++ )
++ .unwrap();
++ drop(conn);
++ assert!(
++ store.reader.handoff_by_id(id).await.is_err(),
++ "raw database corruption must not materialize an invalid owner"
++ );
++}
++
+/// 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 by_subject = IdentityKey::Subject {
++ issuer: "https://idp.example".into(),
++ 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"
++ "user:alice must not receive the OIDC-owned baton"
+ );
+ // The subject-identified caller — the filter the auth layer builds for an
- // ingress that forwards only the `sub` claim.
++ // ingress that forwards the complete issuer/subject pair.
+ let sub_filter = OwnerFilter::for_actor_context(&ActorContext {
++ issuer: Some("https://idp.example".into()),
+ 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,
++ ws,
++ proj,
+ 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,
++ ws,
++ proj,
+ 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,
++ ws,
++ proj,
+ 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"))
++ .cancel_handoff(id, ws, proj, filter_for("bob"))
+ .await
+ .unwrap(),
+ "Bob must not cancel Alice's handoff"
+ );
+ assert!(
+ store
+ .writer
- .cancel_handoff(id, filter_for("alice"))
++ .cancel_handoff(id, ws, proj, filter_for("alice"))
+ .await
+ .unwrap(),
+ "the owner can cancel her own"
+ );
+}
+
++/// Destructive operations must recheck the resolved scope in the same UPDATE
++/// that changes state. A preceding scoped read is not sufficient because a
++/// concurrent lifecycle operation could move the project between that read and
++/// the writer command.
++#[tokio::test]
++async fn destructive_handoff_updates_recheck_scope_atomically() {
++ let tmp = tempfile::tempdir().unwrap();
++ let store = Store::open(tmp.path()).unwrap();
++ let (ws, proj) = scope(&store).await;
++ let other_proj = store
++ .writer
++ .get_or_create_project(ws, "other-app".to_string(), None)
++ .await
++ .unwrap();
++ let id = store
++ .writer
++ .insert_handoff(handoff(ws, proj, "scoped baton", Some("alice")))
++ .await
++ .unwrap();
++
++ assert!(
++ !store
++ .writer
++ .accept_handoff(
++ id,
++ ws,
++ other_proj,
++ AgentKind::ClaudeCode,
++ None,
++ Some(operator("alice")),
++ OwnerFilter::Any,
++ None,
++ )
++ .await
++ .unwrap(),
++ "even a root recovery claim must not cross its resolved project"
++ );
++ assert!(
++ !store
++ .writer
++ .cancel_handoff(id, ws, other_proj, OwnerFilter::Any)
++ .await
++ .unwrap(),
++ "even a root recovery cancel must not cross its resolved project"
++ );
++ assert_eq!(
++ store.reader.handoff_by_id(id).await.unwrap().unwrap().state,
++ ai_memory_core::HandoffState::Open
++ );
++ assert!(
++ store
++ .writer
++ .accept_handoff(
++ id,
++ ws,
++ proj,
++ AgentKind::ClaudeCode,
++ None,
++ Some(operator("alice")),
++ OwnerFilter::Any,
++ None,
++ )
++ .await
++ .unwrap(),
++ "the exact project can still claim the handoff"
++ );
++}
++
+/// 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,
++ ws,
++ proj,
+ 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
++/// follows the `oidc:` prefix includes the OIDC identity a trusted proxy
++/// asserted. 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,
++ ws,
++ proj,
+ 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 --cc crates/ai-memory-web/src/routes/api.rs
index 8b14e18d,d0421db5..d0b4e012
--- a/crates/ai-memory-web/src/routes/api.rs
+++ b/crates/ai-memory-web/src/routes/api.rs
@@@ -77,6 -73,6 +77,21 @@@ fn with_cache(resp: Response, max_age:
resp
}
++/// Prevent browser reuse of a response whose body depends on request identity.
++///
++/// `private` alone still permits a browser cache to serve Alice's response
++/// after credentials at the same URL switch to Bob. These endpoints contain
++/// owner-scoped prompt text, so successful responses must be revalidated by
++/// executing the authorization/filtering path on every request.
++fn with_no_store(resp: Response) -> Response {
++ let mut resp = resp;
++ resp.headers_mut().insert(
++ header::CACHE_CONTROL,
++ HeaderValue::from_static("private, no-store"),
++ );
++ resp
++}
++
async fn workspaces_handler(State(state): State<Arc<WebState>>) -> Result<Response, Response> {
let workspaces = state
.reader
@@@ -425,18 -420,13 +440,15 @@@ async fn briefing_handler
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(
-- Json(briefing).into_response(),
-- LIST_CACHE_MAX_AGE,
-- ))
++ Ok(with_no_store(Json(briefing).into_response()))
}
async fn overview_handler(
@@@ -513,221 -493,14 +525,241 @@@
orphan_pages: detail.orphans,
};
-- Ok(with_cache(
++ Ok(with_no_store(
Json(ApiOverview {
handoff,
briefing,
health,
})
.into_response(),
-- LIST_CACHE_MAX_AGE,
+ ))
+}
+
+/// 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
++/// `actor.user`: an ingress that forwards a complete OIDC issuer/subject pair
++/// may leave `user` empty, and reading `user` here would file that 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 —
++/// Three ways to qualify: an authenticated 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.
++/// it is root-only here. The `all_owners` query switch produces it only after
++/// checking the request's resolved [`ai_memory_core::AuthLevel`]. Keeping the
++/// body check local as well prevents a future caller from constructing `Any`
++/// without the matching authorization gate.
+///
+/// # 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.
++/// [`ai_memory_core::AuthLevel::User`] when it asserted a username or a
++/// complete issuer/subject pair. Both are resolved by
++/// [`ai_memory_core::ActorContext::identity_key`], 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::User(_) => {
++ matches!(
++ level,
++ Some(ai_memory_core::AuthLevel::User | ai_memory_core::AuthLevel::Root)
++ )
++ }
+ 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);
++ /// Operator the handoff belongs to (qualified `oidc:`/`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,
++ /// Root-only recovery view across every operator. Omitted/false keeps the
++ /// normal own-plus-shared ownership boundary.
++ #[serde(default)]
++ all_owners: bool,
+}
+
+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 level = auth.as_ref().map(|axum::Extension(level)| *level);
++ let owner_filter = if query.all_owners {
++ if level != Some(ai_memory_core::AuthLevel::Root) {
++ return Err(json_error(
++ StatusCode::FORBIDDEN,
++ "all_owners requires root authorization",
++ ));
++ }
++ ai_memory_core::OwnerFilter::Any
++ } else {
++ 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(
++ Ok(with_no_store(
+ Json(serde_json::json!({ "handoffs": entries })).into_response(),
- LIST_CACHE_MAX_AGE,
))
}
@@@ -784,14 -553,14 +816,13 @@@ async fn project_overview_handler
orphan_pages: detail.orphans,
};
-- Ok(with_cache(
++ Ok(with_no_store(
Json(ApiOverview {
handoff,
briefing,
health,
})
.into_response(),
-- LIST_CACHE_MAX_AGE,
))
}
@@@ -1127,44 -896,3 +1158,57 @@@ 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
++ /// The `all_owners` recovery switch routes `Any` into the listing. 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))
+ ));
+ }
+
++ #[test]
++ fn named_owner_filter_requires_an_authenticated_tier() {
++ let filter = OwnerFilter::User("user:alice".into());
++ for level in [None, Some(AuthLevel::Anonymous)] {
++ assert!(
++ !serves_handoff_body(&filter, level.map(Extension)),
++ "actor identity without a matching authenticated tier served a body"
++ );
++ }
++ for level in [AuthLevel::User, AuthLevel::Root] {
++ assert!(serves_handoff_body(&filter, Some(Extension(level))));
++ }
++ }
++
+ /// 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 --cc crates/ai-memory-web/tests/routes.rs
index 2eb4dbb5,ba6cee7a..699e6080
--- a/crates/ai-memory-web/tests/routes.rs
+++ b/crates/ai-memory-web/tests/routes.rs
@@@ -1345,475 -1343,6 +1345,561 @@@ async fn api_project_overview_aggregate
);
}
+/// 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.
++/// asserts a complete OIDC issuer/subject pair.
+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())
++ ai_memory_core::IdentityKey::Subject {
++ issuer: "https://idp.example".into(),
++ subject: sub.into(),
++ }
+}
+
- /// The sub-only proxy rung, end to end through the browser's own endpoint.
++/// The OIDC proxy rung, end to end through the browser's own endpoint.
+///
- /// An ingress that terminates OIDC and forwards only the subject claim resolves
++/// An ingress that terminates OIDC and forwards the issuer/subject pair 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.
++/// ones — so on an OIDC-proxy 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() {
++async fn api_handoff_listing_serves_an_oidc_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 {
++ issuer: Some("https://idp.example".into()),
+ 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}",
+ );
+}
+
++#[tokio::test]
++async fn api_handoff_all_owners_is_root_only_and_returns_every_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();
++ for (summary, owner) in [
++ ("alice_all_marker", Some(user_key("alice"))),
++ ("bob_all_marker", Some(user_key("bob"))),
++ ("shared_all_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());
++ for (actor, auth) in [
++ (
++ Some(ai_memory_core::ActorContext {
++ user: Some("alice".into()),
++ ..ai_memory_core::ActorContext::default()
++ }),
++ Some(ai_memory_core::AuthLevel::User),
++ ),
++ (None, Some(ai_memory_core::AuthLevel::Anonymous)),
++ ] {
++ let resp = app
++ .clone()
++ .oneshot(api_req_actor(
++ "/workspaces/default/projects/scratch/handoffs?all_owners=true",
++ actor,
++ auth,
++ ))
++ .await
++ .unwrap();
++ assert_eq!(resp.status(), StatusCode::FORBIDDEN);
++ let text = String::from_utf8(
++ axum::body::to_bytes(resp.into_body(), usize::MAX)
++ .await
++ .unwrap()
++ .to_vec(),
++ )
++ .unwrap();
++ assert!(text.contains("all_owners requires root authorization"));
++ assert!(!text.contains("alice_all_marker"));
++ assert!(!text.contains("bob_all_marker"));
++ }
++
++ let resp = app
++ .oneshot(api_req_actor(
++ "/workspaces/default/projects/scratch/handoffs?all_owners=true",
++ None,
++ Some(ai_memory_core::AuthLevel::Root),
++ ))
++ .await
++ .unwrap();
++ assert_eq!(resp.status(), StatusCode::OK);
++ let text = String::from_utf8(
++ axum::body::to_bytes(resp.into_body(), usize::MAX)
++ .await
++ .unwrap()
++ .to_vec(),
++ )
++ .unwrap();
++ for marker in ["alice_all_marker", "bob_all_marker", "shared_all_marker"] {
++ assert!(
++ text.contains(marker),
++ "root listing omitted {marker}: {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;
@@@ -2096,6 -1625,6 +2182,50 @@@ async fn api_responses_set_cache_contro
);
}
++#[tokio::test]
++async fn actor_scoped_api_responses_are_never_reused_across_credentials() {
++ let (_tmp, store, wiki) = setup().await;
++ let ws = store
++ .writer
++ .get_or_create_workspace("default")
++ .await
++ .unwrap();
++ store
++ .writer
++ .get_or_create_project(ws, "scratch", None)
++ .await
++ .unwrap();
++
++ let app = api_router(store.reader.clone(), wiki.clone());
++ for uri in [
++ "/workspaces/default/projects/scratch/briefing",
++ "/workspaces/default/overview",
++ "/workspaces/default/projects/scratch/overview",
++ "/workspaces/default/projects/scratch/handoffs",
++ ] {
++ let resp = app
++ .clone()
++ .oneshot(api_req_actor(
++ uri,
++ Some(ai_memory_core::ActorContext {
++ user: Some("alice".into()),
++ ..ai_memory_core::ActorContext::default()
++ }),
++ Some(ai_memory_core::AuthLevel::User),
++ ))
++ .await
++ .unwrap();
++ assert_eq!(resp.status(), StatusCode::OK, "{uri}");
++ let cache = resp
++ .headers()
++ .get(header::CACHE_CONTROL)
++ .expect("actor-scoped responses need Cache-Control")
++ .to_str()
++ .unwrap();
++ assert_eq!(cache, "private, no-store", "{uri}");
++ }
++}
++
#[tokio::test]
async fn api_page_handler_emits_etag_and_supports_if_none_match() {
let (_tmp, store, wiki) = setup().await;
diff --cc docs/ARCHITECTURE.md
index 8430704b,8430704b..7f0c5716
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@@ -338,9 -338,9 +338,9 @@@ invariants below
| `memory_status` | read-only | Counts, paths, version. |
| `memory_briefing` | read-only | Structured counts/activity/rules/slots/recent snapshot. |
| `memory_explore` | read-only | LLM prose digest over the briefing snapshot, degrading to JSON without a provider. |
--| `memory_handoff_begin` | destructive | Open a handoff for the next agent. Optional `workspace` + `project` targets a named sibling workspace/project. |
--| `memory_handoff_accept` | destructive | Fetch + ack the latest open handoff (auto-cwd-matched by default). Optional `workspace` + `project` targets a named sibling workspace/project. |
--| `memory_handoff_cancel` | destructive | Mark an exact open handoff id expired when it was created by mistake. |
++| `memory_handoff_begin` | destructive | Open an owner-scoped handoff for the next agent; `shared=true` deliberately publishes it to the project. Optional `workspace` + `project` targets a named sibling workspace/project. |
++| `memory_handoff_accept` | destructive | Fetch + ack the latest own/shared handoff (automatic handoffs are cwd-matched). Root-only `any_owner=true` recovers across operators. Optional `workspace` + `project` targets a named sibling workspace/project. |
++| `memory_handoff_cancel` | destructive | Mark an exact visible open handoff id expired when it was created by mistake; root-only `any_owner=true` recovers across operators. |
| `memory_consolidate` | destructive | LLM-driven page rewrite. `multi_page=true` for atomic fan-out. Consolidation prompts append the target project's active reserved `_prompts/consolidation.md` body as sanitized, 2,000-character-capped, JSON-encoded, untrusted advisory preferences; TTL-expired pages are ignored and a per-call `instructions` argument overrides the page for one call. Both system prompts keep schema, evidence, disclosure, tool-use, and output rules authoritative. |
| `memory_feedback` | write | Record a quality signal for one page by exact `path`: `helpful`/`not_helpful` step `pages.salience` for sweep-eligible episodic pages, while `stale`/`wrong` floor salience and surface any current page as a `feedback_flagged` lint finding. Never deletes; the path resolves to the current version in the transaction, so a later rewrite clears it. Retrieved content never authorizes feedback by itself. |
| `memory_auto_improve` | write | Manually review a completed session and apply or stage validated wiki edits through the auto-improvement approval path. Defaults to the latest completed session in the resolved current project; the server also schedules review for new sessions; `[auto_improve] require_approval = true` leaves proposals pending for manual review. |
diff --cc docs/admission-webhooks.md
index 35c4b69b,e73d0d0d..eaa5a149
--- a/docs/admission-webhooks.md
+++ b/docs/admission-webhooks.md
@@@ -1,7 -1,7 +1,8 @@@
# Admission webhooks: pre-persistence HTTP hooks
> Operator-configured HTTP hooks invoked on the engine's write path
--> (`Wiki::write_page`, `delete_page`, `purge_project`, `purge_workspace`, `move_project`)
++> (`Wiki::write_page`, `delete_page`, `purge_project`, `purge_workspace`,
++> `move_project`, and handoff lifecycle operations)
> just before the durable mutation commits. Write hooks can mutate the page
> (return a new frontmatter / body); delete/purge/move hooks are notifications
> that can observe, mirror, or reject. Sourced from
@@@ -70,51 -70,6 +71,54 @@@ Webhooks fire on these `op` values toda
`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.
++- The session-start claim is served by the synchronous hook path. The shortest
++ shipped caller is the shell hook's one-second curl deadline (native hook
++ commands allow three seconds), so the server caps admission at 750 ms. A
++ refusal, that server deadline, a per-webhook timeout or an unreachable host
++ leaves the handoff **open** for the next session; it never fails the session
++ start or consumes context after the caller has disconnected.
+
+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.
++That sum is then capped by the server's 750 ms automatic-claim deadline.
++`timeout_ms` still defaults to 2000 ms per webhook for ordinary MCP and write
++paths; on automatic session-start acceptance, a chain that cannot approve
++within 750 ms is treated as a refusal and the baton remains open. Configure
++smaller per-webhook values when you need logs to identify which decider timed
++out rather than the aggregate deadline firing first.
`delete` / `purge_project` / `purge_workspace` / `move_project` are notifications — there is no
body to mutate; a `Reject`-policy webhook still aborts the operation
@@@ -288,7 -234,7 +292,7 @@@ Constants are exported from the `ai-mem
|---|---|---|
| `MAX_ADMISSION_WEBHOOKS` | `16` | Chain length. `AdmissionChain::new` errors out beyond this — a misconfigured template (helm loop, duplicated block) can't push N hooks into the write-path. |
| `MAX_RESPONSE_BYTES` | `1 MiB` | Webhook response body. Beyond this the response is dropped (treated as no-op + `warn`). |
--| Per-webhook `timeout_ms` | operator-set (default `2000`) | Single request. The chain is sequential, so total worst case ≈ `Σ timeout_ms`. |
++| Per-webhook `timeout_ms` | operator-set (default `2000`) | Single request. The chain is sequential, so total worst case ≈ `Σ timeout_ms`; automatic session-start handoff acceptance additionally caps the whole deciding chain at 750 ms. |
## 8. Configuration
diff --cc docs/design-decisions.md
index cd43bb19,cd43bb19..73ff1acf
--- a/docs/design-decisions.md
+++ b/docs/design-decisions.md
@@@ -191,7 -191,7 +191,7 @@@ struct Handoff
}
```
--MCP tools `memory_handoff_begin` (writes a handoff row tagged `state=open`), `memory_handoff_accept` (acknowledges, returns the handoff content, marks `accepted_by`), and `memory_handoff_cancel` (marks an exact open handoff id expired when it was created by mistake). The user can stop Claude Code, start Codex, and Codex's session-start hook fetches the open handoff for the cwd. The cwd is matched by path-boundary (the prior art's check), not exact equality: a handoff left in `/repo` is delivered to a session in `/repo/api`, but never to `/repo-other`. A manual `memory_handoff_begin` handoff is stored with no cwd and so is project-wide, and is preferred over the auto SessionEnd handoff so an explicit "where we left off" baton is never shadowed by the heuristic one. Among cwd-eligible automatic handoffs the newest wins, with cwd specificity only breaking timestamp ties, so stale subdirectory context cannot shadow a newer parent-session handoff. Creating an automatic handoff expires prior open automatic handoffs from the exact cwd. Accepting one atomically expires older automatic candidates eligible for that receiving cwd; manual and sibling-directory handoffs remain open.
++MCP tools `memory_handoff_begin` (writes a handoff row tagged `state=open`), `memory_handoff_accept` (acknowledges, returns the handoff content, marks `accepted_by`), and `memory_handoff_cancel` (marks an exact open handoff id expired when it was created by mistake). The user can stop Claude Code, start Codex, and Codex's session-start hook fetches the open handoff for the cwd. On an operator-distinguishing server, delivery is owner-scoped first: callers see their own plus deliberately shared rows; `shared=true` publishes a manual handoff to the project, while root-only `any_owner=true` is the recovery escape hatch for accept/cancel. The cwd is matched by path-boundary (the prior art's check), not exact equality: a handoff left in `/repo` is delivered to a session in `/repo/api`, but never to `/repo-other`. A manual `memory_handoff_begin` handoff is project-wide by cwd and is preferred over the auto SessionEnd handoff so an explicit "where we left off" baton is never shadowed by the heuristic one. Among cwd-eligible automatic handoffs the newest wins, with cwd specificity only breaking timestamp ties, so stale subdirectory context cannot shadow a newer parent-session handoff. Creating an automatic handoff expires prior open automatic handoffs from the exact cwd and owner. Accepting one atomically expires older automatic candidates eligible for that receiving cwd and carrying the same owner; manual, sibling-directory, and other-owner handoffs remain open.
Handoffs are a next-session transfer rather than live inter-agent messaging.
Antigravity CLI exposes `PreInvocation` instead of SessionStart, and it fires
diff --cc docs/frontend-api.md
index ff35de51,9e3ddcd4..40b8c0de
--- a/docs/frontend-api.md
+++ b/docs/frontend-api.md
@@@ -25,8 -25,8 +25,10 @@@ middleware as `/mcp`, `/hook`, and `/ad
- **Anonymous request → `401 Unauthorized`** (when the server is running
with a bearer token configured).
- **Disallowed `Host` header → `403 Forbidden`** (DNS-rebinding guard).
--- The same token protects everything; there is no per-user scoping.
-- Single-tenant by design (see [`docs/design-decisions.md`](design-decisions.md) §13).
++- The static bearer is the root credential. DB-user tokens and a configured
++ trusted-proxy bearer resolve per-user identities; actor-scoped responses then
++ expose only that operator's plus shared handoffs. See
++ [`docs/users.md`](users.md) for the full auth ladder.
Pass the bearer in the standard header:
@@@ -37,7 -37,7 +39,7 @@@ Authorization: Bearer <token
Get a token:
```bash
--ai-memory generate-auth-token # writes to stdout
++ai-memory generate-auth-token # writes a root token to stdout
# then export AI_MEMORY_AUTH_TOKEN=<token> in the server's environment,
# or put it under [auth].bearer_token in config.toml
```
@@@ -67,7 -67,7 +69,7 @@@ with one of these statuses
|---|---|
| `400 Bad Request` | invalid query params, malformed `Authorization`, partial scope (workspace without project or vice versa), too many scopes in `POST /search` (>25), empty `q`. |
| `401 Unauthorized` | bearer missing or wrong. |
--| `403 Forbidden` | Host header not in allowlist. |
++| `403 Forbidden` | Host header not in allowlist; or a non-root caller requests `all_owners=true`. |
| `404 Not Found` | workspace, project, or page doesn't exist; or page file missing on disk. |
| `500 Internal Server Error` | reader pool / SQLite failure. Body is `{"error":"<context>"}` with the source error chain. |
@@@ -296,57 -296,6 +298,62 @@@ 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
++GET /api/v1/workspaces/{workspace}/projects/{project}/handoffs?all_owners=true
+```
+
+### 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.
++For recovery, a root-authorized request may pass `all_owners=true` to list all
++operators' rows. User and anonymous requests receive `403`; the default remains
++own plus shared, including for root.
+
+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
++(`ActorContext::identity_key()`): the asserted issuer/subject pair when there is
++one, otherwise the username. An ingress that terminates OIDC and forwards both
++`X-Memory-Actor-Issuer` and `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:…`).
++(`user:alice`, `oidc:<issuer-byte-length>:<issuer><subject>`).
+
+```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.
@@@ -438,16 -387,16 +445,19 @@@ the info-leak surface is nil
## 5. Limits and pagination
--- All `limit` query params clamp to `1..=100`.
++- Most `limit` query params clamp to `1..=100`; handoff history clamps to
++ `1..=200`.
- `POST /api/v1/search`: at most **25 scopes** per request.
- HTTP body cap: **10 MB** (shared with the MCP body limit; you won't
hit this for normal API traffic).
--- **Cache-Control + ETag.** Idempotent read endpoints (workspaces,
-- projects, pages list, page read, recent, briefing, overview) send
-- `Cache-Control: private, max-age=N` with an N tuned per endpoint
-- and a SHA-256 `ETag` derived from the response body. Browsers that
-- echo back `If-None-Match` receive a `304 Not Modified` with no body.
-- Search responses are not cacheable (request body affects the result).
++- **Cache-Control + ETag.** Identity-independent read endpoints use
++ `Cache-Control: private, max-age=N` with an endpoint-specific TTL; page reads
++ also carry a SHA-256 `ETag`, and a matching `If-None-Match` receives `304 Not
++ Modified`. Briefing, overview and handoff-list responses depend on the
++ authenticated actor and therefore use `Cache-Control: private, no-store`, so
++ a browser cannot reuse Alice's prompt-derived response after credentials at
++ the same URL switch to Bob. Search responses are not cacheable because the
++ request body affects the result.
## 6. Custom UI hosting and base paths
diff --cc docs/mcp-install.md
index f0da54be,f0da54be..da1a99e4
--- a/docs/mcp-install.md
+++ b/docs/mcp-install.md
@@@ -540,9 -540,9 +540,11 @@@ The rendered hooks config looks like
the conversation. After the final turn, run
`ai-memory finalize-session --agent antigravity-cli` to create the final
summary and automatic handoff and to queue opt-in SessionEnd consolidation.
--- `memory_handoff_begin` always creates an explicit, project-wide manual
-- handoff with no `from_session_id` and `from_agent = other`; that
-- session-neutral shape is the same for every MCP client. Handoffs carrying a
++- `memory_handoff_begin` always creates an explicit manual handoff with no
++ `from_session_id` and `from_agent = other`; it is project-wide for cwd
++ matching but belongs to the creating operator by default. Pass `shared=true`
++ only to publish it to every operator in the project. That session-neutral
++ shape is the same for every MCP client. Handoffs carrying a
Codex or Claude session id came from canonical SessionEnd processing, not
from the manual tool. Use the explicit Antigravity finalizer when the
session itself must end and produce an attributed automatic handoff.
diff --cc docs/usage.md
index 3d40022f,3d40022f..9aeb9a0f
--- a/docs/usage.md
+++ b/docs/usage.md
@@@ -40,6 -40,6 +40,14 @@@ If an agent has MCP but no lifecycle ho
`memory_handoff_begin` before quitting. The next hooked agent can still
consume that handoff automatically.
++On a server that distinguishes operators, handoffs belong to their creator by
++default: the next session for that operator sees their own plus deliberately
++shared rows, never a teammate's. Use `shared: true` on
++`memory_handoff_begin` only when the baton is intended for anyone in the
++project. Root-authorized recovery can pass `any_owner: true` to
++`memory_handoff_accept` or `memory_handoff_cancel`; normal callers cannot use
++that switch.
++
Handoffs are next-session transfer, not a live message bus between agents that
are still running. In particular, Antigravity CLI exposes `PreInvocation`
before every model call; ai-memory fetches a handoff only on invocation zero,
diff --cc docs/users.md
index aba93283,0946f25f..50d06be3
--- a/docs/users.md
+++ b/docs/users.md
@@@ -3,14 -3,15 +3,17 @@@
> **Status:** Introduced in v0.8; this page documents the current shipped
> contract.
--ai-memory is **single-tenant data** with **optional multi-user
++ai-memory is **single-tenant wiki data** with **optional multi-user
attribution**. Every authenticated request sees the same wiki pages —
--there is no per-page RBAC, no per-user data scoping, no group
--permissions. What multi-user mode adds is *who-did-this*: every write
++there is no per-page RBAC or group permission model. Operational handoffs and
++open-session recovery are owner-scoped so one operator cannot accidentally
++consume or finalize another's live context. What multi-user mode also adds is
++*who-did-this*: every write
attributes to a named user, audit-log rows carry that identity, and the
web UI can show "Last edited by Alice Smith" instead of the anonymous
- default. Every `/admin/*` endpoint stays root-only once at least one user
- row exists, including read-only status/search/read-page helpers.
+ default. Every `/admin/*` endpoint stays root-only once the deployment has a
+ DB user or trusted-proxy identities, including read-only
+ status/search/read-page helpers.
If you run ai-memory alone, you can skip this page — your install
keeps working unchanged.
@@@ -99,78 -98,18 +100,70 @@@ root_subject = "<root-subject>
## Identity keys
- Ownership everywhere in the engine is keyed on a *qualified* identity — never
- a bare string. `ActorContext::identity_key()` resolves each request to
- `sub:<subject>` (when the proxy asserts an OIDC subject) or `user:<name>`
- (when only a username was asserted). The two name spaces are disjoint by
- construction: a username equal to somebody else's subject is a different
- identity, in storage and in every admit check.
-
- `sub` outranks `user` because OIDC defines `sub` as the stable,
- non-reassignable identifier and explicitly forbids relying on
- `preferred_username`. Practical consequence: **configure the proxy to forward
- `sub` from day one if the IdP provides it.** An ingress that asserted only
- `sub` and later adds a username keeps the same key; an ingress that asserted
- only a username and later adds `sub` re-buckets that operator once, at the
- moment the stronger identifier appears.
-
- Where an identity becomes a wiki path segment, the raw value is never used —
- subjects are often URLs, and pages are real files on every platform. The
- derivation is `IdentityKey::path_segment()`: values made only of
- `[A-Za-z0-9._-]` pass through readably (`u-alice`, `s-103459784`); anything
- else hex-encodes under a distinct prefix (`sx-…`, `ux-…`) that keeps the
- encoding injective.
+ Identity-sensitive routing uses a *qualified* identity, never a bare string.
+ `ActorContext::identity_key()` resolves a request to the OIDC
+ `(issuer, subject)` pair when both are present, or to `user:<name>` for a
+ username-only identity. The namespaces are disjoint, and identical subjects
+ from different issuers stay different.
+
+ The OIDC pair outranks `user` because OIDC defines `(iss, sub)` as the stable
+ identifier and explicitly forbids relying on `preferred_username` for
+ uniqueness. Configure the proxy to forward both values from day one. Adding a
+ display username later then preserves the same identity; moving from a
+ username-only assertion to the OIDC pair deliberately changes it once.
+## 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
++ `[auth].root_username`: with no `users` rows and no proxy bearer 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
++ `ActorContext::identity_key()`, so the issuer-qualified OIDC key when a
++ complete issuer/subject pair is asserted and `user:<name>` otherwise. It is
++ the same rule that decides the auth tier, so the proxy path 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.
++ unauthenticated. The default listing remains own plus shared; root may request
++ the explicit recovery view with `?all_owners=true`, while user and anonymous
++ tiers receive `403`.
+- 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
++`users` rows exist, or `[auth].actor_proxy_bearer_token` 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: