Add optional descriptions to agent message board channels (#52183)

## What changed

- Accept an optional `description` in `create_channel` and return it in channel summaries so agents can describe a channel's purpose.
- Enforce a limit of 512 UTF-8 bytes and account for JSON escaping in the output budget before creating the channel.
- Store descriptions in both board backends and migrate existing SQLite databases, leaving older channels without descriptions.

## Testing

Add coverage for UTF-8 byte limits, serialization, output budgets, legacy database migration, and persistence after reopening. Update the model-context scenario to create and list a described channel before posting and reading a message.

GitOrigin-RevId: cf6f395944da23e238e078eefa5de201c8b9c197
This commit is contained in:
jif
2026-10-08 17:25:39 +00:00
committed by copyberry
parent 78a19f5ab5
commit d650bd7c05
11 changed files with 275 additions and 29 deletions
@@ -143,7 +143,9 @@ async fn board_post_and_reads_reach_model_context_without_self_notices(
) -> anyhow::Result<()> {
let server = responses::start_mock_server().await;
let mock = responses::mount_sse_sequence(&server, vec![
tool("post-decision", "post", json!({"new_channel_name":"design", "text":"A shared decision.", "agents_to_notify":["/root"]})),
tool("create-design", "create_channel", json!({"channel_name":"design", "description":"Design decisions and tradeoffs."})),
tool("find-channels", "get_channels", json!({})),
tool("post-decision", "post", json!({"channel_name":"design", "text":"A shared decision.", "agents_to_notify":["/root"]})),
tool("find-decision", "search_posts", json!({"channel_name":"design","query":"decision"})),
done(),
]).await;
@@ -159,15 +161,26 @@ async fn board_post_and_reads_reach_model_context_without_self_notices(
.with_external_time_provider(std::sync::Arc::new(BoardClock::Available))
.build_with_auto_env(&server)
.await?;
test.submit_turn("Record the decision on the board, notify me, and read it.")
.await?;
test.submit_turn(
"Create and describe a design channel, list it, then post and read the decision.",
)
.await?;
let requests = mock.requests();
assert_eq!(requests.len(), 3);
assert_eq!(requests.len(), 5);
assert!(
responses::namespace_child_tool(&requests[0].body_json(), "collaboration", "post")
.is_some()
);
let output = requests[1]
let channel_result: Value = serde_json::from_str(
&requests[2]
.function_call_output_text("find-channels")
.expect("channel list"),
)?;
assert_eq!(
channel_result["results"],
json!([{ "channel_name":"design", "description":"Design decisions and tradeoffs.", "created_at":"2026-09-18T12:00:00Z", "created_by":"/root", "message_count":0, "last_message_id":null }])
);
let output = requests[3]
.function_call_output_text("post-decision")
.expect("post result");
let post: Value =
@@ -175,7 +188,7 @@ async fn board_post_and_reads_reach_model_context_without_self_notices(
assert_eq!(post["author"], "/root");
assert_eq!(post["created_at"], "2026-09-18T12:00:00Z");
let result: Value = serde_json::from_str(
&requests[2]
&requests[4]
.function_call_output_text("find-decision")
.expect("search result"),
)?;
@@ -204,7 +217,7 @@ async fn board_post_and_reads_reach_model_context_without_self_notices(
insta::assert_snapshot!(
"agent_message_board_context",
context_snapshot::format_context_snapshot(
"An active agent posts a shared decision and fetches the text without a self-notification.",
"An active agent describes a channel, lists it, posts a shared decision and reads it without a self-notification.",
&bodies.iter().map(SnapshotEntry::body).collect::<Vec<_>>(),
&ContextSnapshotOptions::default().rewrite_known_segments(),
)
@@ -1,8 +1,8 @@
---
source: core/tests/suite/scenarios_agent_message_board.rs
expression: "context_snapshot::format_context_snapshot(\"An active agent posts a shared decision and fetches the text without a self-notification.\",\n&bodies.iter().map(SnapshotEntry::body).collect::<Vec<_>>(),\n&ContextSnapshotOptions::default().rewrite_known_segments(),)"
expression: "context_snapshot::format_context_snapshot(\"An active agent describes a channel, lists it, posts a shared decision and reads it without a self-notification.\",\n&bodies.iter().map(SnapshotEntry::body).collect::<Vec<_>>(),\n&ContextSnapshotOptions::default().rewrite_known_segments(),)"
---
Scenario: An active agent posts a shared decision and fetches the text without a self-notification.
Scenario: An active agent describes a channel, lists it, posts a shared decision and reads it without a self-notification.
## Window 1
-- request 1 (request) --
@@ -33,10 +33,16 @@ Scenario: An active agent posts a shared decision and fetches the text without a
04:message/user:
<ENVIRONMENT_CONTEXT>
05:message/user:
Record the decision on the board, notify me, and read it.
Create and describe a design channel, list it, then post and read the decision.
-- request 2 (request) --
06:function_call/collaboration.post:{"agents_to_notify":["/root"],"new_channel_name":"design","text":"A shared decision."}
07:function_call_output:{"author":"/root","channel_name":"design","created_at":"2026-09-18T12:00:00Z","message_id":"<UUID 1>","thread_id":"<UUID 1>"}
06:function_call/collaboration.create_channel:{"channel_name":"design","description":"Design decisions and tradeoffs."}
07:function_call_output:{"channel_name":"design","created_at":"2026-09-18T12:00:00Z","created_by":"/root","description":"Design ...tradeoffs.","last_message_id":null,"message_count":0} [hash=48975f3c1a0c0378]
-- request 3 (request) --
08:function_call/collaboration.search_posts:{"channel_name":"design","query":"decision"}
09:function_call_output:{"has_more":false,"n_returned":1,"next_cursor":null,"results":[{"author":"/root","channel_name":"design"...ecision.","thread_id":"<UUID 1>","truncated":false}]} [hash=facdb1e4f66cc5b9]
08:function_call/collaboration.get_channels:{}
09:function_call_output:{"has_more":false,"n_returned":1,"next_cursor":null,"results":[{"channel_name":"design","created_at":"20...adeoffs.","last_message_id":null,"message_count":0}]} [hash=7c1cdfeb5b4b833d]
-- request 4 (request) --
10:function_call/collaboration.post:{"agents_to_notify":["/root"],"channel_name":"design","text":"A shared decision."}
11:function_call_output:{"author":"/root","channel_name":"design","created_at":"2026-09-18T12:00:00Z","message_id":"<UUID 1>","thread_id":"<UUID 1>"}
-- request 5 (request) --
12:function_call/collaboration.search_posts:{"channel_name":"design","query":"decision"}
13:function_call_output:{"has_more":false,"n_returned":1,"next_cursor":null,"results":[{"author":"/root","channel_name":"design"...ecision.","thread_id":"<UUID 1>","truncated":false}]} [hash=facdb1e4f66cc5b9]
@@ -1,4 +1,5 @@
//! Operations on one board. Requests describe intent independently of tool schemas.
//! Channel descriptions enforce their byte limit at construction and deserialization.
use crate::ChannelSummary;
use crate::Page;
@@ -11,6 +12,7 @@ use crate::ThreadSummary;
use codex_protocol::AgentPath;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result;
use futures::future::BoxFuture;
use serde::Deserialize;
@@ -119,9 +121,42 @@ pub enum SubscriptionChange {
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CreateChannelRequest {
pub channel_name: String,
/// Optional channel purpose, at most 512 UTF-8 bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<ChannelDescription>,
pub subscription: SubscriptionChange,
}
/// A channel purpose containing at most 512 UTF-8 bytes.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "String")]
pub struct ChannelDescription(String);
impl TryFrom<String> for ChannelDescription {
type Error = CodexErr;
fn try_from(text: String) -> Result<Self> {
if text.len() > 512 {
return Err(CodexErr::InvalidRequest(
"channel descriptions must contain at most 512 UTF-8 bytes".into(),
));
}
Ok(Self(text))
}
}
impl ChannelDescription {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl From<ChannelDescription> for String {
fn from(description: ChannelDescription) -> Self {
description.0
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChannelQuery {
pub query: Option<String>,
@@ -149,7 +149,13 @@ impl State {
.transpose()
}
fn insert_channel(&mut self, name: &str, author: AgentPath, now: DateTime<Utc>) -> Result<()> {
fn insert_channel(
&mut self,
name: &str,
description: Option<String>,
author: AgentPath,
now: DateTime<Utc>,
) -> Result<()> {
if name.is_empty()
|| name.len() > 128
|| name.trim() != name
@@ -167,6 +173,7 @@ impl State {
Channel {
summary: ChannelSummary {
channel_name: name.to_owned(),
description,
created_at: now,
created_by: author,
message_count: 0,
@@ -206,7 +213,12 @@ impl InMemoryAgentMessageBoard {
let author = self.host.agent_path(caller).await?;
let now = self.host.current_time(caller).await?;
let mut state = self.state.lock().await;
state.insert_channel(&request.channel_name, author, now)?;
state.insert_channel(
&request.channel_name,
request.description.map(String::from),
author,
now,
)?;
if request.subscription == SubscriptionChange::Subscribe {
state.subscribe(
SubscriptionTarget::Channel(request.channel_name.clone()),
@@ -258,7 +270,7 @@ impl InMemoryAgentMessageBoard {
(name.clone(), id, SubscriptionTarget::Channel(name.clone()))
}
PostDestination::NewChannel(name) => {
state.insert_channel(name, author.clone(), now)?;
state.insert_channel(name, /*description*/ None, author.clone(), now)?;
state.subscribe(SubscriptionTarget::Channel(name.clone()), caller);
(name.clone(), id, SubscriptionTarget::Channel(name.clone()))
}
@@ -12,6 +12,7 @@ mod tools;
mod types;
pub use api::AgentMessageBoard;
pub use api::ChannelDescription;
pub use api::ChannelQuery;
pub use api::CreateChannelRequest;
pub use api::PageRequest;
+37 -9
View File
@@ -4,7 +4,9 @@
//! Live handles in this process share one connection pool per database path.
//! Accepted posts survive runtime unload and process restart, but cannot recreate
//! a board after its root has been permanently deleted.
//! Opening storage adds optional channel metadata without invalidating older readers.
use crate::ChannelDescription;
use crate::ChannelSummary;
use crate::CreateChannelRequest;
use crate::MessageBoardHost;
@@ -61,7 +63,7 @@ static POOLS: LazyLock<Mutex<HashMap<PathBuf, Weak<SqlitePool>>>> = LazyLock::ne
const SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS deleted_boards (board TEXT PRIMARY KEY NOT NULL);
CREATE TABLE IF NOT EXISTS channels (
board TEXT NOT NULL, name TEXT NOT NULL, name_search TEXT NOT NULL, created_at TEXT NOT NULL, timestamp INTEGER NOT NULL, author TEXT NOT NULL,
board TEXT NOT NULL, name TEXT NOT NULL, name_search TEXT NOT NULL, created_at TEXT NOT NULL, timestamp INTEGER NOT NULL, author TEXT NOT NULL, description TEXT,
PRIMARY KEY(board,name)
);
CREATE TABLE IF NOT EXISTS posts (
@@ -128,10 +130,27 @@ impl LocalAgentMessageBoard {
.open_read_write_pool(&path)
.await
.map_err(storage_error)?;
sqlx::raw_sql(SCHEMA)
.execute(&pool)
let mut tx = pool
.begin_with("BEGIN IMMEDIATE")
.await
.map_err(storage_error)?;
sqlx::raw_sql(SCHEMA)
.execute(&mut *tx)
.await
.map_err(storage_error)?;
let has_description: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM pragma_table_info('channels') WHERE name='description')",
)
.fetch_one(&mut *tx)
.await
.map_err(storage_error)?;
if !has_description {
sqlx::query("ALTER TABLE channels ADD COLUMN description TEXT")
.execute(&mut *tx)
.await
.map_err(storage_error)?;
}
tx.commit().await.map_err(storage_error)?;
let pool = Arc::new(pool);
pools.insert(path, Arc::downgrade(&pool));
pool
@@ -152,8 +171,14 @@ impl LocalAgentMessageBoard {
let author = self.host.agent_path(caller).await?;
let now = self.host.current_time(caller).await?;
let mut tx = self.begin_write().await?;
self.insert_channel(&mut tx, &request.channel_name, &author, now)
.await?;
self.insert_channel(
&mut tx,
&request.channel_name,
request.description.as_ref().map(ChannelDescription::as_str),
&author,
now,
)
.await?;
if request.subscription == SubscriptionChange::Subscribe {
self.subscribe(
&mut tx,
@@ -234,7 +259,8 @@ impl LocalAgentMessageBoard {
}
PostDestination::NewChannel(channel) => {
validate_channel(channel)?;
self.insert_channel(&mut tx, channel, &author, now).await?;
self.insert_channel(&mut tx, channel, /*description*/ None, &author, now)
.await?;
self.subscribe(
&mut tx,
&SubscriptionTarget::Channel(channel.clone()),
@@ -398,11 +424,12 @@ impl LocalAgentMessageBoard {
&self,
conn: &mut SqliteConnection,
name: &str,
description: Option<&str>,
author: &AgentPath,
now: DateTime<Utc>,
) -> Result<()> {
let inserted = sqlx::query("INSERT OR IGNORE INTO channels(board,name,name_search,created_at,timestamp,author) VALUES(?,?,?,?,?,?)")
.bind(self.identity.to_string()).bind(name).bind(default_case_fold_str(name)).bind(now.to_rfc3339()).bind(now.timestamp_micros()).bind(author.to_string())
let inserted = sqlx::query("INSERT OR IGNORE INTO channels(board,name,name_search,created_at,timestamp,author,description) VALUES(?,?,?,?,?,?,?)")
.bind(self.identity.to_string()).bind(name).bind(default_case_fold_str(name)).bind(now.to_rfc3339()).bind(now.timestamp_micros()).bind(author.to_string()).bind(description)
.execute(conn).await.map_err(storage_error)?.rows_affected();
if inserted == 0 {
return Err(invalid("channel already exists"));
@@ -465,7 +492,7 @@ impl LocalAgentMessageBoard {
name: &str,
) -> Result<ChannelSummary> {
let row = sqlx::query(
"SELECT c.created_at,c.author,
"SELECT c.created_at,c.author,c.description,
(SELECT COUNT(*) FROM posts p WHERE p.board=c.board AND p.channel=c.name) AS message_count,
(SELECT p.id FROM posts p WHERE p.board=c.board AND p.channel=c.name ORDER BY p.timestamp DESC,p.seq DESC LIMIT 1) AS last_message_id
FROM channels c WHERE c.board=? AND c.name=?",
@@ -478,6 +505,7 @@ impl LocalAgentMessageBoard {
.ok_or_else(|| invalid("channel not found in this board"))?;
Ok(ChannelSummary {
channel_name: name.to_string(),
description: row.get("description"),
created_at: DateTime::parse_from_rfc3339(row.get("created_at"))
.map_err(storage_error)?
.with_timezone(&Utc),
+10 -1
View File
@@ -169,15 +169,24 @@ impl BoardTool {
"create_channel" => {
let arguments::CreateChannel {
channel_name,
description,
subscribe,
} = serde_json::from_str(raw).map_err(model_error)?;
self.check_mutation_budget(budget, /*target_path_bytes*/ 0)?;
// JSON can escape each description byte into six output bytes.
let description_budget = description
.as_ref()
.map_or(0, |text| text.as_str().len() * 6);
self.check_mutation_budget(
budget.saturating_sub(description_budget),
/*target_path_bytes*/ 0,
)?;
encode(
board
.create_channel(
caller,
CreateChannelRequest {
channel_name,
description,
subscription: if subscribe.unwrap_or(true) {
SubscriptionChange::Subscribe
} else {
@@ -1,5 +1,6 @@
//! Flat model arguments; runtime identities are supplied by the host.
use crate::ChannelDescription;
use crate::ThreadSort;
use serde::Deserialize;
use std::num::NonZeroU32;
@@ -9,6 +10,7 @@ use uuid::Uuid;
#[serde(deny_unknown_fields)]
pub(super) struct CreateChannel {
pub(super) channel_name: String,
pub(super) description: Option<ChannelDescription>,
pub(super) subscribe: Option<bool>,
}
@@ -28,7 +28,7 @@ pub(super) fn tool(
let (description, fields, required): (&str, &[&str], &[&str]) = match name {
"create_channel" => (
"Create a channel where all agents in this collaboration can read and post messages. You are subscribed to new top-level posts by default.",
&["channel_name", "subscribe"],
&["channel_name", "description", "subscribe"],
&["channel_name"],
),
"get_channels" => (
@@ -97,6 +97,9 @@ pub(super) fn tool(
let mut properties = serde_json::Map::new();
for field in fields {
let schema = match *field {
"description" => {
json!({"type":"string","description":"Optional channel purpose, at most 512 UTF-8 bytes."})
}
"new_channel_name" => {
json!({"type":"string","description":"Create and subscribe to this channel."})
}
@@ -48,6 +48,8 @@ pub struct ThreadSummary {
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChannelSummary {
pub channel_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
pub created_at: DateTime<Utc>,
pub created_by: AgentPath,
pub message_count: usize,
@@ -624,6 +624,7 @@ async fn check_queries_enforce_page_and_preview_caps(backend: Backend) {
root,
CreateChannelRequest {
channel_name: "Straße".into(),
description: None,
subscription: SubscriptionChange::Unsubscribe,
},
)
@@ -656,6 +657,7 @@ async fn check_queries_enforce_page_and_preview_caps(backend: Backend) {
.await
.unwrap();
assert_eq!(channels.results.len(), 1);
assert_eq!(channels.results[0].description, None);
let query = PostQuery {
channel_name: None,
query: Some("STRASSE".into()),
@@ -993,11 +995,22 @@ async fn check_tools_cover_channel_discussions_subscriptions_and_escaped_preview
let created = tool("create_channel")
.handle(board_tool_call(
"create_channel",
json!({"channel_name":"Workflow"}),
json!({"channel_name":"Workflow", "description":"é".repeat(256)}),
))
.await
.unwrap();
let created: ChannelSummary = serde_json::from_str(&created.log_output()).unwrap();
assert_eq!(
created,
ChannelSummary {
channel_name: "Workflow".into(),
description: Some("é".repeat(256)),
created_at: "2026-09-18T12:00:00Z".parse().unwrap(),
created_by: AgentPath::root(),
message_count: 0,
last_message_id: None,
}
);
let channels = tool("get_channels")
.handle(board_tool_call("get_channels", json!({"query":"WORK"})))
.await
@@ -1196,6 +1209,22 @@ async fn check_tools_validate_arguments_deduplicate_calls_and_bound_unicode_resu
limited.truncation_policy = TruncationPolicy::Bytes(1);
assert!(tool(name).handle(limited).await.is_err());
}
assert!(
tool("create_channel")
.handle(call(
"create_channel",
json!({"channel_name":"too-long", "description":"é".repeat(257)}),
))
.await
.is_err()
);
// Escaped descriptions must fit before creation, rather than failing after commit.
let mut small_budget = call(
"create_channel",
json!({"channel_name":"too-small-budget", "description":"\u{1}".repeat(512)}),
);
small_budget.truncation_policy = TruncationPolicy::Bytes(4096);
assert!(tool("create_channel").handle(small_budget).await.is_err());
assert!(
tool("post")
.handle(call(
@@ -1357,3 +1386,109 @@ async fn check_tools_validate_arguments_deduplicate_calls_and_bound_unicode_resu
<= 8000
);
}
#[test]
fn channel_descriptions_validate_construction_and_serialization() {
use serde_json::json;
let description = "é".repeat(256);
let request_json = json!({
"channel_name": "design",
"description": description,
"subscription": "Unsubscribe",
});
let request: CreateChannelRequest = serde_json::from_value(request_json.clone()).unwrap();
assert_eq!(
request.description,
Some(ChannelDescription::try_from(description).unwrap())
);
assert_eq!(serde_json::to_value(request).unwrap(), request_json);
let too_long = "é".repeat(257);
assert!(ChannelDescription::try_from(too_long.clone()).is_err());
assert!(
serde_json::from_value::<CreateChannelRequest>(json!({
"channel_name": "too-long",
"description": too_long,
"subscription": "Unsubscribe",
}))
.is_err()
);
}
#[tokio::test]
async fn channel_descriptions_migrate_legacy_storage_and_survive_reopen() {
let dir = tempfile::tempdir().unwrap();
let sqlite = SqliteConfig::new_for_testing(dir.path().to_path_buf().try_into().unwrap());
let root = ThreadId::new();
let host = Arc::new(Host {
clock: AtomicI64::default(),
agent_path_calls: AtomicUsize::default(),
members: [(root, AgentPath::root())].into(),
active: AtomicBool::new(true),
fail_notifications: AtomicBool::new(false),
notifications: Mutex::default(),
});
let pool = sqlite
.open_read_write_pool(&dir.path().join("agent_message_board_1.sqlite"))
.await
.unwrap();
sqlx::query("CREATE TABLE channels (board TEXT NOT NULL, name TEXT NOT NULL, name_search TEXT NOT NULL, created_at TEXT NOT NULL, timestamp INTEGER NOT NULL, author TEXT NOT NULL, PRIMARY KEY(board,name))").execute(&pool).await.unwrap();
sqlx::query(
"INSERT INTO channels VALUES (?, 'legacy', 'legacy', '2026-09-17T12:00:00Z', 0, '/root')",
)
.bind(root.to_string())
.execute(&pool)
.await
.unwrap();
pool.close().await;
let board = LocalAgentMessageBoard::open(&sqlite, root.into(), host.clone())
.await
.unwrap();
let legacy = ChannelSummary {
channel_name: "legacy".into(),
description: None,
created_at: "2026-09-17T12:00:00Z".parse().unwrap(),
created_by: AgentPath::root(),
message_count: 0,
last_message_id: None,
};
let created = board
.create_channel(
root,
CreateChannelRequest {
channel_name: "design".into(),
description: Some(
"Design decisions and tradeoffs."
.to_string()
.try_into()
.unwrap(),
),
subscription: SubscriptionChange::Unsubscribe,
},
)
.await
.unwrap();
drop(board);
let reopened = LocalAgentMessageBoard::open(&sqlite, root.into(), host)
.await
.unwrap();
let listed = reopened
.list_channels(
root,
ChannelQuery {
query: None,
direction: SortDirection::NewestFirst,
page: PageRequest::default(),
},
)
.await
.unwrap();
assert_eq!(
listed,
Page {
results: vec![created, legacy],
next_cursor: None
}
);
}