Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(ownership): agentsession typed owner on create (#7228)
Will Hutchinsonece0b9828f30
diff --git a/.sqlx/query-6042ea8a1c04a936adcc88e1c4cb50a175132ac2a9e6f855354c952258317186.json b/.sqlx/query-6042ea8a1c04a936adcc88e1c4cb50a175132ac2a9e6f855354c952258317186.jsonnew file mode 100644index 0000000000..4fd3cab3ac--- /dev/null+++ b/.sqlx/query-6042ea8a1c04a936adcc88e1c4cb50a175132ac2a9e6f855354c952258317186.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT id FROM \"User\" WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "6042ea8a1c04a936adcc88e1c4cb50a175132ac2a9e6f855354c952258317186"+}diff --git a/.sqlx/query-8ae05c4367968a7f8c1a5ba0836fa52dd52a67f33e14b677d6816695c5da2cb1.json b/.sqlx/query-8ae05c4367968a7f8c1a5ba0836fa52dd52a67f33e14b677d6816695c5da2cb1.jsonnew file mode 100644index 0000000000..5997e6ff01--- /dev/null+++ b/.sqlx/query-8ae05c4367968a7f8c1a5ba0836fa52dd52a67f33e14b677d6816695c5da2cb1.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT count(*) AS \"count!\"\n FROM agent_session\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "8ae05c4367968a7f8c1a5ba0836fa52dd52a67f33e14b677d6816695c5da2cb1"+}diff --git a/.sqlx/query-9ca1e0bb096d08f20783cde4a26d3b4d4ffc2f43e573f0898b76f4acf167a423.json b/.sqlx/query-9ca1e0bb096d08f20783cde4a26d3b4d4ffc2f43e573f0898b76f4acf167a423.jsonnew file mode 100644index 0000000000..e40adbdf8b--- /dev/null+++ b/.sqlx/query-9ca1e0bb096d08f20783cde4a26d3b4d4ffc2f43e573f0898b76f4acf167a423.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT source_type::text AS \"source_type!\", source_id, access_level::text AS \"access_level!\"\n FROM entity_access\n WHERE entity_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "source_type!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "source_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "access_level!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null,+ false,+ null+ ]+ },+ "hash": "9ca1e0bb096d08f20783cde4a26d3b4d4ffc2f43e573f0898b76f4acf167a423"+}diff --git a/.sqlx/query-f06292f93d2ed73cd37308a3dd5fbebbcf68224404eeb093127e8e39b5b24f24.json b/.sqlx/query-f06292f93d2ed73cd37308a3dd5fbebbcf68224404eeb093127e8e39b5b24f24.jsonnew file mode 100644index 0000000000..638604143e--- /dev/null+++ b/.sqlx/query-f06292f93d2ed73cd37308a3dd5fbebbcf68224404eeb093127e8e39b5b24f24.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT count(*) AS \"count!\"\n FROM entity_access\n WHERE entity_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "f06292f93d2ed73cd37308a3dd5fbebbcf68224404eeb093127e8e39b5b24f24"+}diff --git a/Cargo.lock b/Cargo.lockindex 888ac94906..9245b23eb7 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -422,6 +422,8 @@ dependencies = ["database_env_vars","doppler-config","entity_access",+ "entity_registry",+ "entity_registry_db_utils","futures","github","harness_id",@@ -598,6 +600,7 @@ dependencies = ["dashmap","entity_access","entity_access_db_utils",+ "entity_registry","entity_registry_db_utils","genai_telemetry","harness_id",@@ -685,6 +688,8 @@ dependencies = ["crm","database_env_vars","entity_access",+ "entity_registry",+ "entity_registry_db_utils","initiative","kafka_util","lexical_client",@@ -14059,10 +14064,13 @@ dependencies = ["async-trait","aws-sdk-secretsmanager","axum",+ "bots","connection_gateway_client","database_env_vars","doppler-config","entity_access",+ "entity_registry",+ "entity_registry_db_utils","macro_auth","macro_authorization","macro_aws_config",@@ -15966,6 +15974,7 @@ dependencies = ["aws-sdk-s3","aws-sdk-sqs","axum",+ "bots","calendar_events","call","channels",@@ -15978,6 +15987,8 @@ dependencies = ["email","email_db_client","ensure_exists",+ "entity_registry",+ "entity_registry_db_utils","futures","http-body-util","kafka_util",diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.tsindex 5cd2cfa452..974cabf006 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts@@ -60,13 +60,12 @@ a session is a control action instead, and reads as one in itstranscript. */model?: CreateAgentSessionRequestModel;/** The user who owns the session. Ignored for user callers, who always-own their own sessions, and for harness callers, whose verified acting-user (owner or confirmed team member) owns the session instead;-required for bot callers without verified acting-user claims.--For bot callers this is a claim, not a verified fact: it is scoped to-the bot's own sessions, but the named user owns the session on the-bot's say-so. */+own their own sessions, for harness callers, whose verified acting+user owns the session, and for bots that already act for a verified+user. A bot without one may name a user here. That claim is trusted+for the bot's own sessions. With no claim, a team bot owns the session+itself only while non-user owners are enabled. Every other bot still+needs an owner. */owner?: CreateAgentSessionRequestOwner;/** First prompt to deliver once the session is running. Managed sessionsonly - an external runtime sends its own first prompt through thediff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestOwner.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestOwner.tsindex 9a7c2a79a8..8681506b58 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestOwner.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestOwner.ts@@ -7,12 +7,11 @@/*** The user who owns the session. Ignored for user callers, who always-own their own sessions, and for harness callers, whose verified acting-user (owner or confirmed team member) owns the session instead;-required for bot callers without verified acting-user claims.--For bot callers this is a claim, not a verified fact: it is scoped to-the bot's own sessions, but the named user owns the session on the-bot's say-so.+own their own sessions, for harness callers, whose verified acting+user owns the session, and for bots that already act for a verified+user. A bot without one may name a user here. That claim is trusted+for the bot's own sessions. With no claim, a team bot owns the session+itself only while non-user owners are enabled. Every other bot still+needs an owner.*/export type CreateAgentSessionRequestOwner = string | null;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.jsonindex a45a321ced..07293928a5 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json@@ -2577,7 +2577,7 @@},"owner": {"type": ["string", "null"],- "description": "The user who owns the session. Ignored for user callers, who always\nown their own sessions, and for harness callers, whose verified acting\nuser (owner or confirmed team member) owns the session instead;\nrequired for bot callers without verified acting-user claims.\n\nFor bot callers this is a claim, not a verified fact: it is scoped to\nthe bot's own sessions, but the named user owns the session on the\nbot's say-so."+ "description": "The user who owns the session. Ignored for user callers, who always\nown their own sessions, for harness callers, whose verified acting\nuser owns the session, and for bots that already act for a verified\nuser. A bot without one may name a user here. That claim is trusted\nfor the bot's own sessions. With no claim, a team bot owns the session\nitself only while non-user owners are enabled. Every other bot still\nneeds an owner."},"prompt": {"type": ["string", "null"],diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rsindex 442eddf7b6..23e5ff7c4d 100644--- a/crates/agent_harness/src/domain/service/open.rs+++ b/crates/agent_harness/src/domain/service/open.rs@@ -2,6 +2,7 @@//! external runtime that dials in. Each creates the row, provisions egress//! where there is a sandbox to give it to, and attaches the runtime.+use agent_session::domain::model::session_owner_user;use agent_session::domain::ports::SelectedManagedPersona;use agent_session::domain::repository_branch::RepositoryBranch;use model_owner::Owner;@@ -56,15 +57,7 @@ where&self,request: agent_session::domain::ports::OpenExternalAgentSession,) -> agent_session::domain::error::Result<AgentSession> {- // An external session is opened as a person: the thread it claims is- // checked against what they may post in, and the announcement is- // made in their name. Any other kind of owner is refused before a- // row exists for it.- let owner_user = request- .owner- .as_user()- .cloned()- .ok_or_else(|| AgentSessionError::OwnerNotUser(request.owner.owner_type()))?;+ let owner_user = session_owner_user(&request.owner)?;// The thread linkage is the caller's claim: it is honoured only when// the owner can write to that parent and the message sits in it.if let Some(thread) = &request.thread {@@ -209,16 +202,7 @@ whereservers: Vec::new(),};}- // A managed session runs as its owner: its egress spends their- // connected apps, the repositories it may pick are the ones they- // reach, and its sandbox size is their preference. Only a person has- // those, so any other kind of owner is refused before anything is- // provisioned.- let owner_user = request- .owner- .as_user()- .cloned()- .ok_or_else(|| AgentSessionError::OwnerNotUser(request.owner.owner_type()))?;+ let owner_user = session_owner_user(&request.owner)?;// Explicit source choices are a domain decision, before any session or egress grant exists.let selected_repo = if let Some(url) = request.repo_url.as_deref() {if kind != AgentKind::Cursor {diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rsindex 94dca4b087..cf9b229850 100644--- a/crates/agent_harness/src/domain/service/test.rs+++ b/crates/agent_harness/src/domain/service/test.rs@@ -3441,6 +3441,62 @@ async fn open_managed_session_spawns_at_the_users_default_size() {);}+#[tokio::test]+async fn open_external_session_refuses_a_bot_owner() {+ let (service, repo, _containers, announcer, _runtimes) = harness();+ let id = AgentSessionId::new();++ let error = service+ .open_external_session(OpenExternalAgentSession {+ id: Some(id),+ owner: model_owner::Owner::Bot(BotId::TEST_A),+ ..open_external_request("/srv/agent")+ })+ .await+ .expect_err("a bot cannot own a session");++ assert!(+ matches!(+ error,+ AgentSessionError::OwnerNotUser(model_owner::OwnerType::Bot)+ ),+ "unexpected error: {error:?}"+ );+ assert!(repo.get(id).await.is_err(), "no session row is created");+ assert!(announcer.announced().is_empty());+}++#[tokio::test]+async fn open_managed_session_refuses_a_bot_owner() {+ let (service, repo, containers, announcer, _runtimes) = harness();+ let id = AgentSessionId::new();++ let error = service+ .open_managed_session(OpenManagedSession {+ id: Some(id),+ repo_url: None,+ repo_branch: None,+ instructions: None,+ model: None,+ owner: model_owner::Owner::Bot(BotId::TEST_A),+ prompt: None,+ profile: None,+ })+ .await+ .expect_err("a bot cannot own a session");++ assert!(+ matches!(+ error,+ AgentSessionError::OwnerNotUser(model_owner::OwnerType::Bot)+ ),+ "unexpected error: {error:?}"+ );+ assert!(repo.get(id).await.is_err(), "no session row is created");+ assert!(announcer.announced().is_empty());+ assert!(containers.spawn_sizes().is_empty());+}+#[tokio::test]async fn set_sandbox_size_refuses_a_session_not_owned_by_a_user() {let (service, repo, containers, _announcer, _runtimes) = harness();diff --git a/crates/agent_session/Cargo.toml b/crates/agent_session/Cargo.tomlindex b039048eaf..fbffa5995d 100644--- a/crates/agent_session/Cargo.toml+++ b/crates/agent_session/Cargo.toml@@ -13,6 +13,7 @@ cli = ["dep:clap", "outbound"]# The axum router serving sessions over HTTP.inbound = ["dep:axum",+ "dep:entity_registry","dep:macro_authorization","entity_access/inbound","macro_authorization/axum",@@ -25,6 +26,7 @@ outbound = ["dep:ai_usage","dep:connection_gateway_client","dep:entity_access_db_utils",+ "dep:entity_registry","dep:entity_registry_db_utils","dep:model-entity","dep:sqlx",@@ -64,6 +66,7 @@ entity_access = { path = "../entity_access", default-features = false, features"ports",] }entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }+entity_registry = { path = "../entity_registry/entity_registry", default-features = false, optional = true }entity_registry_db_utils = { path = "../entity_registry/entity_registry_db_utils", optional = true }genai_telemetry = { path = "../genai_telemetry" }model-entity = { path = "../model-entity", optional = true }diff --git a/crates/agent_session/src/bin/backfill_turn_states.rs b/crates/agent_session/src/bin/backfill_turn_states.rsindex 40bee60739..b473fa9409 100644--- a/crates/agent_session/src/bin/backfill_turn_states.rs+++ b/crates/agent_session/src/bin/backfill_turn_states.rs@@ -8,7 +8,10 @@ use std::num::NonZeroUsize;use agent_session::domain::turn_state::backfill_turn_states;use agent_session::outbound::postgres::PgAgentSessionRepo;+use bots::outbound::pg_bots_repo::PgBotsRepo;use clap::Parser;+use entity_registry::OwnerGrantPolicy;+use entity_registry_db_utils::OwnedEntityRegistrar;use sqlx::postgres::PgPoolOptions;#[derive(Parser)]@@ -28,7 +31,14 @@ async fn main() -> anyhow::Result<()> {.max_connections(1).connect(&args.database_url).await?;- let result = backfill_turn_states(&PgAgentSessionRepo::new(pool), args.limit).await?;+ let result = backfill_turn_states(+ &PgAgentSessionRepo::new(+ pool.clone(),+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(pool))),+ ),+ args.limit,+ )+ .await?;println!("examined={} projected={}",result.examined, result.projecteddiff --git a/crates/agent_session/src/bin/seed_jsonl.rs b/crates/agent_session/src/bin/seed_jsonl.rsindex 24363b563d..abb5dd0436 100644--- a/crates/agent_session/src/bin/seed_jsonl.rs+++ b/crates/agent_session/src/bin/seed_jsonl.rs@@ -35,7 +35,10 @@ use agent_session::domain::ports::{AgentSessionLogWriter, AgentSessionRepo, NoOpuse agent_session::domain::service::LiveSessionLogWriter;use agent_session::outbound::postgres::PgAgentSessionRepo;use bots::domain::models::BotId;+use bots::outbound::pg_bots_repo::PgBotsRepo;use clap::Parser;+use entity_registry::OwnerGrantPolicy;+use entity_registry_db_utils::OwnedEntityRegistrar;use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;use serde::Deserialize;@@ -231,7 +234,10 @@ async fn seed(args: &Args) -> Result<(), SeedError> {})?;// The same repo answers every port, exactly as the composition root in// `document_storage_service` wires them.- let repo = PgAgentSessionRepo::new(pool);+ let repo = PgAgentSessionRepo::new(+ pool.clone(),+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(pool))),+ );// Straight to the repo rather than `create_session`: that attaches a// transport, and a recording has no container to attach to. The row isdiff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rsindex dbb20733b8..84effdc699 100644--- a/crates/agent_session/src/domain/model.rs+++ b/crates/agent_session/src/domain/model.rs@@ -279,13 +279,7 @@ pub struct AgentSession {}impl AgentSession {- /// The user this session runs as.- ///- /// For every path that acts as the owner - spends their credentials,- /// bills them, grants them access - rather than merely names them. The- /// owner is a user for every session today, but the type no longer says- /// so; asking here fails typed for any other kind instead of treating a- /// bot or team as a person.+ /// The user this session runs as; see [`session_owner_user`].pub fn owner_user(&self) -> Result<&MacroUserIdStr<'static>, AgentSessionError> {self.owner_id.as_user()@@ -293,6 +287,18 @@ impl AgentSession {}}+/// The user a session runs as.+///+/// A session spends its owner's credentials and bills them, so only a user+/// can own one until the runtime has a bot execution context.+// TODO(ownership-v2): T5.4 admits bot owners once the runtime has a bot execution context.+pub fn session_owner_user(owner: &Owner) -> Result<MacroUserIdStr<'static>, AgentSessionError> {+ owner+ .as_user()+ .cloned()+ .ok_or_else(|| AgentSessionError::OwnerNotUser(owner.owner_type()))+}+/// A persisted agent-session name changed and should be shown to live viewers.#[derive(Debug, Clone, PartialEq, Eq)]pub struct AgentSessionRenamed {diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rsindex 9c357a4abb..096b509d27 100644--- a/crates/agent_session/src/domain/ports.rs+++ b/crates/agent_session/src/domain/ports.rs@@ -12,7 +12,7 @@ use agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessause bots::domain::models::BotId;use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;-use model_owner::Owner;+use model_owner::{Owner, OwnerType};use std::num::NonZeroUsize;/// A bidirectional connection to an agent runtime.@@ -149,9 +149,10 @@ pub enum ManagedPersonaError {/// operator to ask and no owner to authorize against, so it is nobody's/// to start - a misconfiguration rather than a policy answer.UnmanagedSystemBot,- /// The owner does not own or belong to the persona's owner, or is not- /// a user at all.+ /// The owner does not own or belong to the persona's owner.Forbidden,+ /// The owner is not a user, so no persona rule applies.+ OwnerNotUser(OwnerType),/// Looking up the persona or its owner failed.Lookup(AgentSessionError),}@@ -174,7 +175,12 @@ pub async fn persona_for_owner<Bots: BotDirectory>(bot_id: BotId,owner: &Owner,) -> std::result::Result<SelectedPersona, ManagedPersonaError> {- let user = owner.as_user().ok_or(ManagedPersonaError::Forbidden)?;+ let user = session_owner_user(owner).map_err(|error| match error {+ AgentSessionError::OwnerNotUser(owner_type) => {+ ManagedPersonaError::OwnerNotUser(owner_type)+ }+ other => ManagedPersonaError::Lookup(other),+ })?;let facts = bots.bot_facts(bot_id).awaitdiff --git a/crates/agent_session/src/domain/ports/test.rs b/crates/agent_session/src/domain/ports/test.rsindex 30faeaf6f0..eebc115ac5 100644--- a/crates/agent_session/src/domain/ports/test.rs+++ b/crates/agent_session/src/domain/ports/test.rs@@ -176,16 +176,18 @@ async fn channel_co_member_can_select_a_team_selected_channel_persona() {#[tokio::test]async fn an_owner_that_is_not_a_user_selects_no_persona() {- // Every persona rule is about a person - who owns it, whose team it- // belongs to, who shares a channel with it - so a bot owner matches none- // of them, even for a persona anyone could otherwise select.let result = persona_for_owner(&Directory::managed_private(),BotId::TEST_A,&Owner::Bot(BotId::TEST_A),).await;- assert!(matches!(result, Err(ManagedPersonaError::Forbidden)));+ assert!(matches!(+ result,+ Err(ManagedPersonaError::OwnerNotUser(+ model_owner::OwnerType::Bot+ ))+ ));}/// The managed persona a selection resolved to, failing the test otherwise.diff --git a/crates/agent_session/src/domain/routines/service.rs b/crates/agent_session/src/domain/routines/service.rsindex 1037df5fba..57c4eb871c 100644--- a/crates/agent_session/src/domain/routines/service.rs+++ b/crates/agent_session/src/domain/routines/service.rs@@ -69,7 +69,9 @@ where).await.map_err(|error| match error {- ManagedPersonaError::Forbidden => RoutineSessionError::Forbidden,+ ManagedPersonaError::Forbidden | ManagedPersonaError::OwnerNotUser(_) => {+ RoutineSessionError::Forbidden+ }ManagedPersonaError::Lookup(error) => session_error(error),ManagedPersonaError::Unknown| ManagedPersonaError::NotAgentdiff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rsindex 8418bd4b81..aa0fb84086 100644--- a/crates/agent_session/src/inbound/axum_router.rs+++ b/crates/agent_session/src/inbound/axum_router.rs@@ -34,9 +34,11 @@ use chrono::Utc;use entity_access::domain::models::{EditAccessLevel, OwnerAccessLevel, ViewAccessLevel};use entity_access::domain::ports::EntityAccessService;use entity_access::inbound::axum_extractors::AgentSessionAccessLevelExtractor;+use entity_registry::{NonUserOwners, resolve_creation_principal};use macro_authorization::{- ActingUser, InternalOnly, MacroAuthorizationExtractor, MacroAuthorizationService,- MacroAuthorizationState, UserBotOrHarness, UserBotOrHarnessAuthorization,+ ActingUser, InternalOnly, MacroAuthorization, MacroAuthorizationExtractor,+ MacroAuthorizationService, MacroAuthorizationState, UserBotOrHarness,+ UserBotOrHarnessAuthorization,};use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;@@ -1469,6 +1471,7 @@ pub struct CreateSessionState<Opener, Bots, Requests, Auth> {bots: Arc<Bots>,requests: Arc<Requests>,authorization_state: MacroAuthorizationState<Auth>,+ non_user_owners: NonUserOwners,}impl<Opener, Bots, Requests, Auth> CreateSessionState<Opener, Bots, Requests, Auth> {@@ -1478,12 +1481,14 @@ impl<Opener, Bots, Requests, Auth> CreateSessionState<Opener, Bots, Requests, Aubots: Arc<Bots>,requests: Arc<Requests>,authorization_state: MacroAuthorizationState<Auth>,+ non_user_owners: NonUserOwners,) -> Self {Self {opener,bots,requests,authorization_state,+ non_user_owners,}}}@@ -1496,6 +1501,7 @@ impl<Opener, Bots, Requests, Auth> Clone for CreateSessionState<Opener, Bots, Rebots: Arc::clone(&self.bots),requests: Arc::clone(&self.requests),authorization_state: self.authorization_state.clone(),+ non_user_owners: self.non_user_owners,}}}@@ -1576,13 +1582,12 @@ pub struct CreateAgentSessionRequest {/// Omitted, the session starts on the repository's default branch.pub repo_branch: Option<String>,/// The user who owns the session. Ignored for user callers, who always- /// own their own sessions, and for harness callers, whose verified acting- /// user (owner or confirmed team member) owns the session instead;- /// required for bot callers without verified acting-user claims.- ///- /// For bot callers this is a claim, not a verified fact: it is scoped to- /// the bot's own sessions, but the named user owns the session on the- /// bot's say-so.+ /// own their own sessions, for harness callers, whose verified acting+ /// user owns the session, and for bots that already act for a verified+ /// user. A bot without one may name a user here. That claim is trusted+ /// for the bot's own sessions. With no claim, a team bot owns the session+ /// itself only while non-user owners are enabled. Every other bot still+ /// needs an owner.pub owner: Option<String>,/// The thread whose mention triggered the session, when one did./// Linkage only - the mention's text is delivered by the runtime as the@@ -1761,10 +1766,9 @@ impl IntoResponse for CreateSessionApiError {StatusCode::CONFLICT,"this bot already has a session for this thread".to_owned(),),- Self::Domain(AgentSessionError::SessionIdTaken(_)) => (- StatusCode::CONFLICT,- "a session with this id already exists".to_owned(),- ),+ Self::Domain(AgentSessionError::SessionIdTaken(_)) => {+ (StatusCode::CONFLICT, "this id is already taken".to_owned())+ }Self::Domain(AgentSessionError::InvalidRepositorySelection(reason)) => {(StatusCode::UNPROCESSABLE_ENTITY, reason.to_owned())}@@ -1776,6 +1780,10 @@ impl IntoResponse for CreateSessionApiError {StatusCode::UNPROCESSABLE_ENTITY,"owner is not a known user".to_owned(),),+ Self::Domain(AgentSessionError::OwnerNotUser(owner_type)) => (+ StatusCode::UNPROCESSABLE_ENTITY,+ format!("a session cannot be owned by a {owner_type}; sessions run as a user"),+ ),// Nothing to open onto: the persona's runtime is its operator's,// and it did not answer. Says what they have to fix.Self::Domain(AgentSessionError::RuntimeUnavailable(reason)) => {@@ -1843,31 +1851,52 @@ fn resolve_bot(/// Resolve who owns the session.///-/// Only ever a user here: every caller this route admits acts as a person,-/// and the body's `owner` claim is a user id. The type is wider than that so-/// the row and the runtimes are asked, not told, what kind of owner they got.-///-/// A user caller always owns their own sessions. A harness caller always has a-/// verified acting user - the owner for a private harness, a confirmed team-/// member for a team one (the harness authorizer checks the forwarded-/// `x-macro-harness-for-macro-user-id` claim against ownership) - and that-/// verified user owns the session; the body's `owner` claim is never trusted-/// for it. This matches the control endpoint, which already acts only for that-/// verified user: a session that could not later be prompted for its owner is-/// one that should never have been created for that owner. A bot caller's-/// verified acting user wins when present; otherwise the body's claimed owner-/// is accepted (see [`CreateAgentSessionRequest::owner`] for the trust model).+/// The shared resolver refuses harnesses, so that arm trusts the acting user+/// the harness authorizer already verified. A bot with no verified acting+/// user is trusted for a body claim on its own sessions; see+/// [`CreateAgentSessionRequest::owner`].fn resolve_owner(caller: &UserBotOrHarnessAuthorization,claimed: Option<String>,+ non_user_owners: NonUserOwners,) -> Result<Owner, CreateSessionApiError> {- if let Some(user) = caller.acting_user() {- return Ok(Owner::User(user.macro_user_id.clone()));+ match caller {+ UserBotOrHarnessAuthorization::User(user) => {+ principal_owner(&MacroAuthorization::User(user.clone()), non_user_owners)+ }+ UserBotOrHarnessAuthorization::Harness(harness) => {+ Ok(Owner::User(harness.acting_user.macro_user_id.clone()))+ }+ UserBotOrHarnessAuthorization::Bot(bot) => match (bot.acting_user.as_ref(), claimed) {+ (Some(_), _) => principal_owner(&MacroAuthorization::Bot(bot.clone()), non_user_owners),+ (None, Some(text)) => MacroUserIdStr::try_from(text)+ .map(Owner::User)+ .map_err(|_| CreateSessionApiError::UnparseableOwner),+ (None, None) => {+ match resolve_creation_principal(+ &MacroAuthorization::Bot(bot.clone()),+ non_user_owners,+ ) {+ Ok(principal) => Ok(principal.owner()),+ Err(_) => Err(CreateSessionApiError::OwnerRequired),+ }+ }+ },}- let claimed = claimed.ok_or(CreateSessionApiError::OwnerRequired)?;- MacroUserIdStr::try_from(claimed)- .map(Owner::User)- .map_err(|_| CreateSessionApiError::UnparseableOwner)+}++/// The shared resolver accepts every user and every bot with a verified+/// acting user, so an error here is a programming error and surfaces as the+/// existing 500.+fn principal_owner(+ authorization: &MacroAuthorization,+ non_user_owners: NonUserOwners,+) -> Result<Owner, CreateSessionApiError> {+ resolve_creation_principal(authorization, non_user_owners)+ .map(|principal| principal.owner())+ .map_err(|error| {+ CreateSessionApiError::Domain(AgentSessionError::Unknown(anyhow::anyhow!(error)))+ })}#[utoipa::path(@@ -1915,7 +1944,7 @@ pub async fn create_agent_session_handler<if request.thread.is_some() || request.owner.is_some() {return Err(CreateSessionApiError::MixedSessionShape);}- let owner = resolve_owner(&caller.authorization, None)?;+ let owner = resolve_owner(&caller.authorization, None, state.non_user_owners)?;let profile = if let Some(bot_id) = request.bot_id {let selected =persona_for_owner(state.bots.as_ref(), BotId::new_from_uuid(bot_id), &owner)@@ -1927,6 +1956,11 @@ pub async fn create_agent_session_handler<CreateSessionApiError::UnmanagedSystemBot}ManagedPersonaError::Forbidden => CreateSessionApiError::NotYourBot,+ ManagedPersonaError::OwnerNotUser(owner_type) => {+ CreateSessionApiError::Domain(AgentSessionError::OwnerNotUser(+ owner_type,+ ))+ }ManagedPersonaError::Lookup(error) => CreateSessionApiError::Domain(error),})?;match selected {@@ -2054,7 +2088,7 @@ pub async fn create_agent_session_handler<}validate_workspace(&workspace)?;- let owner = resolve_owner(&caller.authorization, request.owner)?;+ let owner = resolve_owner(&caller.authorization, request.owner, state.non_user_owners)?;let thread = request.threaddiff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rsindex b478807827..e010a4d139 100644--- a/crates/agent_session/src/inbound/axum_router/test.rs+++ b/crates/agent_session/src/inbound/axum_router/test.rs@@ -1,14 +1,14 @@use super::*;-use crate::domain::model::SessionStatus;+use crate::domain::model::{SessionStatus, session_owner_user};use axum::body::Body;use axum::http::{Request, header};use chrono::Utc;use macro_authorization::{- BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, BotAuthorizer,- BotScope, HARNESS_FOR_MACRO_USER_ID_HEADER, HARNESS_TOKEN_HEADER, HarnessAuthentication,- HarnessAuthorizationOwner, HarnessAuthorizer, InternalAuthConfig, JwtValidator,- MacroAuthorizationError, MacroAuthorizationServiceImpl, MacroUserAuthentication,- NoUserApiKeyAuthorizer, ValidatedIdentity,+ BOT_FOR_MACRO_USER_ID_HEADER, BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims,+ BotAuthentication, BotAuthorizer, BotScope, HARNESS_FOR_MACRO_USER_ID_HEADER,+ HARNESS_TOKEN_HEADER, HarnessAuthentication, HarnessAuthorizationOwner, HarnessAuthorizer,+ InternalAuthConfig, JwtValidator, MacroAuthorizationError, MacroAuthorizationServiceImpl,+ MacroUserAuthentication, NoUserApiKeyAuthorizer, ValidatedIdentity,};use rootcause::Report;use std::sync::{Arc, Mutex};@@ -18,6 +18,7 @@ const BOT_TOKEN: &str = "mbot_self_test";const HARNESS_TOKEN: &str = "mhns_self_test";const OWNER: &str = "macro|[email protected]";const STRANGER: &str = "macro|[email protected]";+const TEAM_ID: Uuid = Uuid::from_u128(0x7EA3);#[derive(Clone, Default)]struct FakeJwtValidator;@@ -42,17 +43,33 @@ impl BotAuthorizer for SelfBotAuthorizer {&self,bot_token: &str,bot_scope: BotScope,- _acting_user: Option<BotActingUserClaims>,+ acting_user: Option<BotActingUserClaims>,) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {if bot_token != BOT_TOKEN {return Err(Report::new(MacroAuthorizationError::InvalidCredentials));}+ let acting_user = match acting_user.and_then(|claims| claims.user_id) {+ Some(user_id) => {+ let macro_user_id = MacroUserIdStr::try_from(user_id.clone())+ .map_err(|_| Report::new(MacroAuthorizationError::ActingUserNotAuthorized))?;+ Some(MacroUserAuthentication {+ macro_user_id,+ user_context: model_user::UserContext {+ user_id,+ fusion_user_id: "fusion-owner".to_owned(),+ permissions: None,+ organization_id: None,+ },+ })+ }+ None => None,+ };Ok(BotAuthentication {bot_id: BotId::TEST_A,token_id: Uuid::new_v4(),bot_scope,- team_id: None,- acting_user: None,+ team_id: Some(TEAM_ID),+ acting_user,})}}@@ -106,6 +123,7 @@ impl SessionOpener for RecordingOpener {&self,request: OpenExternalAgentSession,) -> crate::domain::error::Result<AgentSession> {+ session_owner_user(&request.owner)?;let session = AgentSession {repo_branch: None,pull_request_url: None,@@ -138,6 +156,7 @@ impl SessionOpener for RecordingOpener {&self,request: OpenManagedSession,) -> crate::domain::error::Result<AgentSession> {+ session_owner_user(&request.owner)?;let bot_id = request.profile.as_ref()@@ -398,6 +417,15 @@ fn router_with_requests(opener: Arc<RecordingOpener>,bots: OneBotDirectory,requests: Arc<RecordingRequester>,+) -> Router {+ router_with_gate(opener, bots, requests, NonUserOwners::Disabled)+}++fn router_with_gate(+ opener: Arc<RecordingOpener>,+ bots: OneBotDirectory,+ requests: Arc<RecordingRequester>,+ non_user_owners: NonUserOwners,) -> Router {let service = MacroAuthorizationServiceImpl::new(FakeJwtValidator,@@ -414,6 +442,7 @@ fn router_with_requests(Arc::new(bots),requests,MacroAuthorizationState::new(Arc::new(service)),+ non_user_owners,))}@@ -436,12 +465,18 @@ fn body(bot_id: Option<Uuid>, workspace: &str, owner: Option<&str>) -> String {}fn as_bot(request_body: String) -> Request<Body> {- Request::post("/")+ as_bot_for("user", None, request_body)+}++fn as_bot_for(scope: &str, acting_user: Option<&str>, request_body: String) -> Request<Body> {+ let mut builder = Request::post("/").header(header::CONTENT_TYPE, "application/json").header(BOT_TOKEN_HEADER, BOT_TOKEN)- .header(BOT_SCOPE_HEADER, "user")- .body(Body::from(request_body))- .unwrap()+ .header(BOT_SCOPE_HEADER, scope);+ if let Some(acting_user) = acting_user {+ builder = builder.header(BOT_FOR_MACRO_USER_ID_HEADER, acting_user);+ }+ builder.body(Body::from(request_body)).unwrap()}fn as_harness(request_body: String) -> Request<Body> {@@ -672,6 +707,164 @@ async fn a_bot_caller_must_claim_an_owner() {assert!(opener.opened.lock().unwrap().is_empty());}+#[tokio::test]+async fn a_bot_acting_for_a_verified_user_owns_the_session_for_that_user() {+ let opener = Arc::new(RecordingOpener::default());+ let request = as_bot_for(+ "user",+ Some(STRANGER),+ body(None, "/srv/agent", Some(OWNER)),+ );++ let response = router(opener.clone()).oneshot(request).await.unwrap();++ assert_eq!(response.status(), StatusCode::CREATED);+ let opened = opener.opened.lock().unwrap();+ assert!(matches!(&opened[0].owner, Owner::User(user) if user.as_ref() == STRANGER));+}++#[tokio::test]+async fn a_team_bot_may_still_claim_a_user_owner() {+ let opener = Arc::new(RecordingOpener::default());+ let request = as_bot_for("team", None, body(None, "/srv/agent", Some(OWNER)));++ let response = router_with_gate(+ opener.clone(),+ OneBotDirectory::external_agent(),+ Arc::new(RecordingRequester::default()),+ NonUserOwners::Disabled,+ )+ .oneshot(request)+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::CREATED);+ let opened = opener.opened.lock().unwrap();+ assert!(matches!(&opened[0].owner, Owner::User(user) if user.as_ref() == OWNER));+}++#[tokio::test]+async fn a_team_bot_without_a_claim_needs_an_owner_while_the_gate_is_off() {+ let opener = Arc::new(RecordingOpener::default());+ let request = as_bot_for("team", None, body(None, "/srv/agent", None));++ let response = router_with_gate(+ opener.clone(),+ OneBotDirectory::external_agent(),+ Arc::new(RecordingRequester::default()),+ NonUserOwners::Disabled,+ )+ .oneshot(request)+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ assert_eq!(bytes.as_ref(), b"owner is required for bot callers");+ assert!(opener.opened.lock().unwrap().is_empty());+}++#[tokio::test]+async fn a_team_bot_without_a_claim_resolves_to_a_bot_owner_when_the_gate_is_on() {+ let opener = Arc::new(RecordingOpener::default());+ let request = as_bot_for("team", None, body(None, "/srv/agent", None));++ let response = router_with_gate(+ opener.clone(),+ OneBotDirectory::external_agent(),+ Arc::new(RecordingRequester::default()),+ NonUserOwners::Enabled,+ )+ .oneshot(request)+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ assert_eq!(+ bytes.as_ref(),+ b"a session cannot be owned by a bot; sessions run as a user"+ );+ assert!(opener.opened.lock().unwrap().is_empty());+}++#[tokio::test]+async fn a_team_bot_selecting_a_persona_is_refused_as_a_bot_owner() {+ let opener = Arc::new(RecordingOpener::default());+ let requests = Arc::new(RecordingRequester::default());+ let request = as_bot_for(+ "team",+ None,+ serde_json::json!({ "botId": BotId::TEST_A.as_uuid() }).to_string(),+ );++ let response = router_with_gate(+ opener.clone(),+ OneBotDirectory::managed_agent(),+ requests.clone(),+ NonUserOwners::Enabled,+ )+ .oneshot(request)+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ assert_eq!(+ bytes.as_ref(),+ b"a session cannot be owned by a bot; sessions run as a user"+ );+ assert!(opener.opened.lock().unwrap().is_empty());+ assert!(opener.managed.lock().unwrap().is_empty());+ assert!(requests.requested.lock().unwrap().is_empty());+}++#[tokio::test]+async fn a_bot_owner_is_refused_with_an_explicit_message() {+ let response =+ CreateSessionApiError::Domain(AgentSessionError::OwnerNotUser(model_owner::OwnerType::Bot))+ .into_response();++ assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ assert_eq!(+ bytes.as_ref(),+ b"a session cannot be owned by a bot; sessions run as a user"+ );+}++#[tokio::test]+async fn a_taken_id_says_the_id_is_taken() {+ let response =+ CreateSessionApiError::Domain(AgentSessionError::SessionIdTaken(AgentSessionId::TEST_A))+ .into_response();++ assert_eq!(response.status(), StatusCode::CONFLICT);+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ assert_eq!(bytes.as_ref(), b"this id is already taken");+}++#[tokio::test]+async fn an_unknown_owner_is_a_422() {+ let response = CreateSessionApiError::Domain(AgentSessionError::UnknownOwner).into_response();++ assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ assert_eq!(bytes.as_ref(), b"owner is not a known user");+}+#[tokio::test]async fn a_relative_workspace_is_rejected() {let opener = Arc::new(RecordingOpener::default());diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rsindex 22632c6d17..5492b7563f 100644--- a/crates/agent_session/src/outbound/postgres.rs+++ b/crates/agent_session/src/outbound/postgres.rs@@ -21,7 +21,7 @@ use crate::domain::model::{ClaimOutcome, CreateAgentSessionParams, ExternalSession, LeaseView, ManagerFence, Message,ReplicaAddress, ReplicaId, SandboxSize, SessionBot, SessionClaim, SessionManager,SessionPreviewCandidate, SessionStatus, StoredAgentSessionLog, StoredQueuedAction,- ThreadSession, cursor_run_checkpoint,+ ThreadSession, cursor_run_checkpoint, session_owner_user,};use crate::domain::ports::{AgentSessionLogRepo, AgentSessionRepo, ExternalSessionRepo, REPLICA_STALE_AFTER,@@ -40,9 +40,10 @@ use entity_access_db_utils::{AccessLevel, EntityAccessSourceType, EntityType, delete_entity_access_rows,insert_entity_access_row,};+use entity_registry::BotFacts;use entity_registry_db_utils::{- NewEntityRecord, RegisteredEntityType, WriteOutcome, delete_entity, insert_entity,- touch_updated,+ EntityRegistryError, NewEntityRecord, OwnedEntityRegistrar, RegisteredEntityType, WriteOutcome,+ delete_entity, touch_updated,};use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;@@ -51,15 +52,26 @@ use sqlx::PgPool;use std::num::NonZeroUsize;/// Postgres implementation of [`AgentSessionRepo`] and [`AgentSessionLogRepo`].-#[derive(Debug, Clone)]-pub struct PgAgentSessionRepo {+#[derive(Clone)]+pub struct PgAgentSessionRepo<B> {pool: PgPool,+ registrar: OwnedEntityRegistrar<B>,}-impl PgAgentSessionRepo {- /// Create a Postgres agent session repository.- pub fn new(pool: PgPool) -> Self {- Self { pool }+impl<B> std::fmt::Debug for PgAgentSessionRepo<B> {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter+ .debug_struct("PgAgentSessionRepo")+ .field("pool", &self.pool)+ .finish_non_exhaustive()+ }+}++impl<B: BotFacts> PgAgentSessionRepo<B> {+ /// Create a Postgres agent session repository that registers owners+ /// through `registrar`.+ pub fn new(pool: PgPool, registrar: OwnedEntityRegistrar<B>) -> Self {+ Self { pool, registrar }}}@@ -280,7 +292,7 @@ impl TryFrom<AgentSessionRow> for AgentSession {}}-impl AgentSessionRepo for PgAgentSessionRepo {+impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {async fn create(&self, params: CreateAgentSessionParams) -> Result<AgentSession> {let CreateAgentSessionParams {id,@@ -303,9 +315,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {// The owner's grant is a user access row, and the session lands in// the owner's history: this store still holds user-owned sessions,// even though the denormalized owner_id no longer references "User".- let owner_user = owner_id- .as_user()- .ok_or_else(|| AgentSessionError::OwnerNotUser(owner_id.owner_type()))?;+ let owner_user = session_owner_user(&owner_id)?;// The session row and its access grants land together: a crash between// the two would leave a session nobody - not even its owner -@@ -316,6 +326,17 @@ impl AgentSessionRepo for PgAgentSessionRepo {.await.context("begin agent session create")?;+ let known_owner = sqlx::query_scalar!(+ r#"SELECT id FROM "User" WHERE id = $1"#,+ owner_user.as_ref(),+ )+ .fetch_optional(&mut *transaction)+ .await+ .context("failed to confirm the session owner")?;+ if known_owner.is_none() {+ return Err(AgentSessionError::UnknownOwner);+ }+let (status, status_event_name) = status_columns(&SessionStatus::NoMessages);// An inline @macro mention is a one-shot on the message. It stays out// of the agents list and search. Every other session — the agents@@ -376,27 +397,20 @@ impl AgentSessionRepo for PgAgentSessionRepo {},)?;- insert_entity_access_row(- &mut transaction,- &id.as_uuid(),- EntityType::AgentSession,- owner_user.as_ref(),- EntityAccessSourceType::User,- AccessLevel::Owner,- )- .await- .context("failed to grant the owner access to the agent session")?;-- insert_entity(- &mut transaction,- NewEntityRecord::new(- id.as_uuid(),- RegisteredEntityType::AgentSession,- owner_id.clone(),- ),- )- .await- .map_err(|error| registry_unknown(error, "failed to register the agent session"))?;+ self.registrar+ .register_owned_entity(+ &mut transaction,+ NewEntityRecord::new(+ id.as_uuid(),+ RegisteredEntityType::AgentSession,+ owner_id.clone(),+ ),+ )+ .await+ .map_err(|error| match *error.current_context() {+ EntityRegistryError::RegistrationConflict => AgentSessionError::SessionIdTaken(id),+ _ => registry_unknown(error, "failed to register the agent session"),+ })?;// The channel the bot was invoked in can steer the session: the// invocation was public there, so that audience is. Read from the@@ -1085,7 +1099,7 @@ impl TryFrom<AgentSessionLogRow> for StoredAgentSessionLog {}}-impl ExternalSessionRepo for PgAgentSessionRepo {+impl<B: BotFacts + 'static> ExternalSessionRepo for PgAgentSessionRepo<B> {#[tracing::instrument(skip(self), err)]async fn upsert(&self, id: AgentSessionId, external: ExternalSession) -> Result<()> {sqlx::query!(@@ -1148,7 +1162,7 @@ impl ExternalSessionRepo for PgAgentSessionRepo {}}-impl AgentSessionLogRepo for PgAgentSessionRepo {+impl<B: BotFacts + 'static> AgentSessionLogRepo for PgAgentSessionRepo<B> {async fn create(&self, log: AgentSessionLog) -> Result<StoredAgentSessionLog> {self.create_projected(log, None, None, None).await}@@ -1501,7 +1515,7 @@ impl AgentSessionLogRepo for PgAgentSessionRepo {}}-impl SessionOwnership for PgAgentSessionRepo {+impl<B: BotFacts + 'static> SessionOwnership for PgAgentSessionRepo<B> {async fn claim(&self, session: AgentSessionId, replica: ReplicaId) -> Result<ClaimOutcome> {// One statement: the replica's heartbeat row is upserted in the CTE// (a claim can never reference a replica the store has not seen),@@ -1680,7 +1694,7 @@ impl SessionOwnership for PgAgentSessionRepo {/// Folding reads the log through `agent_fold`'s own port; this adapter/// already speaks [`AgentSessionLogRepo`], so bridging is one line.-impl agent_fold::domain::ports::LogRepo for PgAgentSessionRepo {+impl<B: BotFacts + 'static> agent_fold::domain::ports::LogRepo for PgAgentSessionRepo<B> {async fn list_by_session(&self,session: AgentSessionId,@@ -1697,7 +1711,7 @@ impl agent_fold::domain::ports::LogRepo for PgAgentSessionRepo {/// A participant who has left keeps their row, with `left_at` set - so the/// filter is what stops a former member being sent a session they can no/// longer open.-impl SessionAudience for PgAgentSessionRepo {+impl<B: BotFacts + 'static> SessionAudience for PgAgentSessionRepo<B> {async fn viewers(&self,agent_session_id: AgentSessionId,diff --git a/crates/agent_session/src/outbound/postgres/pull_request.rs b/crates/agent_session/src/outbound/postgres/pull_request.rsindex 0a919bb86c..2979b8713d 100644--- a/crates/agent_session/src/outbound/postgres/pull_request.rs+++ b/crates/agent_session/src/outbound/postgres/pull_request.rs@@ -2,7 +2,9 @@use super::*;-impl crate::domain::pull_request::SessionPullRequestRepo for PgAgentSessionRepo {+impl<B: BotFacts + 'static> crate::domain::pull_request::SessionPullRequestRepo+ for PgAgentSessionRepo<B>+{async fn record_pull_request(&self,session: AgentSessionId,diff --git a/crates/agent_session/src/outbound/postgres/queue.rs b/crates/agent_session/src/outbound/postgres/queue.rsindex bafedea2e2..f10495bb04 100644--- a/crates/agent_session/src/outbound/postgres/queue.rs+++ b/crates/agent_session/src/outbound/postgres/queue.rs@@ -4,7 +4,7 @@ use super::*;use crate::domain::model::StoredQueuedAction;use sqlx::types::Json;-impl PgAgentSessionRepo {+impl<B> PgAgentSessionRepo<B> {pub(super) async fn load_queued_actions(&self,id: AgentSessionId,diff --git a/crates/agent_session/src/outbound/postgres/search.rs b/crates/agent_session/src/outbound/postgres/search.rsindex 70a77223f1..1fe8a2f265 100644--- a/crates/agent_session/src/outbound/postgres/search.rs+++ b/crates/agent_session/src/outbound/postgres/search.rs@@ -1,5 +1,7 @@//! Bounded-to-allowlist metadata lookup for search.+use entity_registry::BotFacts;+use crate::{domain::{error::Result,@@ -88,7 +90,7 @@ async fn search_metadata(.collect()}-impl AgentSessionSearchMetadataRepo for PgAgentSessionRepo {+impl<B: BotFacts + 'static> AgentSessionSearchMetadataRepo for PgAgentSessionRepo<B> {async fn search_metadata(&self, ids: &[uuid::Uuid]) -> Result<Vec<AgentSessionSearchMetadata>> {Ok(search_metadata(&self.pool, ids).awaitdiff --git a/crates/agent_session/src/outbound/postgres/sharing.rs b/crates/agent_session/src/outbound/postgres/sharing.rsindex 2c4a51adc9..e6c49ac11a 100644--- a/crates/agent_session/src/outbound/postgres/sharing.rs+++ b/crates/agent_session/src/outbound/postgres/sharing.rs@@ -8,6 +8,7 @@ use crate::domain::{};use anyhow::Context;use entity_access_db_utils::update_entity_access_channel_share_permissions;+use entity_registry::BotFacts;use model_entity::EntityType;use models_permissions::share_permission::{LinkShare, SharePermissionV2, UpdateSharePermissionRequestV2,@@ -29,7 +30,7 @@ fn team_error(error: rootcause::Report<TeamShareError>) -> AgentSessionError {}}-impl SessionSharingRepo for PgAgentSessionRepo {+impl<B: BotFacts + 'static> SessionSharingRepo for PgAgentSessionRepo<B> {#[tracing::instrument(skip(self), err)]async fn permissions(&self, id: AgentSessionId) -> Result<SharePermissionV2> {let row = sqlx::query!(diff --git a/crates/agent_session/src/outbound/postgres/sharing/test.rs b/crates/agent_session/src/outbound/postgres/sharing/test.rsindex 427ba754bd..c5902570d0 100644--- a/crates/agent_session/src/outbound/postgres/sharing/test.rs+++ b/crates/agent_session/src/outbound/postgres/sharing/test.rs@@ -1,7 +1,7 @@use super::*;use crate::domain::ports::AgentSessionRepo;use crate::outbound::postgres::test::{- create_session, create_test_bot, insert_originating_thread_fixture, new_session,+ create_session, create_test_bot, insert_originating_thread_fixture, new_session, test_repo,};use macro_db_migrator::MACRO_DB_MIGRATIONS;use models_permissions::share_permission::channel_share_permission::{@@ -20,7 +20,7 @@ fn request() -> UpdateSharePermissionRequestV2 {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn existing_channel_grants_are_visible_before_settings_are_created(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let (channel, thread, message) = insert_originating_thread_fixture(&pool).await;let session = create_session(&repo, new_session(bot, Some(thread), Some(message))).await;@@ -37,7 +37,7 @@ async fn existing_channel_grants_are_visible_before_settings_are_created(pool: P#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn settings_and_channel_grants_round_trip_without_promoting_viewers(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot, None, None)).await;let channel = macro_uuid::generate_uuid_v7().to_string();@@ -121,7 +121,7 @@ async fn settings_and_channel_grants_round_trip_without_promoting_viewers(pool:#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn link_scopes_levels_and_resets_persist(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot, None, None)).await;for scope in [LinkShare::Public, LinkShare::Team] {diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rsindex 5d272a9294..ee497c44e4 100644--- a/crates/agent_session/src/outbound/postgres/test.rs+++ b/crates/agent_session/src/outbound/postgres/test.rs@@ -10,6 +10,8 @@ use agent_runtime_protocol::domain::schema::v0::{AcpMessage, SystemEvent};use bots::domain::models::{BotOwner, CreateBotRequest};use bots::domain::ports::BotRepo;use bots::outbound::pg_bots_repo::PgBotsRepo;+use entity_registry::OwnerGrantPolicy;+use entity_registry_db_utils::OwnedEntityRegistrar;use macro_db_migrator::MACRO_DB_MIGRATIONS;fn user_id(value: &str) -> MacroUserIdStr<'static> {@@ -103,8 +105,15 @@ pub(super) fn new_session(}}-pub(super) async fn create_session(- repo: &PgAgentSessionRepo,+pub(super) fn test_repo(pool: &PgPool) -> PgAgentSessionRepo<PgBotsRepo> {+ PgAgentSessionRepo::new(+ pool.clone(),+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(pool.clone()))),+ )+}++pub(super) async fn create_session<B: entity_registry::BotFacts + 'static>(+ repo: &PgAgentSessionRepo<B>,params: CreateAgentSessionParams,) -> AgentSession {AgentSessionRepo::create(repo, params)@@ -114,8 +123,8 @@ pub(super) async fn create_session(/// Drive a session's status the way production does: append a system event to/// the log and let [`AgentSessionLogRepo::create`] project it onto the session.-async fn append_system_event(- repo: &PgAgentSessionRepo,+async fn append_system_event<B: entity_registry::BotFacts + 'static>(+ repo: &PgAgentSessionRepo<B>,agent_session_id: AgentSessionId,event: SystemEvent,) {@@ -209,6 +218,34 @@ async fn entity_row_count(pool: &PgPool, id: AgentSessionId) -> i64 {.expect("count the session's entity row")}+async fn agent_session_row_count(pool: &PgPool, id: AgentSessionId) -> i64 {+ sqlx::query_scalar!(+ r#"+ SELECT count(*) AS "count!"+ FROM agent_session+ WHERE id = $1+ "#,+ id.as_uuid(),+ )+ .fetch_one(pool)+ .await+ .expect("count agent_session rows")+}++async fn entity_access_row_count(pool: &PgPool, id: AgentSessionId) -> i64 {+ sqlx::query_scalar!(+ r#"+ SELECT count(*) AS "count!"+ FROM entity_access+ WHERE entity_id = $1+ "#,+ id.as_uuid(),+ )+ .fetch_one(pool)+ .await+ .expect("count entity_access rows")+}+fn acp_notification() -> AcpMessage {AcpMessage(RawJsonRpcMessage::notification("test/notify".to_string(), serde_json::json!({}))@@ -218,7 +255,7 @@ fn acp_notification() -> AcpMessage {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn create_refuses_an_owner_that_is_not_a_user(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let params = CreateAgentSessionParams {owner_id: Owner::Bot(bot_id),@@ -226,9 +263,6 @@ async fn create_refuses_an_owner_that_is_not_a_user(pool: PgPool) {};let id = params.id;- // Refused by type before the row's user foreign key, user access row, or- // user history could say it less clearly - and before any of them is- // written.let error = AgentSessionRepo::create(&repo, params).await.expect_err("a bot cannot own a session row");@@ -240,9 +274,96 @@ async fn create_refuses_an_owner_that_is_not_a_user(pool: PgPool) {assert_eq!(entity_row_count(&pool, id).await, 0);}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_registers_the_owner_through_the_registrar(pool: PgPool) {+ let repo = test_repo(&pool);+ let bot_id = create_test_bot(&pool).await;+ let params = new_session(bot_id, None, None);+ let id = params.id;+ create_session(&repo, params).await;++ assert_eq!(entity_row_count(&pool, id).await, 1);+ let (entity_type, owner_type, owner_id, _, _) = fetch_session_entity(&pool, id).await;+ assert_eq!(+ (entity_type, owner_type, owner_id),+ (+ "agent_session".to_string(),+ "user".to_string(),+ OWNER.to_string()+ )+ );++ let grants = sqlx::query!(+ r#"+ SELECT source_type::text AS "source_type!", source_id, access_level::text AS "access_level!"+ FROM entity_access+ WHERE entity_id = $1+ "#,+ id.as_uuid(),+ )+ .fetch_all(&pool)+ .await+ .expect("read the session's grants");+ assert_eq!(grants.len(), 1);+ assert_eq!(grants[0].source_type, "user");+ assert_eq!(grants[0].source_id, OWNER);+ assert_eq!(grants[0].access_level, "owner");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_rejects_an_unknown_user_owner(pool: PgPool) {+ let repo = test_repo(&pool);+ let bot_id = create_test_bot(&pool).await;+ let params = CreateAgentSessionParams {+ owner_id: Owner::User(user_id("macro|[email protected]")),+ ..new_session(bot_id, None, None)+ };+ let id = params.id;++ let error = AgentSessionRepo::create(&repo, params)+ .await+ .expect_err("an unknown user cannot own a session");++ assert!(matches!(error, AgentSessionError::UnknownOwner));+ assert_eq!(agent_session_row_count(&pool, id).await, 0);+ assert_eq!(entity_row_count(&pool, id).await, 0);+ assert_eq!(entity_access_row_count(&pool, id).await, 0);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_refuses_a_caller_minted_id_held_by_another_entity(pool: PgPool) {+ let repo = test_repo(&pool);+ let bot_id = create_test_bot(&pool).await;+ let params = new_session(bot_id, None, None);+ let id = params.id;++ let mut transaction = pool.begin().await.expect("begin entity seed");+ entity_registry_db_utils::insert_entity(+ &mut transaction,+ entity_registry_db_utils::NewEntityRecord::new(+ id.as_uuid(),+ entity_registry_db_utils::RegisteredEntityType::Document,+ Owner::User(user_id(OWNER)),+ ),+ )+ .await+ .expect("register a document under the session id");+ transaction.commit().await.expect("commit entity seed");++ let error = AgentSessionRepo::create(&repo, params)+ .await+ .expect_err("a session cannot take an id another entity holds");++ assert!(matches!(+ error,+ AgentSessionError::SessionIdTaken(taken) if taken == id+ ));+ assert_eq!(agent_session_row_count(&pool, id).await, 0);+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn create_and_get_round_trips(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let mut params = new_session(bot_id, None, None);params.repo_branch = Some(@@ -286,7 +407,7 @@ async fn create_and_get_round_trips(pool: PgPool) {async fn instructions_round_trip_on_every_read_path(pool: PgPool) {const INSTRUCTIONS: &str = "Answer in one sentence.\nNever open a pull request.";- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let (_channel_id, thread_id, originating_message_id) =insert_originating_thread_fixture(&pool).await;@@ -328,7 +449,7 @@ async fn instructions_round_trip_on_every_read_path(pool: PgPool) {/// included, and the default is the owner's connections.#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn mcp_server_selection_round_trips_on_every_read_path(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let (_channel_id, thread_id, originating_message_id) =insert_originating_thread_fixture(&pool).await;@@ -373,7 +494,7 @@ async fn mcp_server_selection_round_trips_on_every_read_path(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn set_acp_session_id_updates_only_the_resume_identity(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let id = create_session(&repo, new_session(bot_id, None, None)).await@@ -399,7 +520,7 @@ async fn set_acp_session_id_updates_only_the_resume_identity(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn set_model_updates_only_the_model(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let id = create_session(&repo, new_session(bot_id, None, None)).await@@ -446,7 +567,7 @@ async fn set_model_updates_only_the_model(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn set_repo_url_replaces_and_clears_the_repository(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let id = create_session(&repo, new_session(bot_id, None, None)).await@@ -494,7 +615,7 @@ async fn set_repo_url_replaces_and_clears_the_repository(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn set_name_updates_only_the_name(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let id = create_session(&repo, new_session(bot_id, None, None)).await@@ -545,7 +666,7 @@ async fn set_name_updates_only_the_name(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn set_name_errors_for_missing_session(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool);+ let repo = test_repo(&pool);assert!(repo.set_name(AgentSessionId::new(), "Missing Session")@@ -556,7 +677,7 @@ async fn set_name_errors_for_missing_session(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn generated_name_only_replaces_the_default(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let id = create_session(&repo, new_session(bot_id, None, None)).await@@ -615,7 +736,7 @@ async fn generated_name_only_replaces_the_default(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn sandbox_size_round_trips_and_user_default_falls_back(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let owner = user_id(OWNER);let id = create_session(&repo, new_session(bot_id, None, None))@@ -661,7 +782,7 @@ async fn sandbox_size_round_trips_and_user_default_falls_back(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn get_missing_session_errors(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool);+ let repo = test_repo(&pool);let missing = AgentSessionId::new();assert!(AgentSessionRepo::get(&repo, missing).await.is_err());@@ -669,7 +790,7 @@ async fn get_missing_session_errors(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn delete_removes_session(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot_id, None, None)).await;let id = session.id;@@ -683,7 +804,7 @@ async fn delete_removes_session(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn log_create_and_list_by_session_orders_chronologically(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let session_id = create_session(&repo, new_session(bot_id, None, None)).await@@ -749,7 +870,7 @@ async fn log_create_and_list_by_session_orders_chronologically(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn find_for_thread_matches_the_originating_thread_and_bot(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_a = create_test_bot(&pool).await;let bot_b = create_test_bot(&pool).await;let (originating_channel, thread, originating_message) =@@ -802,7 +923,7 @@ async fn find_for_thread_matches_the_originating_thread_and_bot(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn find_all_for_thread_returns_every_session_on_the_thread(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_a = create_test_bot(&pool).await;let bot_b = create_test_bot(&pool).await;let (_channel, thread, originating_message) = insert_originating_thread_fixture(&pool).await;@@ -861,7 +982,7 @@ async fn find_all_for_thread_returns_every_session_on_the_thread(pool: PgPool) {async fn recent_for_owner_returns_the_owners_newest_sessions(pool: PgPool) {const OTHER_OWNER: &str = "macro|[email protected]";- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;insert_user(&pool, OTHER_OWNER).await;@@ -899,7 +1020,7 @@ async fn recent_for_owner_returns_the_owners_newest_sessions(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn find_for_thread_requires_thread_and_bot_for_originating_match(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let (_channel, thread, originating_message) = insert_originating_thread_fixture(&pool).await;create_session(@@ -923,7 +1044,7 @@ async fn find_for_thread_requires_thread_and_bot_for_originating_match(pool: PgP#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn thread_and_bot_belong_to_only_one_session(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let (_, thread, originating_message) = insert_originating_thread_fixture(&pool).await;create_session(@@ -942,7 +1063,7 @@ async fn thread_and_bot_belong_to_only_one_session(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn a_sessions_audience_is_its_owner(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot, None, None)).await;@@ -965,7 +1086,7 @@ async fn a_sessions_audience_is_its_owner(pool: PgPool) {/// publisher's own early return is what turns that into no gateway call.#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn an_unknown_session_has_no_audience(pool: PgPool) {- let audience = PgAgentSessionRepo::new(pool)+ let audience = test_repo(&pool).viewers(AgentSessionId::new()).await.expect("read the session audience");@@ -978,7 +1099,7 @@ async fn an_unknown_session_has_no_audience(pool: PgPool) {/// transaction as the session, so a session can never exist unreachable.#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn create_grants_the_owner_and_the_originating_channel(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let (origin_channel_id, thread_id, originating_message_id) =insert_originating_thread_fixture(&pool).await;@@ -1027,7 +1148,7 @@ async fn create_grants_the_owner_and_the_originating_channel(pool: PgPool) {/// from, so it is the owner's alone.#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn create_without_a_mention_grants_only_the_owner(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let params = new_session(bot_id, None, None);@@ -1056,7 +1177,7 @@ async fn create_without_a_mention_grants_only_the_owner(pool: PgPool) {/// touches later, so Soup's `viewed_at` is set from the moment it exists.#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn create_records_the_session_in_the_owners_history(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let params = new_session(bot_id, None, None);@@ -1085,7 +1206,7 @@ async fn create_records_the_session_in_the_owners_history(pool: PgPool) {/// bot, is listed immediately.#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn inline_macro_sessions_start_hidden(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);create_test_bot(&pool).await;let (_channel_id, thread_id, originating_message_id) =insert_originating_thread_fixture(&pool).await;@@ -1120,7 +1241,7 @@ async fn inline_macro_sessions_start_hidden(pool: PgPool) {/// answers what it is asked.#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn preview_answers_per_id_by_the_viewers_grants(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let (channel_id, thread_id, originating_message_id) =insert_originating_thread_fixture(&pool).await;@@ -1229,7 +1350,7 @@ async fn preview_answers_per_id_by_the_viewers_grants(pool: PgPool) {/// has to take its grants with it or they accumulate forever.#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn delete_removes_the_session_grants(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let (_, thread_id, originating_message_id) = insert_originating_thread_fixture(&pool).await;@@ -1299,7 +1420,7 @@ fn cursor_external(agent: &str) -> ExternalSession {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn external_session_round_trips_and_upsert_replaces(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);insert_user(&pool, OWNER).await;let bot_id = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot_id, None, None)).await;@@ -1357,7 +1478,7 @@ async fn external_session_round_trips_and_upsert_replaces(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn two_sessions_cannot_claim_the_same_external_agent(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);insert_user(&pool, OWNER).await;let bot_id = create_test_bot(&pool).await;let (_channel, thread, message) = insert_originating_thread_fixture(&pool).await;@@ -1373,7 +1494,7 @@ async fn two_sessions_cannot_claim_the_same_external_agent(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn deleting_a_session_cascades_its_external_row(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);insert_user(&pool, OWNER).await;let bot_id = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot_id, None, None)).await;@@ -1444,7 +1565,7 @@ fn cursor_checkpoint_log(id: AgentSessionId, run: &str) -> AgentSessionLog {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn claiming_is_reentrant_and_every_claim_bumps_the_fence(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot_id, None, None)).await;let replica = ReplicaId::mint();@@ -1458,7 +1579,7 @@ async fn claiming_is_reentrant_and_every_claim_bumps_the_fence(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn a_live_holder_blocks_a_second_replica(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot_id, None, None)).await;let holder = ReplicaId::mint();@@ -1473,7 +1594,7 @@ async fn a_live_holder_blocks_a_second_replica(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn a_stale_holder_is_superseded(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot_id, None, None)).await;let crashed = ReplicaId::mint();@@ -1493,7 +1614,7 @@ async fn a_stale_holder_is_superseded(pool: PgPool) {/// waiting out the heartbeat it is still sending.#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn a_draining_holder_stops_managing_and_can_be_taken_over(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot_id, None, None)).await;let leaving = ReplicaId::mint();@@ -1540,7 +1661,7 @@ async fn a_draining_holder_stops_managing_and_can_be_taken_over(pool: PgPool) {/// a process on its way out is.#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn draining_is_idempotent_and_needs_no_prior_heartbeat(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot_id, None, None)).await;let replica = ReplicaId::mint();@@ -1570,7 +1691,7 @@ async fn drained_at(pool: &PgPool, replica: ReplicaId) -> Option<chrono::DateTim#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn release_frees_the_lease_but_never_a_successors(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot_id, None, None)).await;let crashed = ReplicaId::mint();@@ -1595,7 +1716,7 @@ async fn release_frees_the_lease_but_never_a_successors(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn a_fenced_append_rejects_a_superseded_writer(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot_id, None, None)).await;let zombie = ReplicaId::mint();@@ -1632,7 +1753,7 @@ async fn a_fenced_append_rejects_a_superseded_writer(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn cursor_checkpoint_advances_atomically_under_the_session_fence(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot_id, None, None)).await;ExternalSessionRepo::upsert(&repo, session.id, cursor_external("bc-1"))@@ -1675,7 +1796,7 @@ async fn cursor_checkpoint_advances_atomically_under_the_session_fence(pool: PgP/// Exercise the generic boundary contract without asking persistence to inspect ACP JSON.#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn history_boundary_selects_initialization_and_keeps_raw_audit(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot, None, None)).await;let claim = claimed(repo.claim(session.id, ReplicaId::mint()).await.unwrap());@@ -1748,7 +1869,7 @@ async fn history_boundary_selects_initialization_and_keeps_raw_audit(pool: PgPoo#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn history_boundary_rejects_foreign_rows_and_stale_claims_atomically(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot, None, None)).await;let other = create_session(&repo, new_session(bot, None, None)).await;@@ -1821,7 +1942,7 @@ async fn history_boundary_rejects_foreign_rows_and_stale_claims_atomically(pool:#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn history_boundary_update_failure_rolls_back_response(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot, None, None)).await;let claim = claimed(repo.claim(session.id, ReplicaId::mint()).await.unwrap());@@ -1862,7 +1983,7 @@ async fn history_boundary_update_failure_rolls_back_response(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn history_boundary_insert_failure_keeps_previous_selection(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot, None, None)).await;let claim = claimed(repo.claim(session.id, ReplicaId::mint()).await.unwrap());@@ -1913,7 +2034,7 @@ async fn history_boundary_insert_failure_keeps_previous_selection(pool: PgPool)#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn history_boundary_readers_see_response_and_selection_together(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot, None, None)).await;let claim = claimed(repo.claim(session.id, ReplicaId::mint()).await.unwrap());@@ -1977,7 +2098,7 @@ async fn history_boundary_readers_see_response_and_selection_together(pool: PgPo#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn history_boundary_range_uses_order_index_and_uuid_tie_break(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot, None, None)).await;// Equal timestamps force ordering and selection to use the UUID tie-break.@@ -2069,7 +2190,7 @@ async fn history_boundary_range_uses_order_index_and_uuid_tie_break(pool: PgPool#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn participants_are_the_distinct_users_the_log_attributes(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let session_id = create_session(&repo, new_session(bot_id, None, None)).await@@ -2108,7 +2229,7 @@ async fn participants_are_the_distinct_users_the_log_attributes(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn pull_request_is_atomic_and_survives_history_selection(pool: PgPool) {use crate::domain::pull_request::SessionPullRequestRepo;- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot, None, None)).await;let url = "https://github.com/org/repo/pull/123";@@ -2164,7 +2285,7 @@ async fn pull_request_is_atomic_and_survives_history_selection(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn rotating_a_session_credential_revokes_the_previous_one(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot, None, None)).await;repo.set_egress_token_hash(session.id, "first-token-hash")@@ -2200,7 +2321,7 @@ async fn rotating_a_session_credential_revokes_the_previous_one(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn pull_request_waiting_on_takeover_cannot_overwrite_successor(pool: PgPool) {use crate::domain::pull_request::SessionPullRequestRepo;- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot, None, None)).await;let ClaimOutcome::Claimed(old) = repo.claim(session.id, ReplicaId::mint()).await.unwrap()@@ -2308,7 +2429,7 @@ async fn a_document_session_preserves_its_origin_and_inherits_live_document_acce}).await.unwrap();- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let session = create_session(&repo, new_session(bot, Some(root.id), Some(root.id))).await;assert_eq!(session.thread_parent, Some(parent.clone()));assert_eq!(@@ -2455,7 +2576,7 @@ impl crate::domain::audience::SessionSubscriptions for DocumentSubscriptions {/// clock.#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn create_batch_fenced_writes_in_order_under_the_given_ids(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot, None, None)).await;let claim = claimed(repo.claim(session.id, ReplicaId::mint()).await.unwrap());@@ -2534,7 +2655,7 @@ async fn create_batch_fenced_writes_in_order_under_the_given_ids(pool: PgPool) {/// touched.#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn create_batch_fenced_refuses_stale_claims_and_foreign_frames(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot, None, None)).await;let other = create_session(&repo, new_session(bot, None, None)).await;@@ -2582,7 +2703,7 @@ async fn turn_projection_is_atomic_fenced_and_backfill_cannot_overwrite_live_stause crate::domain::turn_state::SessionTurnProjectionRepo;use agent_fold::domain::model::TurnState;- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot_id, None, None)).await;let replica = ReplicaId::mint();diff --git a/crates/agent_session/src/outbound/postgres/test/queue.rs b/crates/agent_session/src/outbound/postgres/test/queue.rsindex 45fd5b2a73..9dbe4db311 100644--- a/crates/agent_session/src/outbound/postgres/test/queue.rs+++ b/crates/agent_session/src/outbound/postgres/test/queue.rs@@ -21,7 +21,7 @@ fn stored_prompt(text: &str) -> StoredQueuedAction {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn replace_lists_oldest_first_and_empty_deletes_the_row(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot_id, None, None)).await;@@ -71,7 +71,7 @@ async fn replace_lists_oldest_first_and_empty_deletes_the_row(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn deleting_a_session_cascades_its_queue(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot_id, None, None)).await;repo.replace_queued_actions(session.id, &[stored_prompt("remember me")])@@ -98,7 +98,7 @@ async fn deleting_a_session_cascades_its_queue(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn a_session_without_a_row_lists_empty(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot_id = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot_id, None, None)).await;assert!(diff --git a/crates/agent_session/src/outbound/postgres/test/search.rs b/crates/agent_session/src/outbound/postgres/test/search.rsindex 6a42b58428..f934a1acf2 100644--- a/crates/agent_session/src/outbound/postgres/test/search.rs+++ b/crates/agent_session/src/outbound/postgres/test/search.rs@@ -10,7 +10,7 @@ async fn search_snapshot_folds_persisted_acp_instead_of_indexing_protocol_framesuse agent_fold::domain::{model::Author, service::FoldedMessageService};use serde_json::json;- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot, None, None)).await;for content in [@@ -62,7 +62,7 @@ async fn indexing_pages_current_sessions_and_serializes_snapshot_leases(pool: Pguse sqlx::postgres::PgPoolOptions;use std::time::Duration;- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let first = create_session(&repo, new_session(bot, None, None)).await;let second = create_session(&repo, new_session(bot, None, None)).await;@@ -104,7 +104,7 @@ async fn indexing_pages_current_sessions_and_serializes_snapshot_leases(pool: Pg#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn search_metadata_is_scoped_current_and_omits_deleted_sessions(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let search_metadata = AgentSessionSearchMetadataServiceImpl::new(repo.clone());let bot = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot, None, None)).await;diff --git a/crates/agent_session/src/outbound/postgres/test/user_cleanup.rs b/crates/agent_session/src/outbound/postgres/test/user_cleanup.rsindex 5e27fd85ef..70eb192c5d 100644--- a/crates/agent_session/src/outbound/postgres/test/user_cleanup.rs+++ b/crates/agent_session/src/outbound/postgres/test/user_cleanup.rs@@ -11,7 +11,7 @@ use std::sync::Arc;#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn cleanup_batches_remove_all_session_rows_without_a_user_cascade(pool: PgPool) {const OTHER: &str = "macro|[email protected]";- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;insert_user(&pool, OTHER).await;for _ in 0..101 {diff --git a/crates/agent_session/src/outbound/postgres/test/working_branch.rs b/crates/agent_session/src/outbound/postgres/test/working_branch.rsindex a8dfce517e..a138086109 100644--- a/crates/agent_session/src/outbound/postgres/test/working_branch.rs+++ b/crates/agent_session/src/outbound/postgres/test/working_branch.rs@@ -8,7 +8,7 @@ use crate::testing::RecordingRealtime;#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn runtime_branch_survives_without_pr_and_respects_owner_repository_and_fence(pool: PgPool) {- let repo = PgAgentSessionRepo::new(pool.clone());+ let repo = test_repo(&pool);let bot = create_test_bot(&pool).await;let session = create_session(&repo, new_session(bot, None, None)).await;let owner = session.owner_user().unwrap();diff --git a/crates/agent_session/src/outbound/postgres/turn_state.rs b/crates/agent_session/src/outbound/postgres/turn_state.rsindex 064547afe2..cedd8bb63e 100644--- a/crates/agent_session/src/outbound/postgres/turn_state.rs+++ b/crates/agent_session/src/outbound/postgres/turn_state.rs@@ -2,7 +2,7 @@ use super::*;use crate::domain::turn_state::SessionTurnProjectionRepo;use agent_fold::domain::model::TurnState;-impl SessionTurnProjectionRepo for PgAgentSessionRepo {+impl<B: BotFacts + 'static> SessionTurnProjectionRepo for PgAgentSessionRepo<B> {async fn unprojected_sessions(&self, limit: NonZeroUsize) -> Result<Vec<AgentSessionId>> {let ids = sqlx::query_scalar!("SELECT id FROM agent_session WHERE turn_state IS NULL ORDER BY id LIMIT $1",diff --git a/crates/agent_session/src/outbound/postgres/working_branch.rs b/crates/agent_session/src/outbound/postgres/working_branch.rsindex 38a916890d..70150268e7 100644--- a/crates/agent_session/src/outbound/postgres/working_branch.rs+++ b/crates/agent_session/src/outbound/postgres/working_branch.rs@@ -4,7 +4,7 @@ use super::*;use crate::domain::repository_branch::RepositoryBranch;use crate::domain::working_branch::{SessionWorkingBranchRepo, WorkingBranchWrite};-impl SessionWorkingBranchRepo for PgAgentSessionRepo {+impl<B: BotFacts + 'static> SessionWorkingBranchRepo for PgAgentSessionRepo<B> {async fn record_working_branch(&self,session: AgentSessionId,diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.tsindex 1b021a32c3..0e902e3ba3 100644--- a/packages/sdk/generated/agent-harness/types.gen.ts+++ b/packages/sdk/generated/agent-harness/types.gen.ts@@ -742,13 +742,12 @@ export type CreateAgentSessionRequest = {model?: string | null;/*** The user who owns the session. Ignored for user callers, who always- * own their own sessions, and for harness callers, whose verified acting- * user (owner or confirmed team member) owns the session instead;- * required for bot callers without verified acting-user claims.- *- * For bot callers this is a claim, not a verified fact: it is scoped to- * the bot's own sessions, but the named user owns the session on the- * bot's say-so.+ * own their own sessions, for harness callers, whose verified acting+ * user owns the session, and for bots that already act for a verified+ * user. A bot without one may name a user here. That claim is trusted+ * for the bot's own sessions. With no claim, a team bot owns the session+ * itself only while non-user owners are enabled. Every other bot still+ * needs an owner.*/owner?: string | null;/**diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.jsonindex a45a321ced..07293928a5 100644--- a/packages/sdk/specs/agent-harness.json+++ b/packages/sdk/specs/agent-harness.json@@ -2577,7 +2577,7 @@},"owner": {"type": ["string", "null"],- "description": "The user who owns the session. Ignored for user callers, who always\nown their own sessions, and for harness callers, whose verified acting\nuser (owner or confirmed team member) owns the session instead;\nrequired for bot callers without verified acting-user claims.\n\nFor bot callers this is a claim, not a verified fact: it is scoped to\nthe bot's own sessions, but the named user owns the session on the\nbot's say-so."+ "description": "The user who owns the session. Ignored for user callers, who always\nown their own sessions, for harness callers, whose verified acting\nuser owns the session, and for bots that already act for a verified\nuser. A bot without one may name a user here. That claim is trusted\nfor the bot's own sessions. With no claim, a team bot owns the session\nitself only while non-user owners are enabled. Every other bot still\nneeds an owner."},"prompt": {"type": ["string", "null"],diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.tomlindex 0ef6607538..96dc6a6679 100644--- a/services/agent_harness_service/Cargo.toml+++ b/services/agent_harness_service/Cargo.toml@@ -45,6 +45,8 @@ cursor_cloud_agents = { path = "../../crates/cursor_cloud_agents" }claude_cloud_agents = { path = "../../crates/claude_cloud_agents" }database_env_vars = { path = "../../crates/database_env_vars" }entity_access = { path = "../../crates/entity_access" }+entity_registry = { path = "../../crates/entity_registry/entity_registry", default-features = false }+entity_registry_db_utils = { path = "../../crates/entity_registry/entity_registry_db_utils" }futures = { workspace = true }github = { path = "../../crates/github", default-features = false, features = ["outbound",diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rsindex 3256f805ad..4c2e34630a 100644--- a/services/agent_harness_service/src/config.rs+++ b/services/agent_harness_service/src/config.rs@@ -7,6 +7,7 @@use anyhow::Context;use database_env_vars::{DatabaseUrl, RedisUri};+use entity_registry::NonUserOwners;pub use macro_env::Environment;use macro_uuid::Uuid;@@ -40,6 +41,8 @@ macro_env_var::maybe_env_vars!(pub struct ClaudeOauthKmsKeyId;/// Dedicated KMS key for encrypted per-owner Codex OAuth state.pub struct CodexOauthKmsKeyId;+ /// Rollout gate for sessions owned by a bot.+ pub struct EnableNonUserOwners;);/// The Pipedream project environment matching this deployment: production in@@ -186,6 +189,8 @@ pub struct Config {pub github_sync_app_client_id: String,/// PEM private key of that App.pub github_sync_app_pem_secret_key: LocalOrRemoteSecret<GithubSyncAppPemSecretKey>,+ /// Lets a team-scoped bot with no acting user own the sessions it creates.+ pub enable_non_user_owners: EnableNonUserOwners,}impl Config {@@ -220,6 +225,12 @@ impl Config {.filter(|value| !value.trim().is_empty())}+ /// The parsed `ENABLE_NON_USER_OWNERS` gate. Missing is disabled.+ pub fn non_user_owners(&self) -> anyhow::Result<NonUserOwners> {+ NonUserOwners::from_config_value(self.enable_non_user_owners.value())+ .context("ENABLE_NON_USER_OWNERS must be `true` or `false`")+ }+/// Load the configuration from the environment.pub fn from_env() -> anyhow::Result<Self> {macro_config::ConfigLoader::load::<Config>()diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex a251da0e6f..48793cb9bb 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -106,6 +106,8 @@ use connection_gateway_client::ConnectionGatewayClient;use containers::{InMemRuntime, RoutedContainers};use cursor_api_key::cipher::{AwsKmsCiphertexts, KmsCursorApiKeyCipher};use cursor_cloud_agents::api::cursor_api_base_url;+use entity_registry::OwnerGrantPolicy;+use entity_registry_db_utils::OwnedEntityRegistrar;use github::domain::service::{InstallationTokenConfig, InstallationTokenService, ReachableRepositoriesService,};@@ -202,6 +204,7 @@ async fn run() -> anyhow::Result<()> {.resolve_remote_secrets(Environment::new_or_prod(), &secrets).await.context("failed to resolve agent harness service secrets")?;+ let non_user_owners = config.non_user_owners()?;let bot_id = BotId::new_from_uuid(config.harness_bot_id);let enable_dev_commands = matches!(config.environment,@@ -246,7 +249,9 @@ async fn run() -> anyhow::Result<()> {// as in the `document_storage_service` root - a session's actor writes its// log and pushes each frame at the channel's participants so a viewer sees// it happen.- let session_repo = PgAgentSessionRepo::new(pool.clone());+ let session_registrar =+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(pool.clone())));+ let session_repo = PgAgentSessionRepo::new(pool.clone(), session_registrar.clone());let entity_access = Arc::new(entity_access::domain::service::EntityAccessServiceImpl::new(entity_access::outbound::PgAccessRepository::new(pool.clone()),@@ -405,7 +410,10 @@ async fn run() -> anyhow::Result<()> {// through that listener.let egress = Arc::new(EgressServiceImpl::new(- StoredTokenSessionAuthority::new(PgAgentSessionRepo::new(pool.clone())),+ StoredTokenSessionAuthority::new(PgAgentSessionRepo::new(+ pool.clone(),+ session_registrar,+ )),mcp_credentials,GithubAppTokens::new(InstallationTokenService::new(InstallationTokenConfig {@@ -1058,6 +1066,7 @@ async fn run() -> anyhow::Result<()> {),),MacroAuthorizationState::new(Arc::new(authorization_service.clone())),+ non_user_owners,);let routine_sessions = routine_sessions::router((*bots_directory).clone(),diff --git a/services/agent_harness_service/src/trigger.rs b/services/agent_harness_service/src/trigger.rsindex 1b4596199e..67bd48ad62 100644--- a/services/agent_harness_service/src/trigger.rs+++ b/services/agent_harness_service/src/trigger.rs@@ -12,6 +12,8 @@ use agent_trigger::outbound::{};use bots::outbound::pg_bots_repo::PgBotsRepo;use channels::outbound::pg_channels_repo::PgChannelsRepo;+use entity_registry::OwnerGrantPolicy;+use entity_registry_db_utils::OwnedEntityRegistrar;use kafka_util::{GroupName, KafkaEventConsumer, consumer_span, record_span_error};use lexical_client::LexicalClient;use macro_event_broker::{@@ -34,7 +36,7 @@ impl GroupName for AgentTriggerConsumerGroup {/// The concrete trigger service this binary composes.type Trigger = AgentTriggerService<- PgAgentSessionRepo,+ PgAgentSessionRepo<PgBotsRepo>,BotRepoAgentLookup<PgBotsRepo>,BotRepoAgentLookup<PgBotsRepo>,BotRepoAgentLookup<PgBotsRepo>,@@ -97,7 +99,10 @@ async fn run(recorder.clone(),);let trigger = AgentTriggerService::new(- PgAgentSessionRepo::new(pool.clone()),+ PgAgentSessionRepo::new(+ pool.clone(),+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(pool.clone()))),+ ),BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),diff --git a/services/agent_trigger_service/Cargo.toml b/services/agent_trigger_service/Cargo.tomlindex 91a734b48e..ebbdc327a9 100644--- a/services/agent_trigger_service/Cargo.toml+++ b/services/agent_trigger_service/Cargo.toml@@ -19,6 +19,8 @@ bots = { path = "../../crates/bots", default-features = false, features = ["outbchannels = { path = "../../crates/channels", default-features = false, features = ["outbound", "ports"] }database_env_vars = { path = "../../crates/database_env_vars" }entity_access = { path = "../../crates/entity_access" }+entity_registry = { path = "../../crates/entity_registry/entity_registry", default-features = false }+entity_registry_db_utils = { path = "../../crates/entity_registry/entity_registry_db_utils" }kafka_util = { path = "../../crates/kafka_util" }lexical_client = { path = "../../crates/lexical_client" }macro_config = { path = "../../crates/macro_config" }diff --git a/services/agent_trigger_service/src/main.rs b/services/agent_trigger_service/src/main.rsindex fd0362a2aa..ba2f199e6b 100644--- a/services/agent_trigger_service/src/main.rs+++ b/services/agent_trigger_service/src/main.rs@@ -18,6 +18,8 @@ use anyhow::Context as _;use bots::outbound::pg_bots_repo::PgBotsRepo;use channels::outbound::pg_channels_repo::PgChannelsRepo;use config::Config;+use entity_registry::OwnerGrantPolicy;+use entity_registry_db_utils::OwnedEntityRegistrar;use kafka_util::{GroupName, KafkaEventConsumer, consumer_span, record_span_error};use lexical_client::LexicalClient;use macro_entrypoint::{MacroEntrypoint, shutdown_signal};@@ -40,7 +42,7 @@ impl GroupName for AgentTriggerConsumerGroup {/// The concrete trigger service this binary composes.type Trigger = AgentTriggerService<- PgAgentSessionRepo,+ PgAgentSessionRepo<PgBotsRepo>,BotRepoAgentLookup<PgBotsRepo>,BotRepoAgentLookup<PgBotsRepo>,BotRepoAgentLookup<PgBotsRepo>,@@ -95,7 +97,10 @@ async fn run() -> anyhow::Result<()> {recorder.clone(),);let trigger = AgentTriggerService::new(- PgAgentSessionRepo::new(pool.clone()),+ PgAgentSessionRepo::new(+ pool.clone(),+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(pool.clone()))),+ ),BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rsindex 8c3eaf0696..a36008b21f 100644--- a/services/document_storage_service/src/api/context.rs+++ b/services/document_storage_service/src/api/context.rs@@ -76,6 +76,8 @@ use collab_surface::{outbound::pg_collab_surface_repo::PgCollabSurfaceRepo,outbound::surface_init::LexicalSyncSurfaceInitializer,};+use entity_registry::OwnerGrantPolicy;+use entity_registry_db_utils::OwnedEntityRegistrar;use foreign_entity::{domain::service::ForeignEntityServiceImpl, inbound::axum_router::ForeignEntityRouterState,outbound::pg_foreign_entity_repo::PgForeignEntityRepo,@@ -676,7 +678,12 @@ impl From<&ApiContext> for SearchHandlerState {entity_access_service: ctx.entity_access_service.clone(),authorization_state: ctx.authorization_state.clone(),agent_session_search_metadata: Arc::new(AgentSessionSearchMetadataServiceImpl::new(- PgAgentSessionRepo::new(ctx.db.clone()),+ PgAgentSessionRepo::new(+ ctx.db.clone(),+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(+ ctx.db.clone(),+ ))),+ ),))as Arc<dyn AgentSessionSearchMetadataService>,calendar_search_enabled: ctx.config.calendar_search_enabled,diff --git a/services/preview_gateway/Cargo.toml b/services/preview_gateway/Cargo.tomlindex fcefb603e0..f7c8a8b44c 100644--- a/services/preview_gateway/Cargo.toml+++ b/services/preview_gateway/Cargo.toml@@ -14,11 +14,14 @@ agent_preview = { path = "../../crates/agent_preview" }agent_egress = { path = "../../crates/agent_egress" }agent_session = { path = "../../crates/agent_session" }async-trait = { workspace = true }+bots = { path = "../../crates/bots", default-features = false, features = ["outbound", "ports"] }axum = { workspace = true }aws-sdk-secretsmanager = { workspace = true }connection_gateway_client = { path = "../../crates/connection_gateway_client" }database_env_vars = { path = "../../crates/database_env_vars" }entity_access = { path = "../../crates/entity_access" }+entity_registry = { path = "../../crates/entity_registry/entity_registry", default-features = false }+entity_registry_db_utils = { path = "../../crates/entity_registry/entity_registry_db_utils" }macro_auth = { path = "../../crates/macro_auth" }macro_authorization = { path = "../../crates/macro_authorization", default-features = false, features = ["axum", "outbound", "postgres"] }macro_aws_config = { path = "../../crates/macro_aws_config" }diff --git a/services/preview_gateway/src/main.rs b/services/preview_gateway/src/main.rsindex 7d6fc84d5d..52efb315db 100644--- a/services/preview_gateway/src/main.rs+++ b/services/preview_gateway/src/main.rs@@ -81,7 +81,14 @@ async fn run() -> Result<(), rootcause::Report> {app_origin: config.preview_app_origin,},Arc::new(adapters::MacroAuthority {- sessions: agent_session::outbound::postgres::PgAgentSessionRepo::new(pool),+ sessions: agent_session::outbound::postgres::PgAgentSessionRepo::new(+ pool.clone(),+ entity_registry_db_utils::OwnedEntityRegistrar::new(+ entity_registry::OwnerGrantPolicy::new(+ bots::outbound::pg_bots_repo::PgBotsRepo::new(pool),+ ),+ ),+ ),access: access.clone(),}),Arc::new(adapters::Realtime(diff --git a/services/search_processing_service/Cargo.toml b/services/search_processing_service/Cargo.tomlindex 568878518b..82b3f93d5b 100644--- a/services/search_processing_service/Cargo.toml+++ b/services/search_processing_service/Cargo.toml@@ -43,6 +43,9 @@ path = "src/doppler_config.rs"[dependencies]agent_session = { path = "../../crates/agent_session", default-features = false, features = ["outbound"] }+bots = { path = "../../crates/bots", default-features = false, features = ["outbound", "ports"] }+entity_registry = { path = "../../crates/entity_registry/entity_registry", default-features = false }+entity_registry_db_utils = { path = "../../crates/entity_registry/entity_registry_db_utils" }agent_fold = { path = "../../crates/agent_fold" }anyhow = { workspace = true }aws-sdk-dynamodb = { workspace = true }diff --git a/services/search_processing_service/src/main.rs b/services/search_processing_service/src/main.rsindex a64e38b5a6..4157513bca 100644--- a/services/search_processing_service/src/main.rs+++ b/services/search_processing_service/src/main.rs@@ -52,7 +52,9 @@ pub type AgentSessionIndexer = domain::agent_session_index::AgentSessionIndexSeragent_session::domain::search::indexing::SearchSnapshotServiceImpl<agent_session::outbound::postgres::search::PgSearchIndexingRepo,agent_fold::domain::service::FoldedMessageService<- agent_session::outbound::postgres::PgAgentSessionRepo,+ agent_session::outbound::postgres::PgAgentSessionRepo<+ bots::outbound::pg_bots_repo::PgBotsRepo,+ >,>,>,outbound::agent_session_search::OpenSearchAgentSessionIndex,@@ -227,7 +229,14 @@ async fn main() -> anyhow::Result<()> {let sqs_client = Arc::new(sqs_client);- let session_repo = agent_session::outbound::postgres::PgAgentSessionRepo::new(db.clone());+ let session_repo = agent_session::outbound::postgres::PgAgentSessionRepo::new(+ db.clone(),+ entity_registry_db_utils::OwnedEntityRegistrar::new(+ entity_registry::OwnerGrantPolicy::new(bots::outbound::pg_bots_repo::PgBotsRepo::new(+ db.clone(),+ )),+ ),+ );// Waiting advisory locks must not exhaust the pool used to read ACP logs.let session_lock_pool = PgPoolOptions::new().max_connections(10)