Scope Guardian subscriptions to live reviewers (#63357)

## Why

Persisted channel subscriptions could route new evidence to an agent before
its reviewer started. A replacement reviewer conversation for a still-loaded
agent needs to retain the agent's subscriptions and replay its inbox.

## What changed

Keep channel subscriptions and queued evidence references in the live
reviewer's inbox. Replacement conversations reuse that inbox, and a reviewer
that reloads after shutdown starts with an empty inbox and subscription set.

Route committed evidence once per matching inbox, even when several channels
match. Unsubscribing preserves evidence already selected for delivery, and
closing an inbox prevents pending deliveries from reaching a later reviewer
for the same agent.

Manage subscriptions through the reviewer tools. An exact channel name can
be subscribed to before the channel exists, and evidence remains searchable
on the message board.

## Testing

Cover pending delivery across unsubscribe and reviewer reload, and exercise
subscription and delivery behavior with both in-memory and SQLite boards.

GitOrigin-RevId: e3dfbcc7c3f34bd509faa24742cf83d9236ef83a
This commit is contained in:
felixxia-oai
2026-11-23 15:29:37 +00:00
committed by copyberry
parent a4ae34320c
commit e00c64fb68
24 changed files with 654 additions and 589 deletions
+17 -20
View File
@@ -22,6 +22,8 @@ use std::num::NonZeroU32;
use std::sync::Arc;
use uuid::Uuid;
const MAX_CHANNEL_BYTES: usize = 128;
// Local and remote implementations must remain usable through the same handle.
const _: Option<&dyn AgentMessageBoard> = None;
@@ -89,16 +91,6 @@ pub trait AgentMessageBoard: Send + Sync {
request: AppendRequest,
) -> BoxFuture<'_, Result<PostMetadata>>;
/// Like a silent append, also returns the subscribers at the moment of insertion.
/// An idempotent retry returns the existing post and no new deliveries.
fn append_with_subscribers(
&self,
_caller: ThreadId,
_request: AppendRequest,
) -> BoxFuture<'_, Result<(PostMetadata, Vec<ThreadId>)>> {
unsupported("appending with subscribers")
}
fn list_threads(
&self,
caller: ThreadId,
@@ -142,15 +134,6 @@ pub trait AgentMessageBoard: Send + Sync {
caller: ThreadId,
request: SubscriptionRequest,
) -> BoxFuture<'_, Result<SubscriptionState>>;
/// List a caller's current channel subscriptions on a live board.
fn subscribed_channels(
&self,
_caller: ThreadId,
_page: PageRequest,
) -> BoxFuture<'_, Result<Page<String>>> {
unsupported("listing channel subscriptions")
}
}
fn unsupported<T>(operation: &'static str) -> BoxFuture<'static, Result<T>> {
@@ -184,6 +167,21 @@ pub enum SubscriptionChange {
Unsubscribe,
}
/// Checks whether a name is valid for channel creation, independent of board contents.
pub fn validate_channel(name: &str) -> Result<()> {
if name.is_empty()
|| name.len() > MAX_CHANNEL_BYTES
|| name.trim() != name
|| name.chars().any(char::is_control)
{
return Err(CodexErr::InvalidRequest(
"channel names must contain 1–128 bytes without edge whitespace or control characters"
.into(),
));
}
Ok(())
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CreateChannelRequest {
pub channel_name: String,
@@ -260,7 +258,6 @@ pub struct PostRequest {
pub(crate) enum PostBehavior {
Discussion,
SilentAppend,
SilentAppendWithSubscribers,
}
/// Request to append evidence without subscribing its author or notifying anyone.
+2 -14
View File
@@ -18,6 +18,7 @@ use crate::SubscriptionState;
use crate::SubscriptionTarget;
use crate::UpsertChannelRequest;
use crate::api::PostBehavior;
use crate::validate_channel;
use caseless::default_case_fold_str;
use chrono::DateTime;
use chrono::Utc;
@@ -35,7 +36,7 @@ use std::sync::Weak;
use tokio::sync::Mutex;
use uuid::Uuid;
mod queries;
pub(crate) mod queries;
#[cfg(test)]
#[path = "in_memory_tests.rs"]
@@ -467,19 +468,6 @@ impl InMemoryAgentMessageBoard {
}
}
fn validate_channel(name: &str) -> Result<()> {
if name.is_empty()
|| name.len() > 128
|| name.trim() != name
|| name.chars().any(char::is_control)
{
return Err(invalid(
"channel names must contain 1–128 bytes without edge whitespace or control characters",
));
}
Ok(())
}
fn invalid(message: impl Into<String>) -> CodexErr {
CodexErr::InvalidRequest(message.into())
}
@@ -270,7 +270,8 @@ impl AgentMessageBoard for InMemoryAgentMessageBoard {
}
}
fn page<T>(request: &PageRequest, results: Vec<T>) -> Result<Page<T>> {
/// Paginate an ordered collection with the board's cursor format and page limit.
pub fn page<T>(request: &PageRequest, results: impl IntoIterator<Item = T>) -> Result<Page<T>> {
let offset = match &request.cursor {
Some(cursor) => {
let mut bytes = [0; 4];
+2
View File
@@ -29,10 +29,12 @@ pub use api::SubscriptionTarget;
pub use api::ThreadQuery;
pub use api::ThreadSort;
pub use api::UpsertChannelRequest;
pub use api::validate_channel;
pub use host::MessageBoardHost;
pub use host::NotificationDelivery;
pub use in_memory::InMemoryAgentMessageBoard;
pub use in_memory::InMemoryMessageBoards;
pub use in_memory::queries::page as paginate;
pub use local::LocalAgentMessageBoard;
pub use local::connection::LocalBoard;
pub use local::connection::LocalBoardConnection;
+10 -40
View File
@@ -23,6 +23,7 @@ use crate::SubscriptionRequest;
use crate::SubscriptionState;
use crate::SubscriptionTarget;
use crate::api::PostBehavior;
use crate::validate_channel;
use caseless::default_case_fold_str;
use chrono::DateTime;
use chrono::Utc;
@@ -58,7 +59,6 @@ mod subscriptions;
mod pools_tests;
const MAX_POST_BYTES: usize = 64 * 1024;
const MAX_CHANNEL_BYTES: usize = 128;
const MAX_READ_CHARS: usize = 20_000;
#[derive(Clone)]
@@ -169,28 +169,13 @@ impl LocalAgentMessageBoard {
/// into a recipient's later turn. Once committed, notification failures are
/// logged without failing the post; the persisted content remains readable.
pub async fn post(&self, caller: ThreadId, request: PostRequest) -> Result<PostMetadata> {
Ok(self
.write(caller, request, PostBehavior::Discussion)
.await?
.0)
self.write(caller, request, PostBehavior::Discussion).await
}
/// Appends evidence without automatic subscriptions or notifications, even on a discussion board.
/// Uses the same access checks, caller-scoped request IDs and durable write path as posting.
/// Reusing a request ID for a different payload or operation is an error.
pub async fn append(&self, caller: ThreadId, request: AppendRequest) -> Result<PostMetadata> {
Ok(self
.write_append(caller, request, PostBehavior::SilentAppend)
.await?
.0)
}
async fn write_append(
&self,
caller: ThreadId,
request: AppendRequest,
behavior: PostBehavior,
) -> Result<(PostMetadata, Vec<ThreadId>)> {
self.write(
caller,
PostRequest {
@@ -199,7 +184,7 @@ impl LocalAgentMessageBoard {
text: request.text,
agents_to_notify: Vec::new(),
},
behavior,
PostBehavior::SilentAppend,
)
.await
}
@@ -209,7 +194,7 @@ impl LocalAgentMessageBoard {
caller: ThreadId,
request: PostRequest,
behavior: PostBehavior,
) -> Result<(PostMetadata, Vec<ThreadId>)> {
) -> Result<PostMetadata> {
if let Some(access) = self.access {
access.require_write(
self.identity,
@@ -230,7 +215,7 @@ impl LocalAgentMessageBoard {
caller: ThreadId,
request: PostRequest,
behavior: PostBehavior,
) -> Result<(PostMetadata, Vec<ThreadId>)> {
) -> Result<PostMetadata> {
if request.text.len() > MAX_POST_BYTES
|| request.text.is_empty()
|| request.request_id.is_empty()
@@ -246,9 +231,7 @@ impl LocalAgentMessageBoard {
let request_json = match behavior {
// Keep existing post fingerprints compatible with persisted retries.
PostBehavior::Discussion => serde_json::to_string(&request),
PostBehavior::SilentAppend | PostBehavior::SilentAppendWithSubscribers => {
serde_json::to_string(&("append", &request))
}
PostBehavior::SilentAppend => serde_json::to_string(&("append", &request)),
}
.map_err(storage_error)?;
let mut conn = self.pool.acquire().await.map_err(storage_error)?;
@@ -256,7 +239,7 @@ impl LocalAgentMessageBoard {
.existing_post(&mut conn, &request_id, &request_json)
.await?
{
return Ok((post.metadata, Vec::new()));
return Ok(post.metadata);
}
drop(conn);
let notify_recipients = if behavior == PostBehavior::Discussion {
@@ -274,7 +257,7 @@ impl LocalAgentMessageBoard {
.existing_post(&mut tx, &request_id, &request_json)
.await?
{
return Ok((post.metadata, Vec::new()));
return Ok(post.metadata);
}
let id = Uuid::now_v7();
let (channel, root, target) = match &request.destination {
@@ -371,7 +354,7 @@ impl LocalAgentMessageBoard {
tx.commit().await.map_err(storage_error)?;
let Some(mut recipients) = notify_recipients else {
return Ok((post.metadata, subscribers));
return Ok(post.metadata);
};
recipients.extend(subscribers);
recipients.remove(&caller);
@@ -387,7 +370,7 @@ impl LocalAgentMessageBoard {
}
})
.await;
Ok((post.metadata, Vec::new()))
Ok(post.metadata)
}
pub async fn set_subscription(
@@ -503,19 +486,6 @@ async fn insert_channel(
Ok(())
}
fn validate_channel(name: &str) -> Result<()> {
if name.is_empty()
|| name.len() > MAX_CHANNEL_BYTES
|| name.trim() != name
|| name.chars().any(char::is_control)
{
return Err(invalid(
"channel names must contain 1–128 bytes without edge whitespace or control characters",
));
}
Ok(())
}
fn invalid(message: impl Into<String>) -> CodexErr {
CodexErr::InvalidRequest(message.into())
}
@@ -127,31 +127,6 @@ impl LocalAgentMessageBoard {
.execute(&mut *tx).await.map_err(storage_error)?;
tx.commit().await.map_err(storage_error)
}
/// Lists the caller's channel subscriptions within the existing page budget.
pub async fn subscribed_channels(
&self,
caller: ThreadId,
page: PageRequest,
) -> Result<Page<String>> {
self.host.agent_path(caller).await?;
let window = Window::new(&page)?;
// Probe the existing subscriptions primary key for each channel.
let channels = sqlx::query_scalar::<_, String>(
"SELECT c.name FROM channels AS c WHERE c.board=? AND EXISTS (
SELECT 1 FROM subscriptions AS s
WHERE s.board=c.board AND s.target=json_object('Channel',c.name) AND s.agent=?
) ORDER BY c.name LIMIT ? OFFSET ?",
)
.bind(self.identity.to_string())
.bind(caller.to_string())
.bind((window.limit + 1) as i64)
.bind(window.offset())
.fetch_all(self.pool.as_ref())
.await
.map_err(storage_error)?;
window.finish(channels)
}
}
impl AgentMessageBoard for LocalAgentMessageBoard {
@@ -202,18 +177,6 @@ impl AgentMessageBoard for LocalAgentMessageBoard {
Box::pin(LocalAgentMessageBoard::append(self, caller, request))
}
fn append_with_subscribers(
&self,
caller: ThreadId,
request: AppendRequest,
) -> BoxFuture<'_, Result<(PostMetadata, Vec<ThreadId>)>> {
Box::pin(self.write_append(
caller,
request,
crate::api::PostBehavior::SilentAppendWithSubscribers,
))
}
fn set_subscription(
&self,
caller: ThreadId,
@@ -224,16 +187,6 @@ impl AgentMessageBoard for LocalAgentMessageBoard {
))
}
fn subscribed_channels(
&self,
caller: ThreadId,
page: PageRequest,
) -> BoxFuture<'_, Result<Page<String>>> {
Box::pin(LocalAgentMessageBoard::subscribed_channels(
self, caller, page,
))
}
fn read_post_texts_by_id<'a>(
&'a self,
caller: ThreadId,
-10
View File
@@ -106,7 +106,6 @@ impl<'call> ToolExecutor<ToolCall<'call>> for BoardTool {
}
fn supports_parallel_tool_calls(&self) -> bool {
MessageBoardTool::READ_ONLY.contains(&self.tool)
|| self.tool == MessageBoardTool::SubscribedChannels
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> ToolExecutorFuture<'a>
@@ -220,15 +219,6 @@ impl BoardTool {
})
.await
}
MessageBoardTool::SubscribedChannels => {
let arguments::SubscribedChannels { limit, cursor } =
serde_json::from_str(raw).map_err(model_error)?;
let limit = page_limit(limit);
bounded_read(budget, limit, |scale| {
board.subscribed_channels(caller, page(limit, cursor.clone(), scale))
})
.await
}
MessageBoardTool::ListThreads => {
let arguments::ListThreads {
channel_name,
@@ -63,13 +63,6 @@ pub(super) struct ReadPost {
pub(super) limit_chars: Option<NonZeroU32>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct SubscribedChannels {
pub(super) limit: Option<NonZeroU32>,
pub(super) cursor: Option<String>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct Subscription {
@@ -12,8 +12,6 @@ pub enum MessageBoardTool {
SearchPosts,
ReadThread,
ReadPost,
/// Lists the caller's own subscriptions on a live board.
SubscribedChannels,
Subscribe,
Unsubscribe,
/// Posts, subscribes the author unless opted out, and notifies recipients.
@@ -63,7 +61,6 @@ impl MessageBoardTool {
Self::SearchPosts => "search_posts",
Self::ReadThread => "read_thread",
Self::ReadPost => "read_post",
Self::SubscribedChannels => "subscribed_channels",
Self::Subscribe => "subscribe",
Self::Unsubscribe => "unsubscribe",
Self::Post => "post",
-5
View File
@@ -65,11 +65,6 @@ pub(super) fn tool(
&["message_id", "offset_chars", "limit_chars"],
&["message_id"],
),
MessageBoardTool::SubscribedChannels => (
"List the names of channels you are currently subscribed to.",
&["limit", "cursor"],
&[],
),
MessageBoardTool::Subscribe => (
"Subscribe yourself or another agent to a channel for new top-level posts, or to a thread for replies. Provide exactly one of channel_name or thread_id. Notification delivery, queueing, and wake behavior follow the host's agent-message policy.",
&["channel_name", "thread_id", "target_agent"],