aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,14 @@
load("//:defs.bzl", "codex_rust_crate")
exports_files(
["tests/common/mod.rs"],
visibility = [
"//akode-rs/core:__pkg__",
"//akode-rs/ext/guardian-v3:__pkg__",
],
)
codex_rust_crate(
name = "message-board",
crate_name = "akode_message_board",
)

View File

@@ -0,0 +1,37 @@
[package]
edition.workspace = true
license.workspace = true
name = "akode-message-board"
version.workspace = true
[lib]
name = "akode_message_board"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
base64 = { workspace = true }
caseless = { workspace = true }
chrono = { workspace = true, features = ["serde"] }
akode-protocol = { workspace = true }
akode-state = { workspace = true }
akode-tools = { workspace = true }
futures = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
sqlx = { workspace = true }
tokio = { workspace = true, features = ["fs", "rt", "sync"] }
tracing = { workspace = true }
uuid = { workspace = true, features = ["serde", "v7"] }
[dev-dependencies]
akode-attachment-store = { workspace = true }
akode-message-board-mcp = { workspace = true }
akode-utils-output-truncation = { workspace = true }
pretty_assertions = { workspace = true }
rmcp = { workspace = true, features = ["client", "server", "transport-async-rw"] }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["io-util", "macros", "rt-multi-thread"] }

View File

@@ -0,0 +1,316 @@
//! Operations on one board. Requests describe intent independently of tool schemas.
//! Channel descriptions enforce their byte limit at construction and deserialization.
use crate::BoardReadView;
use crate::ChannelPage;
use crate::ChannelSummary;
use crate::Page;
use crate::PostContent;
use crate::PostMetadata;
use crate::PostPreview;
use crate::SubscriptionState;
use crate::ThreadPage;
use crate::ThreadSummary;
use akode_protocol::AgentPath;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result;
use futures::future::BoxFuture;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeMap;
use std::num::NonZeroU32;
use std::sync::Arc;
use uuid::Uuid;
// Local and remote implementations must remain usable through the same handle.
const _: Option<&dyn AgentMessageBoard> = None;
/// Stores discussions and subscriptions for one board.
///
/// Every operation validates caller membership. IDs are scoped to this board;
/// an agent runtime's ThreadId is distinct from a discussion's root post UUID.
/// Mutation success acknowledges acceptance, not that recipients read a post.
/// Implementations enforce hard input/output limits and return backend failures
/// as errors. They own atomic subscription changes, posting and recipient
/// selection, excluding the post author even when explicitly targeted.
/// Notification delivery follows the host's scheduling and wake policy and may
/// be buffered for an idle recipient; see [`crate::MessageBoardHost`].
///
/// Boxed Send futures support an Arc<dyn AgentMessageBoard>, like AgentControl.
pub trait AgentMessageBoard: Send + Sync {
fn identity(&self) -> SessionId;
/// The host-selected storage namespace, if this backend identifies one.
fn storage_namespace(&self) -> Option<&str> {
None
}
/// Capture a live board's channel summaries and post boundary together for read-only access.
fn read_view(&self, _caller: ThreadId) -> BoxFuture<'_, Result<Arc<dyn BoardReadView>>> {
unsupported("capturing a board read view")
}
fn create_channel(
&self,
caller: ThreadId,
request: CreateChannelRequest,
) -> BoxFuture<'_, Result<ChannelSummary>>;
/// Creates a channel or replaces only its description. Preserves existing
/// posts, authorship, creation time and subscriptions; never sends notices.
/// Backends without upsert support must reject this rather than substitute creation.
fn upsert_channel(
&self,
caller: ThreadId,
request: UpsertChannelRequest,
) -> BoxFuture<'_, Result<()>>;
fn list_channels(
&self,
caller: ThreadId,
query: ChannelQuery,
) -> BoxFuture<'_, Result<ChannelPage>>;
/// Uses the caller's configured clock; clock failures must not create a post.
/// The request ID identifies a logical call across retries. A retry with
/// different input is an error; a successful retry returns the same metadata.
/// Creating a channel while posting also subscribes its author to new roots there.
fn post(&self, caller: ThreadId, request: PostRequest) -> BoxFuture<'_, Result<PostMetadata>>;
/// Writes without automatic subscriptions or notifications. Uses caller-scoped
/// retry IDs shared with posting; changing the operation or payload is an error.
/// Backends without silent-write support must reject this, never fall back to posting.
fn append(
&self,
caller: ThreadId,
request: AppendRequest,
) -> BoxFuture<'_, Result<PostMetadata>>;
fn list_threads(
&self,
caller: ThreadId,
query: ThreadQuery,
) -> BoxFuture<'_, Result<Page<ThreadSummary>>>;
fn search_posts(
&self,
caller: ThreadId,
query: PostQuery,
) -> BoxFuture<'_, Result<Page<PostPreview>>>;
fn read_thread(
&self,
caller: ThreadId,
request: ReadThreadRequest,
) -> BoxFuture<'_, Result<ThreadPage>>;
fn read_post(
&self,
caller: ThreadId,
request: ReadPostRequest,
) -> BoxFuture<'_, Result<PostContent>>;
/// Channel subscriptions concern new roots; thread subscriptions concern
/// replies. Changing one does not change the other. Any member may change
/// another member's subscription. Posting subscribes its author to the thread
/// by default, but preserves an explicit unsubscribe until subscribed again.
fn set_subscription(
&self,
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")
}
/// Set the caller's membership in the supplied channels as one atomic change.
/// Other channels and thread subscriptions retain their current membership.
fn set_subscriptions<'a>(
&'a self,
_caller: ThreadId,
_channels: &'a BTreeMap<&str, SubscriptionChange>,
) -> BoxFuture<'a, Result<()>> {
unsupported("setting channel subscriptions in bulk")
}
}
fn unsupported<T>(operation: &'static str) -> BoxFuture<'static, Result<T>> {
Box::pin(async move { Err(CodexErr::UnsupportedOperation(operation.into())) })
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PageRequest {
pub cursor: Option<String>,
pub limit: NonZeroU32,
}
impl Default for PageRequest {
fn default() -> Self {
Self {
cursor: None,
limit: NonZeroU32::new(20).unwrap_or(NonZeroU32::MIN),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SortDirection {
NewestFirst,
OldestFirst,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SubscriptionChange {
Subscribe,
Unsubscribe,
}
#[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,
}
/// Creates or updates navigation metadata without changing stored evidence or delivery.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UpsertChannelRequest {
pub channel_name: String,
pub description: ChannelDescription,
}
/// 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>,
pub direction: SortDirection,
pub page: PageRequest,
}
/// Exactly one destination; discussion threads use their root post's ID.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum PostDestination {
Channel(String),
NewChannel(String),
Thread(Uuid),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PostRequest {
/// Host-generated tool invocation identity, never a model argument.
pub request_id: String,
pub destination: PostDestination,
pub text: String,
/// Resolved paths in this board's tree; duplicates notify only once.
pub agents_to_notify: Vec<AgentPath>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum PostBehavior {
Discussion,
SilentAppend,
}
/// Request to append evidence without subscribing its author or notifying anyone.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AppendRequest {
/// Caller-scoped invocation identity, shared with posting to reject conflicting retries.
pub request_id: String,
pub destination: PostDestination,
pub text: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ThreadSort {
Created,
Activity,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ThreadQuery {
pub channel_name: String,
pub sort: ThreadSort,
pub direction: SortDirection,
pub page: PageRequest,
pub max_chars_per_post: NonZeroU32,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PostQuery {
pub channel_name: Option<String>,
pub query: Option<String>,
pub after_message_id: Option<Uuid>,
pub author: Option<AgentPath>,
pub page: PageRequest,
pub max_chars_per_post: NonZeroU32,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReadThreadRequest {
pub thread_id: Uuid,
pub page: PageRequest,
pub max_chars_per_post: NonZeroU32,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ReadPostRequest {
pub message_id: Uuid,
/// Offsets and lengths count Unicode scalar values, not UTF-8 bytes.
pub offset_chars: u32,
pub limit_chars: NonZeroU32,
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum SubscriptionTarget {
Channel(String),
Thread(Uuid),
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SubscriptionRequest {
pub target: SubscriptionTarget,
/// None changes the caller's subscription.
pub target_agent: Option<AgentPath>,
pub change: SubscriptionChange,
}

View File

@@ -0,0 +1,38 @@
//! Host capabilities needed by a board without depending on akode-core.
use crate::PostPreview;
use chrono::DateTime;
use chrono::Utc;
use akode_protocol::AgentPath;
use akode_protocol::ThreadId;
use akode_protocol::error::Result;
use futures::future::BoxFuture;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NotificationDelivery {
Accepted,
SkippedInactive,
}
/// Board-scoped membership, clock and notification access supplied by the host.
///
/// The host remains authoritative for membership even when runtimes are unloaded.
/// Clock reads use the posting agent's configured source, including simulated
/// time. Notifications follow the host's ordinary queue-only agent-message
/// scheduling and wake policy, and may be buffered for an idle recipient.
/// Acceptance does not guarantee that the model has consumed the notification.
/// Backends may implement these capabilities with local handles or remote RPCs.
pub trait MessageBoardHost: Send + Sync {
fn agent_path(&self, caller: ThreadId) -> BoxFuture<'_, Result<AgentPath>>;
fn resolve_agent(&self, path: AgentPath) -> BoxFuture<'_, Result<ThreadId>>;
fn current_time(&self, caller: ThreadId) -> BoxFuture<'_, Result<DateTime<Utc>>>;
/// Push metadata and a bounded preview. Full content is retrieved through bounded reads.
fn notify(
&self,
recipient: ThreadId,
post: PostPreview,
) -> BoxFuture<'_, Result<NotificationDelivery>>;
}

View File

@@ -0,0 +1,485 @@
//! Tree-owned message boards for training. Agent handles share state; nothing is written to disk.
//! Mutations and recipient selection are atomic. Host callbacks run outside the state lock.
//! Silent appends share the write path without changing subscriptions or delivering notices.
//! Channel upserts only change descriptions of existing channels.
//! Opening a board prunes registry entries whose state has been released.
use crate::AppendRequest;
use crate::ChannelSummary;
use crate::CreateChannelRequest;
use crate::MessageBoardHost;
use crate::PostDestination;
use crate::PostMetadata;
use crate::PostPreview;
use crate::PostRequest;
use crate::SubscriptionChange;
use crate::SubscriptionRequest;
use crate::SubscriptionState;
use crate::SubscriptionTarget;
use crate::UpsertChannelRequest;
use crate::api::PostBehavior;
use caseless::default_case_fold_str;
use chrono::DateTime;
use chrono::Utc;
use akode_protocol::AgentPath;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result;
use futures::StreamExt;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::Weak;
use tokio::sync::Mutex;
use uuid::Uuid;
mod queries;
#[cfg(test)]
#[path = "in_memory_tests.rs"]
mod tests;
/// Shares board state across a tree while giving each agent its own host handle.
#[derive(Default)]
pub struct InMemoryMessageBoards {
states: Mutex<HashMap<SessionId, Weak<Mutex<State>>>>,
}
impl InMemoryMessageBoards {
pub async fn open(
&self,
identity: SessionId,
host: Arc<dyn MessageBoardHost>,
) -> InMemoryAgentMessageBoard {
let mut states = self.states.lock().await;
states.retain(|_, state| state.strong_count() > 0);
let entry = states.entry(identity).or_default();
let state = entry.upgrade().unwrap_or_else(|| {
let state = Arc::default();
*entry = Arc::downgrade(&state);
state
});
InMemoryAgentMessageBoard {
identity,
host,
state,
}
}
}
/// A board held in memory for one training rollout.
/// The last handle releases its state; there is no persistence or recovery.
#[derive(Clone)]
pub struct InMemoryAgentMessageBoard {
identity: SessionId,
host: Arc<dyn MessageBoardHost>,
state: Arc<Mutex<State>>,
}
#[derive(Default)]
struct State {
channels: HashMap<String, Channel>,
posts: Vec<Post>,
by_id: HashMap<Uuid, usize>,
requests: HashMap<(ThreadId, String), usize>,
subscriptions: BTreeMap<SubscriptionTarget, HashMap<ThreadId, SubscriptionChange>>,
}
struct Channel {
summary: ChannelSummary,
search: String,
posts: Vec<usize>,
roots: Vec<usize>,
}
struct Post {
metadata: PostMetadata,
request: PostRequest,
behavior: PostBehavior,
search: String,
n_chars: usize,
replies: Vec<usize>,
latest_reply: Option<usize>,
}
impl Post {
fn preview(&self, max_chars: usize) -> PostPreview {
PostPreview {
metadata: self.metadata.clone(),
text_preview: self.request.text.chars().take(max_chars).collect(),
n_chars: self.n_chars,
truncated: self.n_chars > max_chars,
}
}
}
impl State {
fn post_index(&self, id: Uuid) -> Result<usize> {
self.by_id
.get(&id)
.copied()
.ok_or_else(|| invalid("post not found in this board"))
}
fn thread_index(&self, id: Uuid) -> Result<usize> {
let index = self.post_index(id)?;
if self.posts[index].metadata.thread_id != id {
return Err(invalid("thread_id must identify a top-level post"));
}
Ok(index)
}
fn key(&self, index: usize) -> (i64, usize) {
(
self.posts[index].metadata.created_at.timestamp_micros(),
index,
)
}
fn existing_post(
&self,
caller: ThreadId,
request: &PostRequest,
behavior: PostBehavior,
) -> Result<Option<PostMetadata>> {
self.requests
.get(&(caller, request.request_id.clone()))
.map(|index| {
let post = &self.posts[*index];
if post.request != *request || post.behavior != behavior {
return Err(invalid("request ID was already used for a different post"));
}
Ok(post.metadata.clone())
})
.transpose()
}
fn insert_channel(
&mut self,
name: &str,
description: Option<String>,
author: AgentPath,
now: DateTime<Utc>,
) -> Result<()> {
validate_channel(name)?;
if self.channels.contains_key(name) {
return Err(invalid("channel already exists"));
}
self.channels.insert(
name.to_owned(),
Channel {
summary: ChannelSummary {
permissions: None,
channel_name: name.to_owned(),
description,
created_at: now,
created_by: author,
message_count: 0,
last_message_id: None,
},
search: default_case_fold_str(name),
posts: Vec::new(),
roots: Vec::new(),
},
);
Ok(())
}
fn subscribe(&mut self, target: SubscriptionTarget, caller: ThreadId) {
self.subscriptions
.entry(target)
.or_default()
.entry(caller)
.or_insert(SubscriptionChange::Subscribe);
}
}
impl InMemoryAgentMessageBoard {
pub fn new(identity: SessionId, host: Arc<dyn MessageBoardHost>) -> Self {
Self {
identity,
host,
state: Arc::default(),
}
}
async fn create_channel(
&self,
caller: ThreadId,
request: CreateChannelRequest,
) -> Result<ChannelSummary> {
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,
request.description.map(String::from),
author,
now,
)?;
if request.subscription == SubscriptionChange::Subscribe {
state.subscribe(
SubscriptionTarget::Channel(request.channel_name.clone()),
caller,
);
}
Ok(state.channels[&request.channel_name].summary.clone())
}
async fn upsert_channel(&self, caller: ThreadId, request: UpsertChannelRequest) -> Result<()> {
validate_channel(&request.channel_name)?;
let author = self.host.agent_path(caller).await?;
{
let mut state = self.state.lock().await;
if let Some(channel) = state.channels.get_mut(&request.channel_name) {
channel.summary.description = Some(request.description.into());
return Ok(());
}
}
// Fetch insertion metadata without holding the state lock, then recheck
// in case another caller created the channel while the clock was pending.
let now = self.host.current_time(caller).await?;
let mut state = self.state.lock().await;
if let Some(channel) = state.channels.get_mut(&request.channel_name) {
channel.summary.description = Some(request.description.into());
Ok(())
} else {
state.insert_channel(
&request.channel_name,
Some(request.description.into()),
author,
now,
)
}
}
async fn post(&self, caller: ThreadId, request: PostRequest) -> Result<PostMetadata> {
self.write(caller, request, PostBehavior::Discussion).await
}
async fn append(&self, caller: ThreadId, request: AppendRequest) -> Result<PostMetadata> {
self.write(
caller,
PostRequest {
request_id: request.request_id,
destination: request.destination,
text: request.text,
agents_to_notify: Vec::new(),
},
PostBehavior::SilentAppend,
)
.await
}
async fn write(
&self,
caller: ThreadId,
request: PostRequest,
behavior: PostBehavior,
) -> Result<PostMetadata> {
// Accepted writes and their one-time fanout outlive cancellation of the tool call.
let board = self.clone();
tokio::spawn(async move { board.post_inner(caller, request, behavior).await })
.await
.map_err(|error| CodexErr::Io(std::io::Error::other(error)))?
}
async fn post_inner(
&self,
caller: ThreadId,
request: PostRequest,
behavior: PostBehavior,
) -> Result<PostMetadata> {
if request.text.is_empty()
|| request.text.len() > 64 * 1024
|| request.request_id.is_empty()
|| request.request_id.len() > 512
|| request.agents_to_notify.len() > 256
{
return Err(invalid(
"post text, request ID or recipient count exceeds the board limits",
));
}
let author = self.host.agent_path(caller).await?;
if let Some(post) = self
.state
.lock()
.await
.existing_post(caller, &request, behavior)?
{
return Ok(post);
}
let mut recipients = HashSet::new();
for path in &request.agents_to_notify {
recipients.insert(self.host.resolve_agent(path.clone()).await?);
}
let now = self.host.current_time(caller).await?;
let (metadata, notice) = {
let mut state = self.state.lock().await;
if let Some(post) = state.existing_post(caller, &request, behavior)? {
return Ok(post);
}
let id = Uuid::now_v7();
let (channel_name, root, target) = match &request.destination {
PostDestination::Channel(name) => {
if !state.channels.contains_key(name) {
return Err(invalid("channel not found in this board"));
}
(name.clone(), id, SubscriptionTarget::Channel(name.clone()))
}
PostDestination::NewChannel(name) => {
state.insert_channel(name, /*description*/ None, author.clone(), now)?;
if behavior == PostBehavior::Discussion {
state.subscribe(SubscriptionTarget::Channel(name.clone()), caller);
}
(name.clone(), id, SubscriptionTarget::Channel(name.clone()))
}
PostDestination::Thread(root) => {
let index = state.thread_index(*root)?;
(
state.posts[index].metadata.channel_name.clone(),
*root,
SubscriptionTarget::Thread(*root),
)
}
};
if behavior == PostBehavior::Discussion
&& let Some(subscribers) = state.subscriptions.get(&target)
{
recipients.extend(subscribers.iter().filter_map(|(agent, change)| {
(*change == SubscriptionChange::Subscribe).then_some(*agent)
}));
}
recipients.remove(&caller);
let metadata = PostMetadata {
message_id: id,
channel_name: channel_name.clone(),
author,
thread_id: root,
created_at: now,
};
let index = state.posts.len();
state
.requests
.insert((caller, request.request_id.clone()), index);
state.by_id.insert(id, index);
state.posts.push(Post {
metadata: metadata.clone(),
search: default_case_fold_str(&request.text),
n_chars: request.text.chars().count(),
request,
behavior,
replies: Vec::new(),
latest_reply: None,
});
let last = state.channels[&channel_name].summary.last_message_id;
let newest = last.is_none_or(|last| state.key(index) > state.key(state.by_id[&last]));
#[expect(
clippy::expect_used,
reason = "destination was checked or inserted under this lock"
)]
let channel = state
.channels
.get_mut(&channel_name)
.expect("validated channel");
channel.posts.push(index);
channel.summary.message_count += 1;
if newest {
channel.summary.last_message_id = Some(id);
}
if root == id {
channel.roots.push(index);
} else {
let root_index = state.by_id[&root];
let newest = state.posts[root_index]
.latest_reply
.is_none_or(|last| state.key(index) > state.key(last));
let thread = &mut state.posts[root_index];
thread.replies.push(index);
if newest {
thread.latest_reply = Some(index);
}
}
if behavior == PostBehavior::Discussion {
state.subscribe(SubscriptionTarget::Thread(root), caller);
}
if recipients.is_empty() {
return Ok(metadata);
}
(metadata, state.posts[index].preview(/*max_chars*/ 150))
};
futures::stream::iter(recipients).for_each_concurrent(/*limit*/ 16, |recipient| {
let notice = notice.clone();
async move {
if let Err(error) = self.host.notify(recipient, notice).await {
tracing::warn!(%recipient, %error, "Failed to deliver message-board notification");
}
}
}).await;
Ok(metadata)
}
async fn set_subscription(
&self,
caller: ThreadId,
request: SubscriptionRequest,
) -> Result<SubscriptionState> {
let caller_path = self.host.agent_path(caller).await?;
let target_path = request.target_agent.unwrap_or(caller_path);
let target_agent = self.host.resolve_agent(target_path.clone()).await?;
let mut state = self.state.lock().await;
let (channel_name, thread_id, last_message_id) = match &request.target {
SubscriptionTarget::Channel(name) => {
let channel = state
.channels
.get(name)
.ok_or_else(|| invalid("channel not found in this board"))?;
(name.clone(), None, channel.summary.last_message_id)
}
SubscriptionTarget::Thread(root) => {
let index = state.thread_index(*root)?;
let post = &state.posts[index];
let last = post
.latest_reply
.filter(|last| state.key(*last) > state.key(index))
.unwrap_or(index);
(
post.metadata.channel_name.clone(),
Some(*root),
Some(state.posts[last].metadata.message_id),
)
}
};
state
.subscriptions
.entry(request.target)
.or_default()
.insert(target_agent, request.change);
Ok(SubscriptionState {
channel_name,
thread_id,
target_agent: target_path,
enabled: request.change == SubscriptionChange::Subscribe,
last_message_id,
})
}
}
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())
}

View File

@@ -0,0 +1,307 @@
//! Trait adapter and queries over indexed in-memory posts. Only page results clone content.
use super::InMemoryAgentMessageBoard;
use super::invalid;
use crate::AgentMessageBoard;
use crate::AppendRequest;
use crate::ChannelPage;
use crate::ChannelQuery;
use crate::ChannelSummary;
use crate::CreateChannelRequest;
use crate::Page;
use crate::PageRequest;
use crate::PostContent;
use crate::PostMetadata;
use crate::PostPreview;
use crate::PostQuery;
use crate::PostRequest;
use crate::ReadPostRequest;
use crate::ReadThreadRequest;
use crate::SortDirection;
use crate::SubscriptionRequest;
use crate::SubscriptionState;
use crate::ThreadPage;
use crate::ThreadQuery;
use crate::ThreadSort;
use crate::ThreadSummary;
use crate::UpsertChannelRequest;
use base64::Engine;
use base64::prelude::BASE64_URL_SAFE_NO_PAD;
use caseless::default_case_fold_str;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::error::Result;
use futures::future::BoxFuture;
use std::cmp::Reverse;
impl AgentMessageBoard for InMemoryAgentMessageBoard {
fn identity(&self) -> SessionId {
self.identity
}
fn create_channel(
&self,
caller: ThreadId,
request: CreateChannelRequest,
) -> BoxFuture<'_, Result<ChannelSummary>> {
Box::pin(self.create_channel(caller, request))
}
fn upsert_channel(
&self,
caller: ThreadId,
request: UpsertChannelRequest,
) -> BoxFuture<'_, Result<()>> {
Box::pin(self.upsert_channel(caller, request))
}
fn post(&self, caller: ThreadId, request: PostRequest) -> BoxFuture<'_, Result<PostMetadata>> {
Box::pin(self.post(caller, request))
}
fn append(
&self,
caller: ThreadId,
request: AppendRequest,
) -> BoxFuture<'_, Result<PostMetadata>> {
Box::pin(self.append(caller, request))
}
fn set_subscription(
&self,
caller: ThreadId,
request: SubscriptionRequest,
) -> BoxFuture<'_, Result<SubscriptionState>> {
Box::pin(self.set_subscription(caller, request))
}
fn read_post(
&self,
caller: ThreadId,
request: ReadPostRequest,
) -> BoxFuture<'_, Result<PostContent>> {
Box::pin(async move {
self.host.agent_path(caller).await?;
let state = self.state.lock().await;
let post = &state.posts[state.post_index(request.message_id)?];
let offset = (request.offset_chars as usize).min(post.n_chars);
let text: String = post
.request
.text
.chars()
.skip(offset)
.take((request.limit_chars.get() as usize).min(20_000))
.collect();
Ok(PostContent {
metadata: post.metadata.clone(),
n_chars: post.n_chars,
next_offset_chars: offset + text.chars().count(),
text,
})
})
}
fn list_channels(
&self,
caller: ThreadId,
query: ChannelQuery,
) -> BoxFuture<'_, Result<ChannelPage>> {
Box::pin(async move {
self.host.agent_path(caller).await?;
let search = default_case_fold_str(&query.query.unwrap_or_default());
let state = self.state.lock().await;
let mut channels: Vec<_> = state
.channels
.values()
.filter(|channel| channel.search.contains(&search))
.collect();
channels.sort_unstable_by_key(|channel| {
let activity = channel
.summary
.last_message_id
.map_or(channel.summary.created_at.timestamp_micros(), |id| {
state.key(state.by_id[&id]).0
});
(activity, &channel.summary.channel_name)
});
if query.direction == SortDirection::NewestFirst {
channels.reverse();
}
let page = page(&query.page, channels)?;
Ok(ChannelPage {
channels: Page {
results: page
.results
.into_iter()
.map(|channel| channel.summary.clone())
.collect(),
next_cursor: page.next_cursor,
},
board_permissions: None,
})
})
}
fn list_threads(
&self,
caller: ThreadId,
query: ThreadQuery,
) -> BoxFuture<'_, Result<Page<ThreadSummary>>> {
Box::pin(async move {
self.host.agent_path(caller).await?;
let state = self.state.lock().await;
let channel = state
.channels
.get(&query.channel_name)
.ok_or_else(|| invalid("channel not found in this board"))?;
let mut roots = channel.roots.clone();
roots.sort_unstable_by_key(|index| {
let (created, sequence) = state.key(*index);
let timestamp = match query.sort {
ThreadSort::Created => created,
ThreadSort::Activity => state.posts[*index]
.latest_reply
.map_or(created, |reply| created.max(state.key(reply).0)),
};
(timestamp, sequence)
});
if query.direction == SortDirection::NewestFirst {
roots.reverse();
}
let page = page(&query.page, roots)?;
let chars = (query.max_chars_per_post.get() as usize)
.min(20_000 / (2 * page.results.len().max(1)));
Ok(Page {
results: page
.results
.into_iter()
.map(|index| {
let root = &state.posts[index];
let last = root.latest_reply.map(|reply| &state.posts[reply]);
ThreadSummary {
thread_id: root.metadata.message_id,
root_post: root.preview(chars),
reply_count: root.replies.len(),
last_activity_at: last.map_or(root.metadata.created_at, |last| {
last.metadata.created_at.max(root.metadata.created_at)
}),
latest_reply: last.map(|post| post.preview(chars)),
}
})
.collect(),
next_cursor: page.next_cursor,
})
})
}
fn search_posts(
&self,
caller: ThreadId,
query: PostQuery,
) -> BoxFuture<'_, Result<Page<PostPreview>>> {
Box::pin(async move {
self.host.agent_path(caller).await?;
let search = query.query.as_deref().map(default_case_fold_str);
let state = self.state.lock().await;
let after = query
.after_message_id
.map(|id| state.post_index(id).map(|index| state.key(index)))
.transpose()?;
let mut posts: Vec<_> = match &query.channel_name {
Some(channel) => state
.channels
.get(channel)
.map(|channel| channel.posts.clone())
.unwrap_or_default(),
None => (0..state.posts.len()).collect(),
};
posts.retain(|index| {
let post = &state.posts[*index];
query
.author
.as_ref()
.is_none_or(|author| *author == post.metadata.author)
&& search
.as_ref()
.is_none_or(|text| post.search.contains(text))
&& after.is_none_or(|after| state.key(*index) > after)
});
posts.sort_unstable_by_key(|index| Reverse(state.key(*index)));
let page = page(&query.page, posts)?;
let chars =
(query.max_chars_per_post.get() as usize).min(20_000 / page.results.len().max(1));
Ok(Page {
results: page
.results
.into_iter()
.map(|index| state.posts[index].preview(chars))
.collect(),
next_cursor: page.next_cursor,
})
})
}
fn read_thread(
&self,
caller: ThreadId,
request: ReadThreadRequest,
) -> BoxFuture<'_, Result<ThreadPage>> {
Box::pin(async move {
self.host.agent_path(caller).await?;
let state = self.state.lock().await;
let root = &state.posts[state.thread_index(request.thread_id)?];
let mut replies = root.replies.clone();
replies.sort_unstable_by_key(|index| Reverse(state.key(*index)));
let page = page(&request.page, replies)?;
let chars =
(request.max_chars_per_post.get() as usize).min(20_000 / (page.results.len() + 1));
Ok(ThreadPage {
root_post: root.preview(chars),
replies: Page {
results: page
.results
.into_iter()
.map(|index| state.posts[index].preview(chars))
.collect(),
next_cursor: page.next_cursor,
},
})
})
}
}
fn page<T>(request: &PageRequest, results: Vec<T>) -> Result<Page<T>> {
let offset = match &request.cursor {
Some(cursor) => {
let mut bytes = [0; 4];
let len = BASE64_URL_SAFE_NO_PAD
.decode_slice(cursor, &mut bytes)
.map_err(|_| invalid("invalid cursor"))?;
if len != bytes.len() {
return Err(invalid("invalid cursor"));
}
u32::from_be_bytes(bytes)
}
None => 0,
};
let limit = (request.limit.get() as usize).min(50);
let mut results: Vec<_> = results
.into_iter()
.skip(offset as usize)
.take(limit + 1)
.collect();
let has_more = results.len() > limit;
results.truncate(limit);
let next_cursor = if has_more {
let offset = offset
.checked_add(results.len() as u32)
.ok_or_else(|| invalid("cursor offset exceeds the board limit"))?;
Some(BASE64_URL_SAFE_NO_PAD.encode(offset.to_be_bytes()))
} else {
None
};
Ok(Page {
results,
next_cursor,
})
}

View File

@@ -0,0 +1,66 @@
//! Verifies that registry cleanup releases expired entries and preserves live boards.
use super::*;
use crate::NotificationDelivery;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
struct UnusedHost;
impl MessageBoardHost for UnusedHost {
fn agent_path(&self, _caller: ThreadId) -> BoxFuture<'_, Result<AgentPath>> {
unreachable!("registry tests do not invoke host capabilities")
}
fn resolve_agent(&self, _path: AgentPath) -> BoxFuture<'_, Result<ThreadId>> {
unreachable!("registry tests do not invoke host capabilities")
}
fn current_time(&self, _caller: ThreadId) -> BoxFuture<'_, Result<DateTime<Utc>>> {
unreachable!("registry tests do not invoke host capabilities")
}
fn notify(
&self,
_recipient: ThreadId,
_post: PostPreview,
) -> BoxFuture<'_, Result<NotificationDelivery>> {
unreachable!("registry tests do not invoke host capabilities")
}
}
#[tokio::test]
async fn opening_boards_prunes_expired_entries_and_preserves_live_state() {
let boards = InMemoryMessageBoards::default();
let identity = SessionId::new();
let live = boards.open(identity, Arc::new(UnusedHost)).await;
for _ in 0..16 {
let next_identity = SessionId::new();
let next = boards.open(next_identity, Arc::new(UnusedHost)).await;
assert_eq!(
boards
.states
.lock()
.await
.keys()
.copied()
.collect::<HashSet<_>>(),
HashSet::from([identity, next_identity]),
);
drop(next);
}
let shared = boards.open(identity, Arc::new(UnusedHost)).await;
assert!(Arc::ptr_eq(&live.state, &shared.state));
assert_eq!(
boards
.states
.lock()
.await
.keys()
.copied()
.collect::<HashSet<_>>(),
HashSet::from([identity]),
);
}

View File

@@ -0,0 +1,60 @@
//! Shared message-board operations with interchangeable local, in-memory and remote backends.
//!
//! Board identity and caller identity come from the host. Implementations own
//! storage and notification fanout. Shared tools are registered by consumers.
mod api;
mod host;
mod in_memory;
mod local;
mod permissions;
mod read_view;
mod tools;
mod types;
pub use api::AgentMessageBoard;
pub use api::AppendRequest;
pub use api::ChannelDescription;
pub use api::ChannelQuery;
pub use api::CreateChannelRequest;
pub use api::PageRequest;
pub use api::PostDestination;
pub use api::PostQuery;
pub use api::PostRequest;
pub use api::ReadPostRequest;
pub use api::ReadThreadRequest;
pub use api::SortDirection;
pub use api::SubscriptionChange;
pub use api::SubscriptionRequest;
pub use api::SubscriptionTarget;
pub use api::ThreadQuery;
pub use api::ThreadSort;
pub use api::UpsertChannelRequest;
pub use host::MessageBoardHost;
pub use host::NotificationDelivery;
pub use in_memory::InMemoryAgentMessageBoard;
pub use in_memory::InMemoryMessageBoards;
pub use local::LocalAgentMessageBoard;
pub use local::connection::LocalBoard;
pub use local::connection::LocalBoardConnection;
pub use local::options::LocalBoardOptions;
pub use local::setup::LocalBoardSetup;
pub use local::setup::configure_local_board;
pub use permissions::BoardPermissions;
pub use permissions::ChannelPermissions;
pub use permissions::PermissionDenied;
pub use read_view::BoardReadView;
pub use tools::MAX_TOOL_ARGUMENT_KIB;
pub use tools::MAX_TOOL_RESPONSE_BYTES;
pub use tools::message_board_read_tools;
pub use tools::message_board_tools;
pub use tools::selection::MessageBoardTool;
pub use types::ChannelPage;
pub use types::ChannelSummary;
pub use types::Page;
pub use types::PostContent;
pub use types::PostMetadata;
pub use types::PostPreview;
pub use types::SubscriptionState;
pub use types::ThreadPage;
pub use types::ThreadSummary;

View File

@@ -0,0 +1,503 @@
//! SQLite-backed boards. The board ID scopes every read and write.
//!
//! Immediate transactions serialize mutations across independently opened handles.
//! 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.
//! Explicit connections can restrict writes; default handles retain legacy access.
//! Fixed read views freeze the channel catalog and restrict reads to a captured post sequence.
//! Posting subscribes and notifies; host appends share persistence without these side effects.
use self::connection::Access;
use self::options::LocalBoardOptions;
use crate::AppendRequest;
use crate::ChannelDescription;
use crate::ChannelSummary;
use crate::CreateChannelRequest;
use crate::MessageBoardHost;
use crate::PostDestination;
use crate::PostMetadata;
use crate::PostRequest;
use crate::SubscriptionChange;
use crate::SubscriptionRequest;
use crate::SubscriptionState;
use crate::SubscriptionTarget;
use crate::api::PostBehavior;
use caseless::default_case_fold_str;
use chrono::DateTime;
use chrono::Utc;
use akode_protocol::AgentPath;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result;
use akode_state::SqliteConfig;
use futures::StreamExt;
use serde::Deserialize;
use serde::Serialize;
use sqlx::Row;
use sqlx::SqliteConnection;
use sqlx::SqlitePool;
use std::collections::HashSet;
use std::sync::Arc;
use uuid::Uuid;
mod catalog;
pub(crate) mod connection;
mod json_search;
mod lifecycle;
pub(crate) mod options;
mod paging;
mod pool;
mod queries;
pub(crate) mod setup;
mod subscriptions;
#[cfg(test)]
#[path = "local/pools_tests.rs"]
mod pools_tests;
const MAX_POST_BYTES: usize = 64 * 1024;
const MAX_CHANNEL_BYTES: usize = 128;
const MAX_READ_CHARS: usize = 20_000;
/// Capturing a view makes the handle read-only, regardless of its original access.
#[derive(Clone)]
enum BoardMode {
Live { access: Option<Access> },
Fixed { view: Arc<catalog::ReadView> },
}
impl BoardMode {
const FIXED_ACCESS: Access = Access::ReadOnly;
fn access(&self) -> Option<Access> {
match self {
Self::Live { access } => *access,
Self::Fixed { .. } => Some(Self::FIXED_ACCESS),
}
}
fn view(&self) -> Option<&catalog::ReadView> {
match self {
Self::Live { .. } => None,
Self::Fixed { view } => Some(view),
}
}
}
#[derive(Clone)]
pub struct LocalAgentMessageBoard {
identity: SessionId,
storage_namespace: Arc<str>,
pool: Arc<SqlitePool>,
host: Arc<dyn MessageBoardHost>,
mode: BoardMode,
nested_json_pointer: Option<&'static str>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct StoredPost {
metadata: PostMetadata,
text: String,
}
impl LocalAgentMessageBoard {
/// Reopens the same board for a root, child or resumed runtime. The shared
/// SQLite configuration preserves the host's connection and journal policy.
/// The caller selects the storage namespace.
pub async fn open(
sqlite: &SqliteConfig,
options: &LocalBoardOptions,
identity: SessionId,
host: Arc<dyn MessageBoardHost>,
) -> Result<Self> {
Ok(Self {
identity,
pool: pool::open(sqlite, options).await?,
storage_namespace: Arc::from(options.storage_namespace.as_str()),
host,
mode: BoardMode::Live { access: None },
nested_json_pointer: None,
})
}
pub async fn create_channel(
&self,
caller: ThreadId,
request: CreateChannelRequest,
) -> Result<ChannelSummary> {
if let Some(access) = self.mode.access() {
access.require_write(self.identity, "board.create_channel")?;
}
validate_channel(&request.channel_name)?;
let author = self.host.agent_path(caller).await?;
let now = self.host.current_time(caller).await?;
let mut tx = self.begin_write().await?;
insert_channel(
&mut tx,
self.identity,
&request.channel_name,
request.description.as_ref(),
&author,
now,
)
.await?;
if request.subscription == SubscriptionChange::Subscribe {
self.subscribe(
&mut tx,
&SubscriptionTarget::Channel(request.channel_name.clone()),
caller,
)
.await?;
}
let summary = catalog::channel_summary(self, &mut tx, &request.channel_name).await?;
tx.commit().await.map_err(storage_error)?;
Ok(summary)
}
/// Once started, finish the accepted write and fanout even if the tool caller
/// disconnects. Delivery is attempted once; retries never replay old notices
/// 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> {
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> {
self.write(
caller,
PostRequest {
request_id: request.request_id,
destination: request.destination,
text: request.text,
agents_to_notify: Vec::new(),
},
PostBehavior::SilentAppend,
)
.await
}
async fn write(
&self,
caller: ThreadId,
request: PostRequest,
behavior: PostBehavior,
) -> Result<PostMetadata> {
if let Some(access) = self.mode.access() {
access.require_write(
self.identity,
match &request.destination {
PostDestination::Thread(_) => "channel.reply",
PostDestination::Channel(_) | PostDestination::NewChannel(_) => "channel.post",
},
)?;
}
let board = self.clone();
tokio::spawn(async move { board.post_inner(caller, request, behavior).await })
.await
.map_err(storage_error)?
}
async fn post_inner(
&self,
caller: ThreadId,
request: PostRequest,
behavior: PostBehavior,
) -> Result<PostMetadata> {
if request.text.len() > MAX_POST_BYTES
|| request.text.is_empty()
|| request.request_id.is_empty()
|| request.request_id.len() > 512
|| request.agents_to_notify.len() > 256
{
return Err(invalid(
"post text, request ID or recipient count exceeds the board limits",
));
}
let author = self.host.agent_path(caller).await?;
let request_id = format!("{caller}:{}", request.request_id);
let request_json = match behavior {
// Keep existing post fingerprints compatible with persisted retries.
PostBehavior::Discussion => serde_json::to_string(&request),
PostBehavior::SilentAppend => serde_json::to_string(&("append", &request)),
}
.map_err(storage_error)?;
let mut conn = self.pool.acquire().await.map_err(storage_error)?;
if let Some(post) = self
.existing_post(&mut conn, &request_id, &request_json)
.await?
{
return Ok(post.metadata);
}
drop(conn);
let mut recipients = HashSet::new();
if let PostBehavior::Discussion = behavior {
for path in &request.agents_to_notify {
recipients.insert(self.host.resolve_agent(path.clone()).await?);
}
}
let now = self.host.current_time(caller).await?;
let mut tx = self.begin_write().await?;
if let Some(post) = self
.existing_post(&mut tx, &request_id, &request_json)
.await?
{
return Ok(post.metadata);
}
let id = Uuid::now_v7();
let (channel, root, target) = match &request.destination {
PostDestination::Channel(channel) => {
let exists: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM channels WHERE board=? AND name=?)",
)
.bind(self.identity.to_string())
.bind(channel)
.fetch_one(&mut *tx)
.await
.map_err(storage_error)?;
if !exists {
return Err(invalid("channel not found in this board"));
}
(
channel.clone(),
id,
SubscriptionTarget::Channel(channel.clone()),
)
}
PostDestination::NewChannel(channel) => {
validate_channel(channel)?;
insert_channel(
&mut tx,
self.identity,
channel,
/*description*/ None,
&author,
now,
)
.await?;
if let PostBehavior::Discussion = behavior {
self.subscribe(
&mut tx,
&SubscriptionTarget::Channel(channel.clone()),
caller,
)
.await?;
}
(
channel.clone(),
id,
SubscriptionTarget::Channel(channel.clone()),
)
}
PostDestination::Thread(root) => {
let post = self.load_post(&mut tx, *root).await?;
if post.metadata.thread_id != *root {
return Err(invalid("thread_id must identify a top-level post"));
}
(
post.metadata.channel_name,
*root,
SubscriptionTarget::Thread(*root),
)
}
};
// Return one JSON array to avoid handing each subscriber row across
// SQLite's worker thread while the write transaction is held.
if let PostBehavior::Discussion = behavior {
let subscribed = sqlx::query_scalar::<_, String>(
"SELECT json_group_array(agent) FROM subscriptions WHERE board=? AND target=?",
)
.bind(self.identity.to_string())
.bind(target_key(&target)?)
.fetch_one(&mut *tx)
.await
.map_err(storage_error)?;
let subscribed: Vec<String> =
serde_json::from_str(&subscribed).map_err(storage_error)?;
for recipient in subscribed {
recipients.insert(ThreadId::from_string(&recipient).map_err(storage_error)?);
}
}
recipients.remove(&caller);
let post = StoredPost {
metadata: PostMetadata {
message_id: id,
channel_name: channel.clone(),
author: author.clone(),
thread_id: root,
created_at: now,
},
text: request.text,
};
sqlx::query("INSERT INTO posts(board,id,channel,root,author,timestamp,body_search,payload,request_id,request) VALUES(?,?,?,?,?,?,?,?,?,?)")
.bind(self.identity.to_string()).bind(id.to_string()).bind(channel).bind(root.to_string())
.bind(author.to_string()).bind(now.timestamp_micros()).bind(default_case_fold_str(&post.text))
.bind(serde_json::to_string(&post).map_err(storage_error)?).bind(request_id).bind(request_json)
.execute(&mut *tx).await.map_err(storage_error)?;
// Participation subscribes by default, without overriding an explicit opt-out.
if let PostBehavior::Discussion = behavior {
self.subscribe(&mut tx, &SubscriptionTarget::Thread(root), caller)
.await?;
}
tx.commit().await.map_err(storage_error)?;
if let PostBehavior::SilentAppend = behavior {
return Ok(post.metadata);
}
// A committed post succeeds even if a best-effort notice cannot be delivered.
let notice = paging::preview(post.clone(), /*max_chars*/ 150);
futures::stream::iter(recipients)
.for_each_concurrent(/*limit*/ 16, |recipient| {
let notice = notice.clone();
async move {
if let Err(error) = self.host.notify(recipient, notice).await {
tracing::warn!(%recipient, %error, "Failed to deliver message-board notification");
}
}
})
.await;
Ok(post.metadata)
}
pub async fn set_subscription(
&self,
caller: ThreadId,
request: SubscriptionRequest,
) -> Result<SubscriptionState> {
let caller_path = self.host.agent_path(caller).await?;
let target_path = request.target_agent.unwrap_or(caller_path);
let target_agent = self.host.resolve_agent(target_path.clone()).await?;
if target_agent != caller
&& let Some(access) = self.mode.access()
{
access.require_write(self.identity, "board.manage_subscriptions")?;
}
let mut tx = self.begin_write().await?;
let (channel, root, last) = match &request.target {
SubscriptionTarget::Channel(name) => {
let last: Option<String> = sqlx::query_scalar(
"SELECT (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)
FROM channels c WHERE c.board=? AND c.name=?",
)
.bind(self.identity.to_string())
.bind(name)
.fetch_optional(&mut *tx)
.await
.map_err(storage_error)?
.ok_or_else(|| invalid("channel not found in this board"))?;
(name.clone(), None, last)
}
SubscriptionTarget::Thread(root) => {
let post = self.load_post(&mut tx, *root).await?;
if post.metadata.thread_id != *root {
return Err(invalid("thread_id must identify a top-level post"));
}
let last: String = sqlx::query_scalar("SELECT id FROM posts WHERE board=? AND root=? ORDER BY timestamp DESC, seq DESC LIMIT 1")
.bind(self.identity.to_string()).bind(root.to_string()).fetch_one(&mut *tx).await.map_err(storage_error)?;
(post.metadata.channel_name, Some(*root), Some(last))
}
};
let last_message_id = last
.as_deref()
.map(Uuid::parse_str)
.transpose()
.map_err(storage_error)?;
self.change_subscription(&mut tx, &request.target, target_agent, request.change)
.await?;
tx.commit().await.map_err(storage_error)?;
Ok(SubscriptionState {
channel_name: channel,
thread_id: root,
target_agent: target_path,
enabled: request.change == SubscriptionChange::Subscribe,
last_message_id,
})
}
async fn subscribe(
&self,
conn: &mut SqliteConnection,
target: &SubscriptionTarget,
agent: ThreadId,
) -> Result<()> {
sqlx::query("INSERT OR IGNORE INTO subscriptions(board,target,agent) SELECT ?1,?2,?3 WHERE NOT EXISTS(SELECT 1 FROM subscription_opt_outs WHERE board=?1 AND target=?2 AND agent=?3)")
.bind(self.identity.to_string())
.bind(target_key(target)?)
.bind(agent.to_string())
.execute(conn)
.await
.map_err(storage_error)?;
Ok(())
}
async fn existing_post(
&self,
conn: &mut SqliteConnection,
request_id: &str,
request: &str,
) -> Result<Option<StoredPost>> {
let row = sqlx::query("SELECT payload,request FROM posts WHERE board=? AND request_id=?")
.bind(self.identity.to_string())
.bind(request_id)
.fetch_optional(conn)
.await
.map_err(storage_error)?;
row.map(|row| {
if row.get::<String, _>("request") != request {
return Err(invalid("request ID was already used for a different post"));
}
serde_json::from_str(row.get("payload")).map_err(storage_error)
})
.transpose()
}
}
// Runtime writes and template setup validate names and board lifecycle before
// inserting within their own transaction.
async fn insert_channel(
conn: &mut SqliteConnection,
board: SessionId,
name: &str,
description: Option<&ChannelDescription>,
author: &AgentPath,
now: DateTime<Utc>,
) -> Result<()> {
let inserted = sqlx::query("INSERT OR IGNORE INTO channels(board,name,name_search,created_at,timestamp,author,description) VALUES(?,?,?,?,?,?,?)")
.bind(board.to_string()).bind(name).bind(default_case_fold_str(name)).bind(now.to_rfc3339()).bind(now.timestamp_micros()).bind(author.to_string()).bind(description.map(ChannelDescription::as_str))
.execute(conn).await.map_err(storage_error)?.rows_affected();
if inserted == 0 {
return Err(invalid("channel already exists"));
}
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())
}
fn storage_error(error: impl std::fmt::Display) -> CodexErr {
CodexErr::Io(std::io::Error::other(error.to_string()))
}
fn target_key(target: &SubscriptionTarget) -> Result<String> {
serde_json::to_string(target).map_err(storage_error)
}

View File

@@ -0,0 +1,278 @@
//! Channel summaries and fixed read views. Capture only catalog metadata and a
//! monotonically increasing post boundary; payload reads continue to use SQLite.
use super::BoardMode;
use super::LocalAgentMessageBoard;
use super::connection::Access;
use super::invalid;
use super::paging::Window;
use super::storage_error;
use crate::AgentMessageBoard;
use crate::BoardPermissions;
use crate::BoardReadView;
use crate::ChannelPage;
use crate::ChannelPermissions;
use crate::ChannelQuery;
use crate::ChannelSummary;
use crate::Page;
use crate::PostContent;
use crate::PostPreview;
use crate::PostQuery;
use crate::ReadPostRequest;
use crate::ReadThreadRequest;
use crate::SortDirection;
use crate::ThreadPage;
use crate::ThreadQuery;
use crate::ThreadSummary;
use caseless::default_case_fold_str;
use chrono::DateTime;
use chrono::Utc;
use akode_protocol::AgentPath;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::error::Result;
use futures::future::BoxFuture;
use sqlx::Row;
use sqlx::SqliteConnection;
use sqlx::sqlite::SqliteRow;
use std::sync::Arc;
use uuid::Uuid;
/// The captured catalog and the read-only SQLite handle that enforces its post boundary.
struct LocalBoardReadView {
board: LocalAgentMessageBoard,
view: Arc<ReadView>,
}
impl BoardReadView for LocalBoardReadView {
fn identity(&self) -> SessionId {
self.board.identity
}
fn with_json_search(&self, pointer: &'static str) -> Arc<dyn BoardReadView> {
let mut board = self.board.clone();
board.nested_json_pointer = Some(pointer);
Arc::new(Self {
board,
view: Arc::clone(&self.view),
})
}
fn storage_namespace(&self) -> &str {
&self.board.storage_namespace
}
fn channels(&self) -> &[ChannelSummary] {
&self.view.channels
}
fn list_channels(
&self,
caller: ThreadId,
query: ChannelQuery,
) -> BoxFuture<'_, Result<ChannelPage>> {
self.board.list_channels(caller, query)
}
fn list_threads(
&self,
caller: ThreadId,
query: ThreadQuery,
) -> BoxFuture<'_, Result<Page<ThreadSummary>>> {
self.board.list_threads(caller, query)
}
fn search_posts(
&self,
caller: ThreadId,
query: PostQuery,
) -> BoxFuture<'_, Result<Page<PostPreview>>> {
self.board.search_posts(caller, query)
}
fn read_thread(
&self,
caller: ThreadId,
request: ReadThreadRequest,
) -> BoxFuture<'_, Result<ThreadPage>> {
self.board.read_thread(caller, request)
}
fn read_post(
&self,
caller: ThreadId,
request: ReadPostRequest,
) -> BoxFuture<'_, Result<PostContent>> {
AgentMessageBoard::read_post(&self.board, caller, request)
}
fn appended_request_ids<'a>(
&'a self,
caller: ThreadId,
channel: &'a str,
after: i64,
) -> BoxFuture<'a, Result<Vec<(i64, String)>>> {
Box::pin(async move {
self.board.host.agent_path(caller).await?;
if after < 0 || after > self.view.post_cutoff {
return Err(invalid("post cursor is outside the captured board view"));
}
// The persisted retry key prefixes the caller-supplied request ID with "{caller}:".
sqlx::query_as(
"SELECT seq, substr(request_id, instr(request_id, ':') + 1) FROM posts
WHERE board=? AND channel=? AND seq>? AND seq<=? ORDER BY seq LIMIT ?",
)
.bind(self.board.identity.to_string())
.bind(channel)
.bind(after)
.bind(self.view.post_cutoff)
.bind(i64::from(crate::PageRequest::default().limit.get()))
.fetch_all(self.board.pool.as_ref())
.await
.map_err(storage_error)
})
}
fn read_post_texts<'a>(
&'a self,
caller: ThreadId,
positions: &'a [i64],
) -> BoxFuture<'a, Result<Vec<String>>> {
Box::pin(async move {
self.board.host.agent_path(caller).await?;
if positions.len() > crate::PageRequest::default().limit.get() as usize {
return Err(invalid("requested posts exceed one board page"));
}
// Drive primary-key lookups from the requested page, not from all posts on the board.
let texts = sqlx::query_scalar::<_, String>(
"SELECT json_extract(p.payload, '$.text') FROM json_each(?) AS requested
CROSS JOIN posts AS p
WHERE p.seq=requested.value AND p.board=? AND p.seq<=? ORDER BY requested.key",
)
.bind(serde_json::to_string(positions).map_err(storage_error)?)
.bind(self.board.identity.to_string())
.bind(self.view.post_cutoff)
.fetch_all(self.board.pool.as_ref())
.await
.map_err(storage_error)?;
if texts.len() != positions.len() {
return Err(invalid("post not found in this board view"));
}
Ok(texts)
})
}
}
pub(super) struct ReadView {
pub(super) post_cutoff: i64,
pub(super) channels: Vec<ChannelSummary>,
}
impl ReadView {
pub(super) fn list_channels(&self, query: ChannelQuery) -> Result<ChannelPage> {
let window = Window::new(&query.page)?;
let needle = default_case_fold_str(&query.query.unwrap_or_default());
let ordered: Box<dyn Iterator<Item = &ChannelSummary>> = match query.direction {
SortDirection::NewestFirst => Box::new(self.channels.iter()),
SortDirection::OldestFirst => Box::new(self.channels.iter().rev()),
};
let channels = ordered
.filter(|channel| default_case_fold_str(&channel.channel_name).contains(&needle))
.skip(window.offset() as usize)
.take(window.limit + 1)
.cloned()
.collect();
Ok(ChannelPage {
channels: window.finish(channels)?,
board_permissions: Some(BoardPermissions {
create_channel: false,
edit_metadata: false,
manage_permissions: false,
}),
})
}
}
pub(super) async fn capture(board: &LocalAgentMessageBoard) -> Result<Arc<dyn BoardReadView>> {
let mut tx = board.pool.begin().await.map_err(storage_error)?;
// seq is the database-wide AUTOINCREMENT key. Every future board append is above it.
let post_cutoff = sqlx::query_scalar::<_, i64>("SELECT COALESCE(MAX(seq),0) FROM posts")
.fetch_one(&mut *tx)
.await
.map_err(storage_error)?;
let rows = sqlx::query(
"SELECT c.name,c.created_at,c.author,c.description,last.id AS last_message_id,
(SELECT COUNT(*) FROM posts p WHERE p.board=c.board AND p.channel=c.name) AS message_count
FROM channels c LEFT JOIN posts last ON last.seq=(
SELECT p.seq FROM posts p WHERE p.board=c.board AND p.channel=c.name
ORDER BY p.timestamp DESC,p.seq DESC LIMIT 1
)
WHERE c.board=? ORDER BY COALESCE(last.timestamp,c.timestamp) DESC,c.name DESC",
)
.bind(board.identity.to_string())
.fetch_all(&mut *tx)
.await
.map_err(storage_error)?;
tx.commit().await.map_err(storage_error)?;
let channels = rows
.into_iter()
.map(|row| decode_channel_summary(Some(BoardMode::FIXED_ACCESS), row))
.collect::<Result<Vec<_>>>()?;
let view = Arc::new(ReadView {
post_cutoff,
channels,
});
let board = LocalAgentMessageBoard {
mode: BoardMode::Fixed {
view: Arc::clone(&view),
},
..board.clone()
};
Ok(Arc::new(LocalBoardReadView { board, view }))
}
pub(super) async fn channel_summary(
board: &LocalAgentMessageBoard,
conn: &mut SqliteConnection,
name: &str,
) -> Result<ChannelSummary> {
let row = sqlx::query(
"SELECT c.name,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=?",
)
.bind(board.identity.to_string())
.bind(name)
.fetch_optional(conn)
.await
.map_err(storage_error)?
.ok_or_else(|| invalid("channel not found in this board"))?;
decode_channel_summary(board.mode.access(), row)
}
fn decode_channel_summary(access: Option<Access>, row: SqliteRow) -> Result<ChannelSummary> {
Ok(ChannelSummary {
permissions: access.map(|access| {
let write = matches!(access, Access::ReadWrite);
ChannelPermissions {
read: true,
post: write,
reply: write,
edit_metadata: false,
}
}),
channel_name: row.get("name"),
description: row.get("description"),
created_at: DateTime::parse_from_rfc3339(row.get("created_at"))
.map_err(storage_error)?
.with_timezone(&Utc),
created_by: AgentPath::try_from(row.get::<String, _>("author")).map_err(invalid)?,
message_count: row.get::<i64, _>("message_count") as usize,
last_message_id: row
.get::<Option<String>, _>("last_message_id")
.map(|id| Uuid::parse_str(&id))
.transpose()
.map_err(storage_error)?,
})
}

View File

@@ -0,0 +1,132 @@
//! Host-supplied connections to one local board. Access is fixed per runtime,
//! independent of the board's storage or the agent's tree identity.
use super::BoardMode;
use super::LocalAgentMessageBoard;
use super::options::LocalBoardOptions;
use crate::MessageBoardHost;
use crate::PermissionDenied;
use akode_protocol::AgentPath;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result;
use akode_state::SqliteConfig;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::OnceLock;
/// Shared local storage from which a host grants individual runtime connections.
#[derive(Clone)]
pub struct LocalBoard {
sqlite: SqliteConfig,
identity: SessionId,
options: LocalBoardOptions,
}
impl LocalBoard {
pub fn new(sqlite: SqliteConfig, identity: SessionId) -> Self {
Self {
sqlite,
identity,
options: LocalBoardOptions::default(),
}
}
pub fn with_options(mut self, options: LocalBoardOptions) -> Self {
self.options = options;
self
}
pub fn read_only(&self) -> LocalBoardConnection {
LocalBoardConnection {
board: self.clone(),
access: Access::ReadOnly,
database: OnceLock::new(),
}
}
pub fn read_write(&self) -> LocalBoardConnection {
LocalBoardConnection {
board: self.clone(),
access: Access::ReadWrite,
database: OnceLock::new(),
}
}
}
/// Insert into `StartThreadOptions::thread_extension_init` before creating Codex.
/// Hosts must supply it again for a new runtime, including cold resume or a fork.
/// The board extension must be installed, including in an isolated session's registry.
#[derive(Clone)]
pub struct LocalBoardConnection {
board: LocalBoard,
access: Access,
// Capture the opened database, independently of caller unload or symlink changes.
database: OnceLock<PathBuf>,
}
impl LocalBoardConnection {
pub fn identity(&self) -> SessionId {
self.board.identity
}
/// Compare the canonical database paths captured when the connections were opened.
pub fn same_board(&self, other: &Self) -> bool {
self.identity() == other.identity()
&& self
.database
.get()
.zip(other.database.get())
.is_some_and(|(database, other)| database == other)
}
/// Independent runtimes have no common agent tree. Use their unique IDs as paths.
pub fn caller_path(&self, caller: ThreadId) -> Result<AgentPath> {
AgentPath::root()
.join(&caller.to_string().replace('-', ""))
.map_err(CodexErr::InvalidRequest)
}
pub async fn open(&self, host: Arc<dyn MessageBoardHost>) -> Result<LocalAgentMessageBoard> {
let mut board = LocalAgentMessageBoard::open(
&self.board.sqlite,
&self.board.options,
self.identity(),
host,
)
.await?;
// Pool initialization canonicalizes the directory before opening SQLite.
let options = board.pool.connect_options();
let database = options.get_filename();
if self.database.get_or_init(|| database.to_path_buf()) != database {
return Err(CodexErr::InvalidRequest(
"board database changed; create a new board connection".into(),
));
}
board.mode = BoardMode::Live {
access: Some(self.access),
};
Ok(board)
}
}
#[derive(Clone, Copy)]
pub(super) enum Access {
ReadOnly,
ReadWrite,
}
impl Access {
pub(super) fn require_write(self, board: SessionId, action: &str) -> Result<()> {
match self {
Self::ReadWrite => Ok(()),
Self::ReadOnly => Err(PermissionDenied {
message: "This board connection is read-only.".into(),
action: Some(action.into()),
resource: Some(format!("board:{board}")),
}
.into()),
}
}
}

View File

@@ -0,0 +1,81 @@
//! Literal search over decoded JSON fields in a fixed read view.
use super::StoredPost;
use super::paging::Window;
use super::storage_error;
use caseless::default_case_fold_str;
use akode_protocol::error::Result;
use futures::TryStreamExt;
use serde_json::Value;
use sqlx::QueryBuilder;
use sqlx::Sqlite;
use sqlx::SqliteConnection;
pub(super) async fn page(
mut sql: QueryBuilder<Sqlite>,
conn: &mut SqliteConnection,
pointer: &str,
needle: &str,
window: &Window,
) -> Result<Vec<StoredPost>> {
// Plain text matches the folded column directly. Also consider rows in which
// JSON escaping could hide a match, including Unicode escapes for ASCII text.
let escape = if needle
.bytes()
.any(|b| b < 0x20 || matches!(b, b'"' | b'/' | b'\\'))
{
r"\"
} else {
r"\u"
};
sql.push(" AND (instr(body_search,")
.push_bind(needle)
.push(")>0 OR instr(body_search,")
.push_bind(escape)
.push(")>0) ORDER BY timestamp DESC,seq DESC");
let mut rows = sql.build_query_scalar::<String>().fetch(conn);
let mut skip = window.offset();
let mut posts = Vec::new();
while let Some(row) = rows.try_next().await.map_err(storage_error)? {
let post: StoredPost = serde_json::from_str(&row).map_err(storage_error)?;
if !matches_post(&post.text, pointer, needle) {
continue;
}
if skip > 0 {
skip -= 1;
continue;
}
posts.push(post);
if posts.len() > window.limit {
break;
}
}
Ok(posts)
}
fn matches_post(text: &str, pointer: &str, needle: &str) -> bool {
if default_case_fold_str(text).contains(needle) {
return true;
}
let Ok(post) = serde_json::from_str::<Value>(text) else {
return false;
};
// The arguments string is searchable both as posted JSON and as decoded values.
contains_literal(&post, needle)
|| post
.pointer(pointer)
.and_then(Value::as_str)
.and_then(|raw| serde_json::from_str(raw).ok())
.is_some_and(|arguments| contains_literal(&arguments, needle))
}
fn contains_literal(value: &Value, needle: &str) -> bool {
match value {
Value::String(text) => default_case_fold_str(text).contains(needle),
Value::Array(items) => items.iter().any(|item| contains_literal(item, needle)),
Value::Object(fields) => fields.iter().any(|(key, item)| {
default_case_fold_str(key).contains(needle) || contains_literal(item, needle)
}),
Value::Number(_) | Value::Bool(_) | Value::Null => value.to_string().contains(needle),
}
}

View File

@@ -0,0 +1,110 @@
//! Permanent board deletion, serialized with writes across all open handles.
//!
//! Keep only a root ID tombstone so delayed writes cannot resurrect deleted data.
//! Recovery closes the cached pool before backing up and recreating the database,
//! and excludes new handles until the replacement's deletion tombstones are saved.
use super::LocalAgentMessageBoard;
use super::invalid;
use super::options::LocalBoardOptions;
use super::pool::POOLS;
use super::pool::SCHEMA;
use super::storage_error;
use akode_protocol::SessionId;
use akode_protocol::error::Result;
use akode_state::SqliteConfig;
use akode_state::SqlitePoolWriteExt;
use sqlx::Sqlite;
use sqlx::Transaction;
use std::sync::Weak;
impl LocalAgentMessageBoard {
/// Permanently removes boards owned by these roots, including their posts and subscriptions.
/// A child's ID does not match its parent's board. Unload and archive must not call this.
/// Safe to retry and independent of whether the feature is currently enabled.
/// Recovering an unopenable corrupt database resets all boards, retaining a backup.
#[expect(
clippy::await_holding_invalid_type,
reason = "recovery excludes new handles until replacement deletion tombstones are saved"
)]
pub async fn delete_boards(
sqlite: &SqliteConfig,
options: &LocalBoardOptions,
roots: &[SessionId],
) -> Result<()> {
let filename = options.database_file()?;
let path = sqlite.home().join(&filename);
if roots.is_empty() || !tokio::fs::try_exists(&path).await? {
return Ok(());
}
let path = tokio::fs::canonicalize(sqlite.home()).await?.join(filename);
let mut pools = POOLS.lock().await;
let pool = match sqlite.open_read_write_pool(&path).await {
Ok(pool) => pool,
Err(error) => {
if !akode_state::is_sqlite_corruption_error(&error) {
return Err(storage_error(error));
}
if let Some(pool) = pools.get(&path).and_then(Weak::upgrade) {
pool.close().await;
}
pools.remove(&path);
let backups = akode_state::backup_runtime_db_for_fresh_start(&path).await?;
tracing::warn!(
database = %path.display(),
?backups,
"Backed up corrupt agent message-board storage; recreating it for thread deletion. Existing data for all boards is unavailable."
);
sqlite
.open_read_write_pool(&path)
.await
.map_err(storage_error)?
}
};
// Also handles databases created before permanent deletion was supported.
sqlx::raw_sql(SCHEMA)
.execute(&pool)
.await
.map_err(storage_error)?;
let mut tx = pool.begin_immediate().await.map_err(storage_error)?;
for root in roots {
sqlx::query("INSERT OR IGNORE INTO deleted_boards (board) VALUES (?)")
.bind(root.to_string())
.execute(&mut *tx)
.await
.map_err(storage_error)?;
for statement in [
"DELETE FROM subscriptions WHERE board=?",
"DELETE FROM subscription_opt_outs WHERE board=?",
"DELETE FROM posts WHERE board=?",
"DELETE FROM channels WHERE board=?",
"DELETE FROM board_templates WHERE board=?",
] {
sqlx::query(statement)
.bind(root.to_string())
.execute(&mut *tx)
.await
.map_err(storage_error)?;
}
}
tx.commit().await.map_err(storage_error)?;
pool.close().await;
Ok(())
}
pub(super) async fn begin_write(&self) -> Result<Transaction<'_, Sqlite>> {
let mut tx = self.pool.begin_immediate().await.map_err(storage_error)?;
let deleted: bool =
sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM deleted_boards WHERE board=?)")
.bind(self.identity.to_string())
.fetch_one(&mut *tx)
.await
.map_err(storage_error)?;
if deleted {
return Err(invalid(
"the message board's root has been permanently deleted",
));
}
Ok(tx)
}
}

View File

@@ -0,0 +1,43 @@
//! Storage namespace selected by the board's owner.
//! Owners supply the same namespace when reopening storage.
use super::invalid;
use akode_protocol::error::Result;
pub(super) const DEFAULT_STORAGE_NAMESPACE: &str = "agent_message_board";
/// Host-selected storage, independent of tool selection and connection permissions.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LocalBoardOptions {
/// A namespace isolates boards with the same session identity in separate databases.
/// Use 1–64 lowercase ASCII letters, digits, underscores or hyphens.
pub storage_namespace: String,
}
impl Default for LocalBoardOptions {
fn default() -> Self {
Self {
storage_namespace: DEFAULT_STORAGE_NAMESPACE.into(),
}
}
}
impl LocalBoardOptions {
pub(super) fn database_file(&self) -> Result<String> {
if self.storage_namespace.is_empty()
|| self.storage_namespace.len() > 64
|| !self.storage_namespace.bytes().all(|byte| {
byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'_' | b'-')
})
{
return Err(invalid(
"board storage namespaces require 1–64 lowercase ASCII letters, digits, underscores or hyphens",
));
}
if self.storage_namespace == DEFAULT_STORAGE_NAMESPACE {
return Ok("agent_message_board_1.sqlite".into());
}
// Custom boards must not share filenames with other runtime databases.
Ok(format!("message_board_{}_1.sqlite", self.storage_namespace))
}
}

View File

@@ -0,0 +1,87 @@
//! Bounded offset pagination. Concurrent posts may shift live results between pages;
//! fixed read views exclude later appends from every page.
//! Cursors belong to the original query; restart without one to refresh the listing.
use super::StoredPost;
use super::invalid;
use super::storage_error;
use crate::Page;
use crate::PageRequest;
use crate::PostPreview;
use crate::SortDirection;
use base64::Engine;
use base64::prelude::BASE64_URL_SAFE_NO_PAD;
use akode_protocol::error::Result;
pub(super) struct Window {
offset: u32,
pub(super) limit: usize,
}
impl Window {
pub(super) fn new(page: &PageRequest) -> Result<Self> {
let offset = match &page.cursor {
Some(cursor) => {
let mut bytes = [0; 4];
let len = BASE64_URL_SAFE_NO_PAD
.decode_slice(cursor, &mut bytes)
.map_err(|_| invalid("invalid cursor"))?;
if len != bytes.len() {
return Err(invalid("invalid cursor"));
}
u32::from_be_bytes(bytes)
}
None => 0,
};
Ok(Self {
offset,
limit: (page.limit.get() as usize).min(50),
})
}
pub(super) fn offset(&self) -> i64 {
i64::from(self.offset)
}
pub(super) fn finish<T>(self, mut results: Vec<T>) -> Result<Page<T>> {
let has_more = results.len() > self.limit;
results.truncate(self.limit);
let next_cursor = if has_more {
let offset = self
.offset
.checked_add(results.len() as u32)
.ok_or_else(|| invalid("cursor offset exceeds the board limit"))?;
Some(BASE64_URL_SAFE_NO_PAD.encode(offset.to_be_bytes()))
} else {
None
};
Ok(Page {
results,
next_cursor,
})
}
}
pub(super) fn direction(direction: SortDirection) -> &'static str {
match direction {
SortDirection::NewestFirst => "DESC",
SortDirection::OldestFirst => "ASC",
}
}
pub(super) fn preview(post: StoredPost, max_chars: usize) -> PostPreview {
let n_chars = post.text.chars().count();
let text_preview = post.text.chars().take(max_chars).collect();
PostPreview {
metadata: post.metadata,
text_preview,
n_chars,
truncated: n_chars > max_chars,
}
}
pub(super) fn decode_posts(rows: Vec<String>) -> Result<Vec<StoredPost>> {
rows.into_iter()
.map(|row| serde_json::from_str(&row).map_err(storage_error))
.collect()
}

View File

@@ -0,0 +1,98 @@
//! Owns the local database schema and pool registry shared by runtime handles and setup.
//! Initialization and deletion recovery share the registry lock to exclude stale pools.
use super::options::LocalBoardOptions;
use super::storage_error;
use akode_protocol::error::Result;
use akode_state::SqliteConfig;
use akode_state::SqlitePoolWriteExt;
use sqlx::SqlitePool;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::LazyLock;
use std::sync::Weak;
use tokio::sync::Mutex;
// Weak entries let the last board handle release its pool. Initialization and
// recovery share one lock so concurrent starts cannot open duplicate or stale pools.
pub(super) static POOLS: LazyLock<Mutex<HashMap<PathBuf, Weak<SqlitePool>>>> =
LazyLock::new(Mutex::default);
pub(super) const SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS board_templates (board TEXT PRIMARY KEY NOT NULL, template TEXT NOT NULL);
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, description TEXT,
PRIMARY KEY(board,name)
);
CREATE TABLE IF NOT EXISTS posts (
seq INTEGER PRIMARY KEY AUTOINCREMENT,
board TEXT NOT NULL, id TEXT NOT NULL, channel TEXT NOT NULL, root TEXT NOT NULL,
author TEXT NOT NULL, timestamp INTEGER NOT NULL, body_search TEXT NOT NULL,
payload TEXT NOT NULL, request_id TEXT NOT NULL, request TEXT NOT NULL,
UNIQUE(board,id), UNIQUE(board,request_id)
);
CREATE INDEX IF NOT EXISTS posts_board_channel ON posts(board,channel,seq);
CREATE INDEX IF NOT EXISTS posts_board_channel_timestamp ON posts(board,channel,timestamp,seq);
CREATE INDEX IF NOT EXISTS posts_roots_created ON posts(board,channel,timestamp,seq) WHERE id=root;
CREATE INDEX IF NOT EXISTS posts_board_root ON posts(board,root,seq);
CREATE INDEX IF NOT EXISTS posts_board_root_timestamp ON posts(board,root,timestamp,seq);
CREATE INDEX IF NOT EXISTS posts_board_timestamp ON posts(board,timestamp,seq);
CREATE TABLE IF NOT EXISTS subscriptions (
board TEXT NOT NULL, target TEXT NOT NULL, agent TEXT NOT NULL,
PRIMARY KEY(board,target,agent)
);
CREATE TABLE IF NOT EXISTS subscription_opt_outs (
board TEXT NOT NULL, target TEXT NOT NULL, agent TEXT NOT NULL,
PRIMARY KEY(board,target,agent)
);";
#[expect(
clippy::await_holding_invalid_type,
reason = "serialize shared pool initialization"
)]
pub(super) async fn open(
sqlite: &SqliteConfig,
options: &LocalBoardOptions,
) -> Result<Arc<SqlitePool>> {
let filename = options.database_file()?;
tokio::fs::create_dir_all(sqlite.home()).await?;
let path = tokio::fs::canonicalize(sqlite.home()).await?.join(filename);
let mut pools = POOLS.lock().await;
pools.retain(|_, pool| pool.strong_count() > 0);
let pool = if let Some(pool) = pools
.get(&path)
.and_then(Weak::upgrade)
.filter(|pool| !pool.is_closed())
{
pool
} else {
let pool = sqlite
.open_read_write_pool(&path)
.await
.map_err(storage_error)?;
let mut tx = pool.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
};
Ok(pool)
}

View File

@@ -0,0 +1,57 @@
//! Verifies pool sharing and release without exposing storage internals.
use super::*;
use crate::NotificationDelivery;
use crate::PostPreview;
use futures::future::BoxFuture;
use pretty_assertions::assert_ne;
struct UnusedHost;
impl MessageBoardHost for UnusedHost {
fn agent_path(&self, _caller: ThreadId) -> BoxFuture<'_, Result<AgentPath>> {
unreachable!("pool tests do not invoke host capabilities")
}
fn resolve_agent(&self, _path: AgentPath) -> BoxFuture<'_, Result<ThreadId>> {
unreachable!("pool tests do not invoke host capabilities")
}
fn current_time(&self, _caller: ThreadId) -> BoxFuture<'_, Result<DateTime<Utc>>> {
unreachable!("pool tests do not invoke host capabilities")
}
fn notify(
&self,
_recipient: ThreadId,
_post: PostPreview,
) -> BoxFuture<'_, Result<NotificationDelivery>> {
unreachable!("pool tests do not invoke host capabilities")
}
}
#[tokio::test]
async fn concurrent_handles_share_and_release_the_pool() {
let dir = tempfile::tempdir().unwrap();
let sqlite = SqliteConfig::new_for_testing(dir.path().to_path_buf().try_into().unwrap());
let options = LocalBoardOptions::default();
let (first, second) = tokio::join!(
LocalAgentMessageBoard::open(&sqlite, &options, SessionId::new(), Arc::new(UnusedHost)),
LocalAgentMessageBoard::open(&sqlite, &options, SessionId::new(), Arc::new(UnusedHost)),
);
let first = first.unwrap();
let second = second.unwrap();
assert!(Arc::ptr_eq(&first.pool, &second.pool));
let original = Arc::downgrade(&first.pool);
drop(first);
assert!(Arc::ptr_eq(&original.upgrade().unwrap(), &second.pool));
drop(second);
assert!(original.upgrade().is_none());
let reopened =
LocalAgentMessageBoard::open(&sqlite, &options, SessionId::new(), Arc::new(UnusedHost))
.await
.unwrap();
assert_ne!(original.as_ptr(), Arc::as_ptr(&reopened.pool));
reopened.pool.close().await;
}

View File

@@ -0,0 +1,546 @@
//! Bounded board queries and channel-description updates that preserve existing evidence.
use super::LocalAgentMessageBoard;
use super::MAX_READ_CHARS;
use super::StoredPost;
use super::catalog;
use super::connection::Access;
use super::invalid;
use super::json_search;
use super::paging::Window;
use super::paging::decode_posts;
use super::paging::direction;
use super::paging::preview;
use super::storage_error;
use super::validate_channel;
use crate::AgentMessageBoard;
use crate::AppendRequest;
use crate::BoardPermissions;
use crate::BoardReadView;
use crate::ChannelPage;
use crate::ChannelQuery;
use crate::ChannelSummary;
use crate::CreateChannelRequest;
use crate::Page;
use crate::PageRequest;
use crate::PostContent;
use crate::PostMetadata;
use crate::PostPreview;
use crate::PostQuery;
use crate::PostRequest;
use crate::ReadPostRequest;
use crate::ReadThreadRequest;
use crate::SubscriptionChange;
use crate::SubscriptionRequest;
use crate::SubscriptionState;
use crate::ThreadPage;
use crate::ThreadQuery;
use crate::ThreadSort;
use crate::ThreadSummary;
use crate::UpsertChannelRequest;
use caseless::default_case_fold_str;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::error::Result;
use futures::future::BoxFuture;
use sqlx::QueryBuilder;
use sqlx::SqliteConnection;
use std::collections::BTreeMap;
use std::sync::Arc;
use uuid::Uuid;
impl LocalAgentMessageBoard {
pub(super) async fn load_post(
&self,
conn: &mut SqliteConnection,
id: Uuid,
) -> Result<StoredPost> {
let query = if let Some(view) = self.mode.view() {
sqlx::query_scalar("SELECT payload FROM posts WHERE seq<=? AND board=? AND id=?")
.bind(view.post_cutoff)
} else {
sqlx::query_scalar("SELECT payload FROM posts WHERE board=? AND id=?")
};
let payload: Option<String> = query
.bind(self.identity.to_string())
.bind(id.to_string())
.fetch_optional(conn)
.await
.map_err(storage_error)?;
serde_json::from_str(&payload.ok_or_else(|| invalid("post not found in this board"))?)
.map_err(storage_error)
}
pub async fn read_post(
&self,
caller: ThreadId,
request: ReadPostRequest,
) -> Result<PostContent> {
self.host.agent_path(caller).await?;
let mut conn = self.pool.acquire().await.map_err(storage_error)?;
let post = self.load_post(&mut conn, request.message_id).await?;
let n_chars = post.text.chars().count();
let offset = (request.offset_chars as usize).min(n_chars);
let text: String = post
.text
.chars()
.skip(offset)
.take((request.limit_chars.get() as usize).min(MAX_READ_CHARS))
.collect();
let next_offset_chars = offset + text.chars().count();
Ok(PostContent {
metadata: post.metadata,
text,
n_chars,
next_offset_chars,
})
}
/// Creates a channel or updates its navigation description without replacing posts,
/// its original author, or its creation time. Only writable connections may call this.
pub async fn upsert_channel(
&self,
caller: ThreadId,
request: UpsertChannelRequest,
) -> Result<()> {
if let Some(access) = self.mode.access() {
access.require_write(self.identity, "channel.edit_metadata")?;
}
let UpsertChannelRequest {
channel_name,
description,
} = request;
validate_channel(&channel_name)?;
let author = self.host.agent_path(caller).await?;
let mut tx = self.begin_write().await?;
let updated = sqlx::query("UPDATE channels SET description=? WHERE board=? AND name=?")
.bind(description.as_str())
.bind(self.identity.to_string())
.bind(&channel_name)
.execute(&mut *tx)
.await
.map_err(storage_error)?
.rows_affected();
if updated != 0 {
return tx.commit().await.map_err(storage_error);
}
tx.rollback().await.map_err(storage_error)?;
// Only creation needs a timestamp. Do not hold a write transaction across
// the host clock call; a concurrent creator is handled by the upsert below.
let now = self.host.current_time(caller).await?;
let mut tx = self.begin_write().await?;
sqlx::query("INSERT INTO channels(board,name,name_search,created_at,timestamp,author,description) VALUES(?,?,?,?,?,?,?) ON CONFLICT(board,name) DO UPDATE SET description=excluded.description")
.bind(self.identity.to_string()).bind(&channel_name).bind(default_case_fold_str(&channel_name))
.bind(now.to_rfc3339()).bind(now.timestamp_micros()).bind(author.to_string()).bind(description.as_str())
.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 {
fn identity(&self) -> SessionId {
self.identity
}
fn storage_namespace(&self) -> Option<&str> {
Some(&self.storage_namespace)
}
fn read_view(&self, caller: ThreadId) -> BoxFuture<'_, Result<Arc<dyn BoardReadView>>> {
Box::pin(async move {
self.host.agent_path(caller).await?;
catalog::capture(self).await
})
}
fn upsert_channel(
&self,
caller: ThreadId,
request: UpsertChannelRequest,
) -> BoxFuture<'_, Result<()>> {
Box::pin(LocalAgentMessageBoard::upsert_channel(
self, caller, request,
))
}
fn create_channel(
&self,
caller: ThreadId,
request: CreateChannelRequest,
) -> BoxFuture<'_, Result<ChannelSummary>> {
Box::pin(LocalAgentMessageBoard::create_channel(
self, caller, request,
))
}
fn post(&self, caller: ThreadId, request: PostRequest) -> BoxFuture<'_, Result<PostMetadata>> {
Box::pin(LocalAgentMessageBoard::post(self, caller, request))
}
fn append(
&self,
caller: ThreadId,
request: AppendRequest,
) -> BoxFuture<'_, Result<PostMetadata>> {
Box::pin(LocalAgentMessageBoard::append(self, caller, request))
}
fn set_subscription(
&self,
caller: ThreadId,
request: SubscriptionRequest,
) -> BoxFuture<'_, Result<SubscriptionState>> {
Box::pin(LocalAgentMessageBoard::set_subscription(
self, caller, request,
))
}
fn subscribed_channels(
&self,
caller: ThreadId,
page: PageRequest,
) -> BoxFuture<'_, Result<Page<String>>> {
Box::pin(LocalAgentMessageBoard::subscribed_channels(
self, caller, page,
))
}
fn set_subscriptions<'a>(
&'a self,
caller: ThreadId,
channels: &'a BTreeMap<&str, SubscriptionChange>,
) -> BoxFuture<'a, Result<()>> {
Box::pin(self.apply_subscriptions(caller, channels))
}
fn read_post(
&self,
caller: ThreadId,
request: ReadPostRequest,
) -> BoxFuture<'_, Result<PostContent>> {
Box::pin(LocalAgentMessageBoard::read_post(self, caller, request))
}
fn list_channels(
&self,
caller: ThreadId,
query: ChannelQuery,
) -> BoxFuture<'_, Result<ChannelPage>> {
Box::pin(async move {
self.host.agent_path(caller).await?;
if let Some(view) = self.mode.view() {
return view.list_channels(query);
}
let mut tx = self.pool.begin().await.map_err(storage_error)?;
let window = Window::new(&query.page)?;
let order = direction(query.direction);
let mut sql = QueryBuilder::new("SELECT c.name FROM channels c WHERE c.board=");
sql.push_bind(self.identity.to_string())
.push(" AND instr(c.name_search,")
.push_bind(default_case_fold_str(&query.query.unwrap_or_default()))
.push(
")>0 ORDER BY COALESCE(
(SELECT MAX(p.timestamp) FROM posts p WHERE p.board=c.board AND p.channel=c.name),
c.timestamp) ",
)
.push(order)
.push(",c.name ")
.push(order)
.push(" LIMIT ")
.push_bind((window.limit + 1) as i64)
.push(" OFFSET ")
.push_bind(window.offset());
let names = sql
.build_query_scalar::<String>()
.fetch_all(&mut *tx)
.await
.map_err(storage_error)?;
let mut channels = Vec::with_capacity(names.len());
for name in names {
channels.push(catalog::channel_summary(self, &mut tx, &name).await?);
}
Ok(ChannelPage {
channels: window.finish(channels)?,
board_permissions: self.mode.access().map(|access| BoardPermissions {
create_channel: matches!(access, Access::ReadWrite),
edit_metadata: false,
manage_permissions: false,
}),
})
})
}
fn list_threads(
&self,
caller: ThreadId,
query: ThreadQuery,
) -> BoxFuture<'_, Result<Page<ThreadSummary>>> {
Box::pin(async move {
self.host.agent_path(caller).await?;
let mut tx = self.pool.begin().await.map_err(storage_error)?;
let exists: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM channels WHERE board=? AND name=?)",
)
.bind(self.identity.to_string())
.bind(&query.channel_name)
.fetch_one(&mut *tx)
.await
.map_err(storage_error)?;
if !exists
|| self.mode.view().is_some_and(|view| {
!view
.channels
.iter()
.any(|channel| channel.channel_name == query.channel_name)
})
{
return Err(invalid("channel not found in this board"));
}
let window = Window::new(&query.page)?;
let order = direction(query.direction);
// Select the page before looking up reply summaries, especially when
// activity sorting examines more roots than the page will return.
let mut sql = QueryBuilder::new("WITH ");
let (roots, by_time, for_count) = if let Some(view) = self.mode.view() {
// A sequence cutoff can make SQLite scan and sort a whole channel or
// thread. Keep the ordered indexes for roots and last activity, and
// allow the reply count to use the sequence range.
sql.push("visible_roots AS NOT MATERIALIZED (SELECT * FROM posts INDEXED BY posts_roots_created WHERE id=root AND seq<=")
.push_bind(view.post_cutoff)
.push("), visible_by_time AS NOT MATERIALIZED (SELECT * FROM posts INDEXED BY posts_board_root_timestamp WHERE seq<=")
.push_bind(view.post_cutoff)
.push("), visible_posts AS NOT MATERIALIZED (SELECT * FROM posts WHERE seq<=")
.push_bind(view.post_cutoff)
.push("), ");
("visible_roots", "visible_by_time", "visible_posts")
} else {
("posts", "posts", "posts")
};
sql.push("page AS MATERIALIZED (SELECT p.board,p.id,p.payload,p.seq,");
match query.sort {
ThreadSort::Created => {
sql.push("p.timestamp");
}
ThreadSort::Activity => {
sql.push("(SELECT MAX(r.timestamp) FROM ")
.push(by_time)
.push(" r WHERE r.board=p.board AND r.root=p.id)");
}
}
sql.push(" AS sort_timestamp FROM ")
.push(roots)
.push(" p WHERE p.board=")
.push_bind(self.identity.to_string())
.push(" AND p.channel=")
.push_bind(query.channel_name)
.push(" AND p.id=p.root ORDER BY sort_timestamp ")
.push(order)
.push(",p.seq ")
.push(order)
.push(" LIMIT ")
.push_bind((window.limit + 1) as i64)
.push(" OFFSET ")
.push_bind(window.offset())
.push(
") SELECT p.payload,
(SELECT COUNT(*) FROM ",
)
.push(for_count)
.push(
" r WHERE r.board=p.board AND r.root=p.id AND r.id<>r.root),
(SELECT r.payload FROM ",
)
.push(by_time)
.push(
" r WHERE r.board=p.board AND r.root=p.id AND r.id<>r.root
ORDER BY r.timestamp DESC,r.seq DESC LIMIT 1)
FROM page p ORDER BY p.sort_timestamp ",
)
.push(order)
.push(",p.seq ")
.push(order);
let rows = sql
.build_query_as::<(String, i64, Option<String>)>()
.fetch_all(&mut *tx)
.await
.map_err(storage_error)?;
let chars = (query.max_chars_per_post.get() as usize)
.min(MAX_READ_CHARS / (2 * rows.len().min(window.limit).max(1)));
let mut threads = Vec::with_capacity(rows.len());
for (root, count, last) in rows {
let root: StoredPost = serde_json::from_str(&root).map_err(storage_error)?;
let id = root.metadata.message_id;
let last: Option<StoredPost> = last
.map(|value| serde_json::from_str(&value))
.transpose()
.map_err(storage_error)?;
let activity = last.as_ref().map_or(root.metadata.created_at, |last| {
last.metadata.created_at.max(root.metadata.created_at)
});
threads.push(ThreadSummary {
thread_id: id,
root_post: preview(root, chars),
reply_count: count as usize,
last_activity_at: activity,
latest_reply: last.map(|post| preview(post, chars)),
});
}
window.finish(threads)
})
}
fn search_posts(
&self,
caller: ThreadId,
query: PostQuery,
) -> BoxFuture<'_, Result<Page<PostPreview>>> {
Box::pin(async move {
self.host.agent_path(caller).await?;
let mut tx = self.pool.begin().await.map_err(storage_error)?;
let window = Window::new(&query.page)?;
let after = if let Some(id) = query.after_message_id {
let lookup = if let Some(view) = self.mode.view() {
sqlx::query_as::<_, (i64, i64)>(
"SELECT timestamp,seq FROM posts WHERE seq<=? AND board=? AND id=?",
)
.bind(view.post_cutoff)
} else {
sqlx::query_as("SELECT timestamp,seq FROM posts WHERE board=? AND id=?")
};
Some(
lookup
.bind(self.identity.to_string())
.bind(id.to_string())
.fetch_optional(&mut *tx)
.await
.map_err(storage_error)?
.ok_or_else(|| invalid("post not found in this board"))?,
)
} else {
None
};
// For a frozen channel page, scan in result order. Otherwise SQLite can
// choose the sequence index for the cutoff and sort the entire channel.
let select = if self.mode.view().is_some() && query.channel_name.is_some() {
"SELECT payload FROM posts INDEXED BY posts_board_channel_timestamp WHERE board="
} else {
"SELECT payload FROM posts WHERE board="
};
let mut sql = QueryBuilder::new(select);
sql.push_bind(self.identity.to_string());
if let Some(view) = self.mode.view() {
sql.push(" AND seq<=").push_bind(view.post_cutoff);
}
if let Some(channel) = query.channel_name {
sql.push(" AND channel=").push_bind(channel);
}
if let Some(author) = query.author {
sql.push(" AND author=").push_bind(author.to_string());
}
if let Some((timestamp, seq)) = after {
sql.push(" AND (timestamp,seq)>(")
.push_bind(timestamp)
.push(",")
.push_bind(seq)
.push(")");
}
let needle = query.query.as_deref().map(default_case_fold_str);
let posts = if let (Some(pointer), Some(needle)) = (
self.nested_json_pointer,
needle.as_deref().filter(|text| !text.is_empty()),
) {
json_search::page(sql, &mut tx, pointer, needle, &window).await?
} else {
if let Some(needle) = needle {
sql.push(" AND instr(body_search,")
.push_bind(needle)
.push(")>0");
}
sql.push(" ORDER BY timestamp DESC,seq DESC LIMIT ")
.push_bind((window.limit + 1) as i64)
.push(" OFFSET ")
.push_bind(window.offset());
decode_posts(
sql.build_query_scalar::<String>()
.fetch_all(&mut *tx)
.await
.map_err(storage_error)?,
)?
};
let chars = (query.max_chars_per_post.get() as usize)
.min(MAX_READ_CHARS / posts.len().min(window.limit).max(1));
window.finish(posts.into_iter().map(|post| preview(post, chars)).collect())
})
}
fn read_thread(
&self,
caller: ThreadId,
request: ReadThreadRequest,
) -> BoxFuture<'_, Result<ThreadPage>> {
Box::pin(async move {
self.host.agent_path(caller).await?;
let mut tx = self.pool.begin().await.map_err(storage_error)?;
let root = self.load_post(&mut tx, request.thread_id).await?;
if root.metadata.thread_id != request.thread_id {
return Err(invalid("thread_id must identify a top-level post"));
}
let window = Window::new(&request.page)?;
let replies = if let Some(view) = self.mode.view() {
sqlx::query_scalar(
"SELECT payload FROM posts INDEXED BY posts_board_root_timestamp
WHERE seq<=? AND board=? AND root=? AND id<>root
ORDER BY timestamp DESC,seq DESC LIMIT ? OFFSET ?",
)
.bind(view.post_cutoff)
} else {
sqlx::query_scalar(
"SELECT payload FROM posts WHERE board=? AND root=? AND id<>root
ORDER BY timestamp DESC,seq DESC LIMIT ? OFFSET ?",
)
};
let posts = decode_posts(
replies
.bind(self.identity.to_string())
.bind(request.thread_id.to_string())
.bind((window.limit + 1) as i64)
.bind(window.offset())
.fetch_all(&mut *tx)
.await
.map_err(storage_error)?,
)?;
let chars = (request.max_chars_per_post.get() as usize)
.min(MAX_READ_CHARS / (posts.len().min(window.limit) + 1));
Ok(ThreadPage {
root_post: preview(root, chars),
replies: window
.finish(posts.into_iter().map(|post| preview(post, chars)).collect())?,
})
})
}
}

View File

@@ -0,0 +1,117 @@
//! Loads initial channels into an empty local board and pins their source template.
use super::insert_channel;
use super::invalid;
use super::options::LocalBoardOptions;
use super::storage_error;
use super::validate_channel;
use crate::ChannelDescription;
use chrono::DateTime;
use chrono::Utc;
use akode_protocol::AgentPath;
use akode_protocol::SessionId;
use akode_protocol::error::Result;
use akode_state::SqliteConfig;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeMap;
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Channel {
#[serde(default, skip_serializing_if = "Option::is_none")]
description: Option<ChannelDescription>,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Template {
version: u32,
#[serde(default)]
channels: BTreeMap<String, Channel>,
}
/// Operator input for loading an empty board. This is not an agent tool.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LocalBoardSetup {
#[serde(default)]
timestamp: Option<DateTime<Utc>>,
template: Template,
}
/// Saves the template and its initial channels atomically. The same template is
/// safe to retry; replacing it or initializing an already-used board is rejected.
pub async fn configure_local_board(
sqlite: &SqliteConfig,
options: &LocalBoardOptions,
board: SessionId,
setup: LocalBoardSetup,
) -> Result<()> {
let template = setup.template;
let encoded = serde_json::to_string(&template).map_err(storage_error)?;
if template.version != 1 || encoded.len() > 64 * 1024 || template.channels.len() > 64 {
return Err(invalid(
"board templates require version 1 and at most 64 KiB / 64 channels",
));
}
for name in template.channels.keys() {
validate_channel(name)?;
}
let pool = super::pool::open(sqlite, options).await?;
let mut tx = pool
.begin_with("BEGIN IMMEDIATE")
.await
.map_err(storage_error)?;
let board_key = board.to_string();
let deleted: bool =
sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM deleted_boards WHERE board=?)")
.bind(&board_key)
.fetch_one(&mut *tx)
.await
.map_err(storage_error)?;
if deleted {
return Err(invalid("the board has been permanently deleted"));
}
let pinned: Option<String> =
sqlx::query_scalar("SELECT template FROM board_templates WHERE board=?")
.bind(&board_key)
.fetch_optional(&mut *tx)
.await
.map_err(storage_error)?;
if let Some(pinned) = pinned {
if pinned != encoded {
return Err(invalid("the board template is already pinned"));
}
} else {
let used: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM channels WHERE board=?)")
.bind(&board_key)
.fetch_one(&mut *tx)
.await
.map_err(storage_error)?;
if used {
return Err(invalid(
"pin the template before creating channels or posts",
));
}
sqlx::query("INSERT INTO board_templates(board,template) VALUES(?,?)")
.bind(&board_key)
.bind(encoded)
.execute(&mut *tx)
.await
.map_err(storage_error)?;
let now = setup.timestamp.unwrap_or_else(Utc::now);
for (name, channel) in &template.channels {
insert_channel(
&mut tx,
board,
name,
channel.description.as_ref(),
&AgentPath::root(),
now,
)
.await?;
}
}
tx.commit().await.map_err(storage_error)
}

View File

@@ -0,0 +1,91 @@
//! Atomic replacement and discovery of a caller's own channel subscriptions.
//! Thread subscriptions and other agents are unaffected; no notifications are emitted.
use super::LocalAgentMessageBoard;
use super::invalid;
use super::storage_error;
use super::target_key;
use super::validate_channel;
use crate::SubscriptionChange;
use crate::SubscriptionTarget;
use akode_protocol::ThreadId;
use akode_protocol::error::Result;
use sqlx::Sqlite;
use sqlx::Transaction;
use std::collections::BTreeMap;
impl LocalAgentMessageBoard {
/// Atomically replaces the caller's membership in the supplied channels.
/// Channels outside this set keep their subscriptions and opt-outs.
/// A read-only live connection permits this self-only operation.
pub(super) async fn apply_subscriptions(
&self,
caller: ThreadId,
channels: &BTreeMap<&str, SubscriptionChange>,
) -> Result<()> {
self.host.agent_path(caller).await?;
for channel in channels.keys() {
validate_channel(channel)?;
}
let names =
serde_json::to_string(&channels.keys().collect::<Vec<_>>()).map_err(storage_error)?;
let mut tx = self.begin_write().await?;
let membership = sqlx::query_as::<_, (String, bool)>(
"SELECT c.name, EXISTS(
SELECT 1 FROM subscriptions AS s WHERE s.board=c.board
AND s.target=json_object('Channel',c.name) AND s.agent=?
) FROM channels AS c WHERE c.board=? AND c.name IN (SELECT value FROM json_each(?))",
)
.bind(caller.to_string())
.bind(self.identity.to_string())
.bind(names)
.fetch_all(&mut *tx)
.await
.map_err(storage_error)?;
if membership.len() != channels.len() {
return Err(invalid("channel not found in this board"));
}
for (name, subscribed) in membership {
let change = channels[name.as_str()];
if subscribed == (change == SubscriptionChange::Subscribe) {
continue;
}
self.change_subscription(&mut tx, &SubscriptionTarget::Channel(name), caller, change)
.await?;
}
tx.commit().await.map_err(storage_error)
}
/// Update explicit membership and its matching implicit-subscription opt-out atomically.
pub(super) async fn change_subscription(
&self,
tx: &mut Transaction<'_, Sqlite>,
target: &SubscriptionTarget,
agent: ThreadId,
change: SubscriptionChange,
) -> Result<()> {
let board = self.identity.to_string();
let target = target_key(target)?;
let agent = agent.to_string();
let statements = match change {
SubscriptionChange::Subscribe => [
"DELETE FROM subscription_opt_outs WHERE board=? AND target=? AND agent=?",
"INSERT OR IGNORE INTO subscriptions(board,target,agent) VALUES(?,?,?)",
],
SubscriptionChange::Unsubscribe => [
"DELETE FROM subscriptions WHERE board=? AND target=? AND agent=?",
"INSERT OR IGNORE INTO subscription_opt_outs(board,target,agent) VALUES(?,?,?)",
],
};
for statement in statements {
sqlx::query(statement)
.bind(&board)
.bind(&target)
.bind(&agent)
.execute(&mut **tx)
.await
.map_err(storage_error)?;
}
Ok(())
}
}

View File

@@ -0,0 +1,84 @@
//! Backend-computed permissions and denials shared by board consumers.
use akode_protocol::error::CodexErr;
use akode_tools::FunctionCallError;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
use serde_json::json;
use std::fmt;
/// Effective board actions for the authenticated caller, not an ACL definition.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct BoardPermissions {
pub create_channel: bool,
pub edit_metadata: bool,
pub manage_permissions: bool,
}
/// Effective channel actions; replying does not imply permission to start a thread.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChannelPermissions {
pub read: bool,
pub post: bool,
pub reply: bool,
pub edit_metadata: bool,
}
/// A backend denial retained through the board's existing error interface.
#[derive(Clone, Debug, Serialize)]
#[serde(tag = "code", rename = "permission_denied")]
pub struct PermissionDenied {
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub action: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
}
impl fmt::Display for PermissionDenied {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "permission_denied: {}", self.message)
}
}
impl std::error::Error for PermissionDenied {}
impl From<PermissionDenied> for CodexErr {
fn from(error: PermissionDenied) -> Self {
Self::Io(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
error,
))
}
}
impl PermissionDenied {
pub(crate) fn model_response(&self, budget: usize) -> Result<Value, FunctionCallError> {
// Keep the denial structured and below 1k tokens, even for oversized service text.
let mut limit = 512;
loop {
let truncated = std::iter::once(self.message.as_str())
.chain(self.action.as_deref())
.chain(self.resource.as_deref())
.any(|text| text.chars().count() > limit);
let mut result = json!({"error": Self {
message: self.message.chars().take(limit).collect(),
action: self.action.as_ref().map(|text| text.chars().take(limit).collect()),
resource: self.resource.as_ref().map(|text| text.chars().take(limit).collect()),
}});
if truncated {
result["error"]["truncated"] = json!(true);
}
if result.to_string().len() <= budget.min(/*other*/ 768) {
return Ok(result);
}
if limit == 0 {
return Err(FunctionCallError::RespondToModel(
"permission_denied: output budget too small for the error".into(),
));
}
limit /= 2;
}
}
}

View File

@@ -0,0 +1,77 @@
//! Read-only board snapshots with a stable channel catalog and post cutoff.
use crate::ChannelPage;
use crate::ChannelQuery;
use crate::ChannelSummary;
use crate::Page;
use crate::PostContent;
use crate::PostPreview;
use crate::PostQuery;
use crate::ReadPostRequest;
use crate::ReadThreadRequest;
use crate::ThreadPage;
use crate::ThreadQuery;
use crate::ThreadSummary;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::error::Result;
use futures::future::BoxFuture;
use std::sync::Arc;
/// A read-only capture of one board. All handles share its namespace, catalog and post cutoff.
/// Later appends and description edits are invisible. Deletion can make captured posts unavailable.
pub trait BoardReadView: Send + Sync {
fn identity(&self) -> SessionId;
fn storage_namespace(&self) -> &str;
fn channels(&self) -> &[ChannelSummary];
/// Keep the capture and search literal values in JSON and in the string-encoded JSON at this pointer.
fn with_json_search(&self, pointer: &'static str) -> Arc<dyn BoardReadView>;
fn list_channels(
&self,
caller: ThreadId,
query: ChannelQuery,
) -> BoxFuture<'_, Result<ChannelPage>>;
fn list_threads(
&self,
caller: ThreadId,
query: ThreadQuery,
) -> BoxFuture<'_, Result<Page<ThreadSummary>>>;
fn search_posts(
&self,
caller: ThreadId,
query: PostQuery,
) -> BoxFuture<'_, Result<Page<PostPreview>>>;
fn read_thread(
&self,
caller: ThreadId,
request: ReadThreadRequest,
) -> BoxFuture<'_, Result<ThreadPage>>;
fn read_post(
&self,
caller: ThreadId,
request: ReadPostRequest,
) -> BoxFuture<'_, Result<PostContent>>;
/// Return one page after the given insertion position, in ascending order.
/// Zero precedes the first post. Positions stay valid across captures of the same board.
/// A page shorter than the default board page size exhausts the captured channel.
fn appended_request_ids<'a>(
&'a self,
caller: ThreadId,
channel: &'a str,
after: i64,
) -> BoxFuture<'a, Result<Vec<(i64, String)>>>;
/// Return whole post bodies for one page in the requested order, within this capture.
fn read_post_texts<'a>(
&'a self,
caller: ThreadId,
positions: &'a [i64],
) -> BoxFuture<'a, Result<Vec<String>>>;
}

View File

@@ -0,0 +1,554 @@
//! Model tools over a caller-bound board. Results stay valid, bounded JSON.
mod arguments;
pub(crate) mod selection;
mod spec;
use self::selection::MessageBoardTool;
use crate::AgentMessageBoard;
use crate::AppendRequest;
use crate::BoardReadView;
use crate::ChannelQuery;
use crate::CreateChannelRequest;
use crate::PageRequest;
use crate::PermissionDenied;
use crate::PostDestination;
use crate::PostQuery;
use crate::PostRequest;
use crate::ReadPostRequest;
use crate::ReadThreadRequest;
use crate::SortDirection;
use crate::SubscriptionChange;
use crate::SubscriptionRequest;
use crate::SubscriptionTarget;
use crate::ThreadQuery;
use crate::ThreadSort;
use akode_protocol::AgentPath;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErrorDetails;
use akode_protocol::openai_models::MultiAgentToolMessages;
use akode_tools::FunctionCallError;
use akode_tools::JsonToolOutput;
use akode_tools::ToolCall;
use akode_tools::ToolCallSource;
use akode_tools::ToolExecutor;
use akode_tools::ToolExecutorFuture;
use akode_tools::ToolName;
use akode_tools::ToolSpec;
use futures::future::BoxFuture;
use serde::Serialize;
use serde_json::Value;
use std::num::NonZeroU32;
use std::sync::Arc;
/// Maximum size of a message-board tool's raw JSON arguments, in KiB.
pub const MAX_TOOL_ARGUMENT_KIB: usize = 128;
/// Maximum response size including JSON escaping and metadata, for direct and Code Mode calls.
pub const MAX_TOOL_RESPONSE_BYTES: usize = 8_000;
/// Creates only the selected tools, in the supplied order, without registering them.
/// The caller and its path must come from the host's authoritative tree metadata.
/// Namespace metadata must match the consumer's other tools. Optional model-catalog
/// descriptions override the bundled descriptions without changing tool parameters.
pub fn message_board_tools(
tools: &[MessageBoardTool],
board: Arc<dyn AgentMessageBoard>,
caller: ThreadId,
caller_path: AgentPath,
namespace: Option<&str>,
namespace_description: &str,
tool_messages: Option<&MultiAgentToolMessages>,
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
bind_tools(
tools,
ToolTarget::Live(board),
caller,
caller_path,
namespace,
namespace_description,
tool_messages,
)
}
/// Creates the channel, thread, search and post read tools for one captured view.
pub fn message_board_read_tools(
view: Arc<dyn BoardReadView>,
caller: ThreadId,
caller_path: AgentPath,
namespace: Option<&str>,
namespace_description: &str,
tool_messages: Option<&MultiAgentToolMessages>,
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
bind_tools(
&MessageBoardTool::READ_ONLY,
ToolTarget::Fixed(view),
caller,
caller_path,
namespace,
namespace_description,
tool_messages,
)
}
fn bind_tools(
tools: &[MessageBoardTool],
target: ToolTarget,
caller: ThreadId,
caller_path: AgentPath,
namespace: Option<&str>,
namespace_description: &str,
tool_messages: Option<&MultiAgentToolMessages>,
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
tools
.iter()
.map(|&tool| {
let name = tool.name();
let tool_message = tool_messages.and_then(|tools| tools.by_name(name));
if tool_message.is_some_and(|tool| tool.parameters.is_some()) {
tracing::warn!(
tool = name,
"Channel tool parameters cannot be overridden; using bundled parameters"
);
}
Arc::new(BoardTool {
caller,
caller_path: caller_path.clone(),
tool,
target: target.clone(),
namespace: namespace.map(str::to_owned),
namespace_description: namespace_description.to_owned(),
description: tool_message.and_then(|tool| tool.description.clone()),
}) as Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>
})
.collect()
}
#[derive(Clone)]
enum ToolTarget {
Live(Arc<dyn AgentMessageBoard>),
Fixed(Arc<dyn BoardReadView>),
}
struct BoardTool {
caller: ThreadId,
caller_path: AgentPath,
tool: MessageBoardTool,
target: ToolTarget,
namespace: Option<String>,
namespace_description: String,
description: Option<String>,
}
impl<'call> ToolExecutor<ToolCall<'call>> for BoardTool {
fn tool_name(&self) -> ToolName {
ToolName::new(self.namespace.clone(), self.tool.name())
}
fn spec(&self) -> ToolSpec {
spec::tool(
self.tool,
self.namespace.as_deref(),
&self.namespace_description,
self.description.as_deref(),
)
}
fn supports_parallel_tool_calls(&self) -> bool {
MessageBoardTool::READ_ONLY.contains(&self.tool)
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(async move {
let raw = call.function_arguments()?;
if raw.len() > MAX_TOOL_ARGUMENT_KIB * 1024 {
return Err(model_error(format!(
"message-board arguments exceed {MAX_TOOL_ARGUMENT_KIB} KiB"
)));
}
let budget = call.response_byte_budget(MAX_TOOL_RESPONSE_BYTES);
let (result, success) = match self.execute(raw, &call, budget).await {
Ok(result) => (result, true),
Err(BoardToolError::Model(error)) => return Err(error),
Err(BoardToolError::PermissionDenied(denied)) => {
(denied.model_response(budget)?, false)
}
};
if result.to_string().len() > budget {
return Err(model_error(
"Result exceeds the output budget. Reduce limit or max_chars_per_post; use read_post with a smaller limit_chars for long posts.",
));
}
Ok(
Box::new(
JsonToolOutput::with_success(result, Some(success)).with_external_context(),
) as Box<dyn akode_tools::ToolOutput>,
)
})
}
}
impl BoardTool {
async fn execute(
&self,
raw: &str,
call: &ToolCall<'_>,
budget: usize,
) -> Result<Value, BoardToolError> {
let caller = self.caller;
let page_limit = |limit: Option<NonZeroU32>| limit.map_or(20, NonZeroU32::get).min(50);
let preview_limit =
|limit: Option<NonZeroU32>| limit.map_or(1000, NonZeroU32::get).min(20_000);
let page = |limit, cursor, scale| PageRequest {
limit: nonzero(limit / scale),
cursor,
};
let direction = |recent_first: Option<bool>| {
if recent_first.unwrap_or(true) {
SortDirection::NewestFirst
} else {
SortDirection::OldestFirst
}
};
match (self.tool, &self.target) {
(MessageBoardTool::UpsertChannel, ToolTarget::Live(board)) => {
let request = serde_json::from_str(raw).map_err(model_error)?;
self.check_mutation_budget(budget, /*target_path_bytes*/ 0)?;
encode(board.upsert_channel(caller, request).await)
}
(MessageBoardTool::CreateChannel, ToolTarget::Live(board)) => {
let arguments::CreateChannel {
channel_name,
description,
subscribe,
} = serde_json::from_str(raw).map_err(model_error)?;
// 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 {
SubscriptionChange::Unsubscribe
},
},
)
.await,
)
}
(MessageBoardTool::GetChannels, target) => {
let arguments::GetChannels {
query,
recent_first,
limit,
cursor,
} = serde_json::from_str(raw).map_err(model_error)?;
let limit = page_limit(limit);
bounded_read(budget, limit, |scale| {
let request = ChannelQuery {
query: query.clone(),
direction: direction(recent_first),
page: page(limit, cursor.clone(), scale),
};
match target {
ToolTarget::Live(board) => board.list_channels(caller, request),
ToolTarget::Fixed(view) => view.list_channels(caller, request),
}
})
.await
}
(MessageBoardTool::ListThreads, target) => {
let arguments::ListThreads {
channel_name,
sort,
recent_first,
limit,
cursor,
max_chars_per_post,
} = serde_json::from_str(raw).map_err(model_error)?;
let limit = page_limit(limit);
let max_chars_per_post = preview_limit(max_chars_per_post);
bounded_read(budget, limit.max(max_chars_per_post), |scale| {
let request = ThreadQuery {
channel_name: channel_name.clone(),
sort: sort.unwrap_or(ThreadSort::Created),
direction: direction(recent_first),
max_chars_per_post: nonzero(max_chars_per_post / scale),
page: page(limit, cursor.clone(), scale),
};
match target {
ToolTarget::Live(board) => board.list_threads(caller, request),
ToolTarget::Fixed(view) => view.list_threads(caller, request),
}
})
.await
}
(MessageBoardTool::SearchPosts, target) => {
let arguments::SearchPosts {
channel_name,
query,
after_message_id,
author,
limit,
cursor,
max_chars_per_post,
} = serde_json::from_str(raw).map_err(model_error)?;
let author = author
.map(|path| self.caller_path.resolve(&path))
.transpose()
.map_err(model_error)?;
let limit = page_limit(limit);
let max_chars_per_post = preview_limit(max_chars_per_post);
bounded_read(budget, limit.max(max_chars_per_post), |scale| {
let request = PostQuery {
channel_name: channel_name.clone(),
query: query.clone(),
after_message_id,
author: author.clone(),
max_chars_per_post: nonzero(max_chars_per_post / scale),
page: page(limit, cursor.clone(), scale),
};
match target {
ToolTarget::Live(board) => board.search_posts(caller, request),
ToolTarget::Fixed(view) => view.search_posts(caller, request),
}
})
.await
}
(MessageBoardTool::ReadThread, target) => {
let arguments::ReadThread {
thread_id,
limit,
cursor,
max_chars_per_post,
} = serde_json::from_str(raw).map_err(model_error)?;
let limit = page_limit(limit);
let max_chars_per_post = preview_limit(max_chars_per_post);
bounded_read(budget, limit.max(max_chars_per_post), |scale| {
let request = ReadThreadRequest {
thread_id,
max_chars_per_post: nonzero(max_chars_per_post / scale),
page: page(limit, cursor.clone(), scale),
};
match target {
ToolTarget::Live(board) => board.read_thread(caller, request),
ToolTarget::Fixed(view) => view.read_thread(caller, request),
}
})
.await
}
(MessageBoardTool::ReadPost, target) => {
let arguments::ReadPost {
message_id,
offset_chars,
limit_chars,
} = serde_json::from_str(raw).map_err(model_error)?;
let limit_chars = limit_chars.map_or(20_000, NonZeroU32::get).min(20_000);
bounded_read(budget, limit_chars, |scale| {
let request = ReadPostRequest {
message_id,
offset_chars: offset_chars.unwrap_or_default(),
limit_chars: nonzero(limit_chars / scale),
};
match target {
ToolTarget::Live(board) => board.read_post(caller, request),
ToolTarget::Fixed(view) => view.read_post(caller, request),
}
})
.await
}
(
MessageBoardTool::Subscribe | MessageBoardTool::Unsubscribe,
ToolTarget::Live(board),
) => {
let arguments::Subscription {
channel_name,
thread_id,
target_agent,
} = serde_json::from_str(raw).map_err(model_error)?;
self.check_mutation_budget(budget, target_agent.as_ref().map_or(0, String::len))?;
let target = match (channel_name, thread_id) {
(Some(channel), None) => SubscriptionTarget::Channel(channel),
(None, Some(thread)) => SubscriptionTarget::Thread(thread),
_ => {
return Err(
model_error("Supply exactly one of channel_name or thread_id").into(),
);
}
};
encode(
board
.set_subscription(
caller,
SubscriptionRequest {
target,
target_agent: target_agent
.map(|path| self.caller_path.resolve(&path))
.transpose()
.map_err(model_error)?,
change: if self.tool == MessageBoardTool::Subscribe {
SubscriptionChange::Subscribe
} else {
SubscriptionChange::Unsubscribe
},
},
)
.await,
)
}
(MessageBoardTool::Post | MessageBoardTool::Append, ToolTarget::Live(board)) => {
let arguments::Post {
text,
channel_name,
new_channel_name,
thread_id,
agents_to_notify,
} = if self.tool == MessageBoardTool::Append {
let args: arguments::Append = serde_json::from_str(raw).map_err(model_error)?;
arguments::Post {
text: args.text,
channel_name: args.channel_name,
new_channel_name: args.new_channel_name,
thread_id: args.thread_id,
agents_to_notify: None,
}
} else {
serde_json::from_str(raw).map_err(model_error)?
};
self.check_mutation_budget(budget, /*target_path_bytes*/ 0)?;
let destination = match (channel_name, new_channel_name, thread_id) {
(Some(channel), None, None) => PostDestination::Channel(channel),
(None, Some(channel), None) => PostDestination::NewChannel(channel),
(None, None, Some(thread)) => PostDestination::Thread(thread),
_ => {
return Err(model_error(
"Supply exactly one of channel_name, new_channel_name or thread_id",
)
.into());
}
};
let invocation = match &call.source {
ToolCallSource::Direct => call.call_id.clone(),
ToolCallSource::CodeMode {
cell_id,
runtime_tool_call_id,
} => format!("{cell_id}:{runtime_tool_call_id}"),
};
let request_id = format!("{}:{invocation}", call.turn_id);
encode(if self.tool == MessageBoardTool::Append {
board
.append(
caller,
AppendRequest {
request_id,
destination,
text,
},
)
.await
} else {
board
.post(
caller,
PostRequest {
request_id,
destination,
text,
agents_to_notify: agents_to_notify
.unwrap_or_default()
.into_iter()
.map(|path| self.caller_path.resolve(&path))
.collect::<Result<_, _>>()
.map_err(model_error)?,
},
)
.await
})
}
(_, ToolTarget::Fixed(_)) => Err(FunctionCallError::Fatal(
"A board mutation was bound to a read-only view".to_string(),
)
.into()),
}
}
fn check_mutation_budget(
&self,
budget: usize,
target_path_bytes: usize,
) -> Result<(), FunctionCallError> {
// Reserve metadata, escaped channel names and agent paths before any write.
if budget < 2048 + self.caller_path.len() + target_path_bytes {
return Err(model_error(
"Output budget is too small to acknowledge a message-board mutation; no change was made.",
));
}
Ok(())
}
}
/// Try the requested read first. Halve limits only when its serialized output is too large.
/// Reissuing the read lets each backend generate a cursor for exactly the returned page.
/// Stop once every limit has reached one; another read would repeat the same request.
async fn bounded_read<'a, T: Serialize>(
budget: usize,
largest_limit: u32,
fetch: impl Fn(u32) -> BoxFuture<'a, akode_protocol::error::Result<T>>,
) -> Result<Value, BoardToolError> {
let mut scale = 1;
loop {
let result = encode(fetch(scale).await)?;
if result.to_string().len() <= budget {
return Ok(result);
}
if largest_limit / scale <= 1 {
break;
}
scale *= 2;
}
Err(model_error("The output budget is too small for this result's metadata.").into())
}
fn nonzero(value: u32) -> NonZeroU32 {
NonZeroU32::new(value).unwrap_or(NonZeroU32::MIN)
}
fn model_error(error: impl std::fmt::Display) -> FunctionCallError {
FunctionCallError::RespondToModel(error.to_string().chars().take(512).collect())
}
enum BoardToolError {
Model(FunctionCallError),
PermissionDenied(PermissionDenied),
}
impl From<FunctionCallError> for BoardToolError {
fn from(error: FunctionCallError) -> Self {
Self::Model(error)
}
}
fn encode<T: Serialize>(value: akode_protocol::error::Result<T>) -> Result<Value, BoardToolError> {
let value = value.map_err(|error| {
if let CodexErrorDetails::Io(io) = error.details()
&& let Some(denied) = io
.get_ref()
.and_then(|source| source.downcast_ref::<PermissionDenied>())
{
BoardToolError::PermissionDenied(denied.clone())
} else {
BoardToolError::Model(model_error(error))
}
})?;
serde_json::to_value(value).map_err(|error| model_error(error).into())
}

View File

@@ -0,0 +1,91 @@
//! Flat model arguments; runtime identities are supplied by the host.
use crate::ChannelDescription;
use crate::ThreadSort;
use serde::Deserialize;
use std::num::NonZeroU32;
use uuid::Uuid;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct CreateChannel {
pub(super) channel_name: String,
pub(super) description: Option<ChannelDescription>,
pub(super) subscribe: Option<bool>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct GetChannels {
pub(super) query: Option<String>,
pub(super) recent_first: Option<bool>,
pub(super) limit: Option<NonZeroU32>,
pub(super) cursor: Option<String>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct ListThreads {
pub(super) channel_name: String,
pub(super) sort: Option<ThreadSort>,
pub(super) recent_first: Option<bool>,
pub(super) limit: Option<NonZeroU32>,
pub(super) cursor: Option<String>,
pub(super) max_chars_per_post: Option<NonZeroU32>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct SearchPosts {
pub(super) channel_name: Option<String>,
pub(super) query: Option<String>,
pub(super) after_message_id: Option<Uuid>,
pub(super) author: Option<String>,
pub(super) limit: Option<NonZeroU32>,
pub(super) cursor: Option<String>,
pub(super) max_chars_per_post: Option<NonZeroU32>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct ReadThread {
pub(super) thread_id: Uuid,
pub(super) limit: Option<NonZeroU32>,
pub(super) cursor: Option<String>,
pub(super) max_chars_per_post: Option<NonZeroU32>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct ReadPost {
pub(super) message_id: Uuid,
pub(super) offset_chars: Option<u32>,
pub(super) limit_chars: Option<NonZeroU32>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct Subscription {
pub(super) channel_name: Option<String>,
pub(super) thread_id: Option<Uuid>,
pub(super) target_agent: Option<String>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct Post {
pub(super) text: String,
pub(super) channel_name: Option<String>,
pub(super) new_channel_name: Option<String>,
pub(super) thread_id: Option<Uuid>,
pub(super) agents_to_notify: Option<Vec<String>>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct Append {
pub(super) text: String,
pub(super) channel_name: Option<String>,
pub(super) new_channel_name: Option<String>,
pub(super) thread_id: Option<Uuid>,
}

View File

@@ -0,0 +1,68 @@
//! Tool choices supplied by consumers. Each tool has one fixed contract.
/// Shared tools a consumer can expose through `message_board_tools`.
/// Tool selection does not grant storage permissions to the underlying connection.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MessageBoardTool {
CreateChannel,
/// Creates a channel or updates its description, without subscriptions or notifications.
UpsertChannel,
GetChannels,
ListThreads,
SearchPosts,
ReadThread,
ReadPost,
Subscribe,
Unsubscribe,
/// Posts, subscribes the author unless opted out, and notifies recipients.
Post,
/// Writes evidence without automatic subscriptions or notifications.
Append,
}
impl MessageBoardTool {
pub(super) const READ_ONLY: [Self; 5] = [
Self::GetChannels,
Self::ListThreads,
Self::SearchPosts,
Self::ReadThread,
Self::ReadPost,
];
/// Existing agent discussion tools, in their original registration order.
pub const DISCUSSION: [Self; 9] = [
Self::CreateChannel,
Self::GetChannels,
Self::ListThreads,
Self::SearchPosts,
Self::ReadThread,
Self::ReadPost,
Self::Subscribe,
Self::Unsubscribe,
Self::Post,
];
/// Bundled schema for discovery before a caller has been bound to a board.
pub fn spec(self) -> akode_tools::ToolSpec {
super::spec::tool(
self, /*namespace*/ None, /*namespace_description*/ "",
/*description_override*/ None,
)
}
pub(super) fn name(self) -> &'static str {
match self {
Self::CreateChannel => "create_channel",
Self::UpsertChannel => "upsert_channel",
Self::GetChannels => "get_channels",
Self::ListThreads => "list_threads",
Self::SearchPosts => "search_posts",
Self::ReadThread => "read_thread",
Self::ReadPost => "read_post",
Self::Subscribe => "subscribe",
Self::Unsubscribe => "unsubscribe",
Self::Post => "post",
Self::Append => "append",
}
}
}

View File

@@ -0,0 +1,153 @@
//! Schemas for shared board tools. The host supplies their selection and namespace.
use super::selection::MessageBoardTool;
use akode_tools::ResponsesApiNamespace;
use akode_tools::ResponsesApiNamespaceTool;
use akode_tools::ResponsesApiTool;
use akode_tools::ToolSpec;
use akode_tools::parse_tool_input_schema;
use serde_json::json;
pub(super) fn tool(
tool: MessageBoardTool,
namespace: Option<&str>,
namespace_description: &str,
description_override: Option<&str>,
) -> ToolSpec {
let (description, fields, required): (&str, &[&str], &[&str]) = match tool {
MessageBoardTool::CreateChannel => (
"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", "description", "subscribe"],
&["channel_name"],
),
MessageBoardTool::UpsertChannel => (
"Create a channel or update only its description. Existing posts, author, creation time and subscriptions are preserved. Does not subscribe anyone or send notifications. Returns null on success.",
&["channel_name", "description"],
&["channel_name", "description"],
),
MessageBoardTool::GetChannels => (
"List channels, most recently active first, or search by a case-insensitive part of the name. Creating a channel or posting in it counts as activity.",
&["query", "recent_first", "limit", "cursor"],
&[],
),
MessageBoardTool::ListThreads => (
"List a channel's threads with previews of the first post and latest reply. New threads come first by default; sorting by activity brings threads with recent replies to the top.",
&[
"channel_name",
"sort",
"recent_first",
"limit",
"cursor",
"max_chars_per_post",
],
&["channel_name"],
),
MessageBoardTool::SearchPosts => (
"Search top-level posts and replies, newest first. Text matches are case-insensitive substrings; omit the query to see recent activity. You can narrow by channel, author, or posts after a message ID. Results are previews; read_post can retrieve the full text.",
&[
"channel_name",
"query",
"after_message_id",
"author",
"limit",
"cursor",
"max_chars_per_post",
],
&[],
),
MessageBoardTool::ReadThread => (
"Read a thread using its first post's message ID. Every page includes previews of the first post and the newest replies; the cursor advances through replies.",
&["thread_id", "limit", "cursor", "max_chars_per_post"],
&["thread_id"],
),
MessageBoardTool::ReadPost => (
"Read a post or reply by message ID, without needing its channel. Offsets count Unicode characters; continue at next_offset_chars while it is less than n_chars.",
&["message_id", "offset_chars", "limit_chars"],
&["message_id"],
),
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"],
&[],
),
MessageBoardTool::Unsubscribe => (
"Unsubscribe yourself or another agent from a channel or thread. Provide exactly one of channel_name or thread_id. Posting again does not undo a thread unsubscribe. Agents explicitly named on a post can still receive that notification.",
&["channel_name", "thread_id", "target_agent"],
&[],
),
MessageBoardTool::Post => (
"Start a thread in an existing or new channel, or reply using the first post's message ID as thread_id. Exactly one destination is required. Posting subscribes you to the thread unless you previously unsubscribed. agents_to_notify requests a one-time notification without subscribing recipients; delivery, queueing, and wake behavior follow the host's agent-message policy. Returns metadata, not the post text.",
&[
"text",
"channel_name",
"new_channel_name",
"thread_id",
"agents_to_notify",
],
&["text"],
),
MessageBoardTool::Append => (
"Store a post in an existing or new channel, or reply using the first post's message ID as thread_id. Exactly one destination is required. Does not subscribe anyone or send notifications, including to existing subscribers. Returns metadata, not the post text.",
&["text", "channel_name", "new_channel_name", "thread_id"],
&["text"],
),
};
let mut properties = serde_json::Map::new();
for field in fields {
let schema = match *field {
"description" if tool == MessageBoardTool::UpsertChannel => {
json!({"type":"string","description":"Channel purpose, at most 512 UTF-8 bytes."})
}
"description" => {
json!({"type":"string","description":"Optional channel purpose, at most 512 UTF-8 bytes."})
}
"new_channel_name" if tool == MessageBoardTool::Append => {
json!({"type":"string","description":"Create this channel without subscribing anyone."})
}
"new_channel_name" => {
json!({"type":"string","description":"Create and subscribe to this channel."})
}
"subscribe" => {
json!({"type":"boolean","description":"Subscribe to new top-level posts. Default true."})
}
"author" | "target_agent" => {
json!({"type":"string","description":"An absolute agent path or a reference relative to you."})
}
"recent_first" => json!({"type":"boolean","description":"Newest first by default."}),
"limit" => {
json!({"type":"integer","minimum":1,"description":"Maximum results, default 20; output budgets may return fewer. Continue with next_cursor."})
}
"offset_chars" => json!({"type":"integer","minimum":0,"description":"Default 0."}),
"limit_chars" | "max_chars_per_post" => {
json!({"type":"integer","minimum":1,"description":"Maximum characters; further capped by output budget. Defaults: limit_chars 20000, max_chars_per_post 1000."})
}
"sort" => json!({"type":"string","enum":["created","activity"]}),
"agents_to_notify" => {
json!({"type":"array","items":{"type":"string"},"description":"Absolute agent paths or references relative to you; maximum 256."})
}
"cursor" => {
json!({"type":"string","description":"Opaque next_cursor from the same query. Keep filters and sorting unchanged. Concurrent posts may shift pages; omit the cursor to refresh."})
}
_ => json!({"type":"string"}),
};
properties.insert((*field).into(), schema);
}
let parameters = json!({"type":"object","properties":properties,"required":required,"additionalProperties":false});
let tool = ResponsesApiTool {
name: tool.name().into(),
description: description_override.unwrap_or(description).into(),
strict: false,
defer_loading: None,
parameters: parse_tool_input_schema(&parameters)
.unwrap_or_else(|error| panic!("message-board schema must parse: {error}")),
output_schema: None,
};
match namespace {
Some(namespace) => ToolSpec::Namespace(ResponsesApiNamespace {
name: namespace.into(),
description: namespace_description.into(),
tools: vec![ResponsesApiNamespaceTool::Function(tool)],
}),
None => ToolSpec::Function(tool),
}
}

View File

@@ -0,0 +1,124 @@
//! Message-board records and notification text shared by backends and tool adapters.
use crate::BoardPermissions;
use crate::ChannelPermissions;
use chrono::DateTime;
use chrono::Utc;
use akode_protocol::AgentPath;
use serde::Deserialize;
use serde::Serialize;
use serde::Serializer;
use serde::ser::SerializeStruct;
use uuid::Uuid;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PostMetadata {
pub message_id: Uuid,
pub channel_name: String,
pub author: AgentPath,
pub thread_id: Uuid,
pub created_at: DateTime<Utc>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PostPreview {
#[serde(flatten)]
pub metadata: PostMetadata,
pub text_preview: String,
pub n_chars: usize,
pub truncated: bool,
}
impl PostPreview {
/// Formats a channel notification from this preview, including its truncation marker.
pub fn notification_text(&self) -> String {
let suffix = if self.truncated {
"\n[Use read_post for the rest.]"
} else {
""
};
format!(
"Message Type: CHANNEL_POST\nSender: {}\nChannel: {}\nMessage ID: {}\nThread ID: {}\nPayload:\n{}{suffix}",
self.metadata.author,
self.metadata.channel_name,
self.metadata.message_id,
self.metadata.thread_id,
self.text_preview,
)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PostContent {
#[serde(flatten)]
pub metadata: PostMetadata,
pub text: String,
pub n_chars: usize,
pub next_offset_chars: usize,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ThreadSummary {
pub thread_id: Uuid,
pub root_post: PostPreview,
pub reply_count: usize,
pub last_activity_at: DateTime<Utc>,
pub latest_reply: Option<PostPreview>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChannelSummary {
/// Absent on boards without ACL metadata; preserve the legacy wire shape.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub permissions: Option<ChannelPermissions>,
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,
pub last_message_id: Option<Uuid>,
}
/// Channel discovery also exposes board actions, including when there are no channels.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChannelPage {
#[serde(flatten)]
pub channels: Page<ChannelSummary>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub board_permissions: Option<BoardPermissions>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SubscriptionState {
pub channel_name: String,
pub thread_id: Option<Uuid>,
pub target_agent: AgentPath,
pub enabled: bool,
pub last_message_id: Option<Uuid>,
}
/// A bounded page. Counts and end-of-list markers are derived at serialization.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
pub struct Page<T> {
pub results: Vec<T>,
pub next_cursor: Option<String>,
}
impl<T: Serialize> Serialize for Page<T> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut page = serializer.serialize_struct("Page", 4)?;
page.serialize_field("results", &self.results)?;
page.serialize_field("n_returned", &self.results.len())?;
page.serialize_field("has_more", &self.next_cursor.is_some())?;
page.serialize_field("next_cursor", &self.next_cursor)?;
page.end()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ThreadPage {
pub root_post: PostPreview,
#[serde(flatten)]
pub replies: Page<PostPreview>,
}

View File

@@ -0,0 +1,82 @@
//! Shared host fixture for board and HTTP integration tests.
use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicI64;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use chrono::DateTime;
use chrono::Utc;
use akode_message_board::*;
use akode_protocol::AgentPath;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result;
use futures::future::BoxFuture;
pub struct Host {
pub clock: AtomicI64,
pub fail_clock: AtomicBool,
pub agent_path_calls: AtomicUsize,
pub members: HashMap<ThreadId, AgentPath>,
pub active: AtomicBool,
pub fail_notifications: AtomicBool,
pub notifications: Mutex<Vec<(ThreadId, PostMetadata)>>,
}
impl MessageBoardHost for Host {
fn agent_path(&self, caller: ThreadId) -> BoxFuture<'_, Result<AgentPath>> {
Box::pin(async move {
self.agent_path_calls.fetch_add(1, Ordering::SeqCst);
self.members
.get(&caller)
.cloned()
.ok_or_else(|| CodexErr::ThreadNotFound(caller))
})
}
fn resolve_agent(&self, path: AgentPath) -> BoxFuture<'_, Result<ThreadId>> {
Box::pin(async move {
self.members
.iter()
.find_map(|(id, member)| (*member == path).then_some(*id))
.ok_or_else(|| CodexErr::InvalidRequest("unknown agent".into()))
})
}
fn current_time(&self, _caller: ThreadId) -> BoxFuture<'_, Result<DateTime<Utc>>> {
Box::pin(async move {
if self.fail_clock.load(Ordering::SeqCst) {
return Err(CodexErr::Io(std::io::Error::other("clock unavailable")));
}
Ok(DateTime::parse_from_rfc3339("2026-09-18T12:00:00Z")
.map_err(|error| CodexErr::Io(std::io::Error::other(error)))?
.with_timezone(&Utc)
+ chrono::Duration::seconds(self.clock.fetch_add(1, Ordering::SeqCst)))
})
}
fn notify(
&self,
recipient: ThreadId,
post: PostPreview,
) -> BoxFuture<'_, Result<NotificationDelivery>> {
Box::pin(async move {
if self.fail_notifications.load(Ordering::SeqCst) {
return Err(CodexErr::Io(std::io::Error::other(
"notification transport failed",
)));
}
if !self.active.load(Ordering::SeqCst) {
return Ok(NotificationDelivery::SkippedInactive);
}
self.notifications
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push((recipient, post.metadata));
Ok(NotificationDelivery::Accepted)
})
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,290 @@
//! Exercises the MCP adapter against the existing board and host fixtures.
use super::*;
use akode_message_board_mcp::MessageBoardMcpServer;
use akode_tools::ToolSpec;
use pretty_assertions::assert_eq;
use rmcp::ServerHandler;
use rmcp::ServiceExt;
use rmcp::model::CallToolRequestParams;
use rmcp::model::CallToolResponse;
use rmcp::model::CallToolResult;
use rmcp::model::RequestId;
use rmcp::model::Tool;
use rmcp::service::RequestContext;
use serde_json::json;
#[tokio::test]
async fn discovery_and_calls_reuse_board_schemas_identity_and_bounded_results() {
for backend in [Backend::Local, Backend::InMemory] {
let dir = tempfile::tempdir().unwrap();
let sqlite = SqliteConfig::new_for_testing(dir.path().to_path_buf().try_into().unwrap());
let caller = ThreadId::new();
let path = AgentPath::root().join("worker").unwrap();
let host = Arc::new(Host {
clock: AtomicI64::default(),
fail_clock: AtomicBool::new(false),
agent_path_calls: AtomicUsize::default(),
members: [(caller, path.clone())].into(),
active: AtomicBool::new(true),
fail_notifications: AtomicBool::new(false),
notifications: Mutex::default(),
});
let board = backend.open(&sqlite, caller.into(), host).await;
let native = message_board_tools(
&MessageBoardTool::DISCUSSION,
board.clone(),
caller,
path.clone(),
/*namespace*/ None,
"",
/*tool_messages*/ None,
);
let adapter = MessageBoardMcpServer::new(
&MessageBoardTool::DISCUSSION,
board.clone(),
caller,
path.clone(),
);
let (server_io, client_io) = tokio::io::duplex(/*max_buf_size*/ 65536);
let (server, client) = tokio::join!(adapter.serve(server_io), ().serve(client_io));
let server = server.unwrap();
let mut client = client.unwrap();
let expected = native
.iter()
.map(|executor| {
let ToolSpec::Function(spec) = executor.spec() else {
panic!("expected function")
};
Tool::new(
spec.name,
spec.description,
Arc::new(
serde_json::from_value(serde_json::to_value(spec.parameters).unwrap())
.unwrap(),
),
)
})
.collect::<Vec<_>>();
assert_eq!(client.list_all_tools().await.unwrap(), expected);
let text = "é\"".repeat(6_000);
let posted = client
.call_tool(
CallToolRequestParams::new("post").with_arguments(
json!({"new_channel_name":"work", "text":text})
.as_object()
.unwrap()
.clone(),
),
)
.await
.unwrap();
assert_eq!(posted.is_error, Some(false));
let metadata: PostMetadata =
serde_json::from_value(posted.structured_content.unwrap()).unwrap();
assert_eq!(metadata.author, path);
let arguments = json!({"message_id":metadata.message_id});
let read = client
.call_tool(
CallToolRequestParams::new("read_post")
.with_arguments(arguments.as_object().unwrap().clone()),
)
.await
.unwrap();
let payload = board_tool_call("read_post", arguments);
let native_read = native
.iter()
.find(|executor| executor.tool_name().name == "read_post")
.unwrap()
.handle(payload.clone())
.await
.unwrap();
let mut expected =
CallToolResult::structured(native_read.code_mode_result(&payload.payload));
// The negotiated legacy wire format omits the newer resultType discriminator.
expected.result_type = None;
assert_eq!(read, expected);
let value = read.structured_content.unwrap();
assert!(value.to_string().len() <= 8_000);
let content: PostContent = serde_json::from_value(value).unwrap();
assert!(content.next_offset_chars < content.n_chars);
assert_eq!(
content.text,
text.chars()
.take(content.next_offset_chars)
.collect::<String>()
);
// Identity is bound by the host, never supplied in model arguments.
let invalid = client
.call_tool(
CallToolRequestParams::new("post").with_arguments(
json!({"new_channel_name":"spoofed", "text":"bad", "caller":ThreadId::new()})
.as_object()
.unwrap()
.clone(),
),
)
.await
.unwrap();
assert_eq!(invalid.is_error, Some(true));
let channels = board
.list_channels(
caller,
ChannelQuery {
query: Some("spoofed".into()),
direction: SortDirection::NewestFirst,
page: PageRequest::default(),
},
)
.await
.unwrap();
assert_eq!(channels.channels.results, Vec::new());
assert!(
client
.call_tool(CallToolRequestParams::new("unknown"))
.await
.is_err()
);
client.close().await.unwrap();
server.waiting().await.unwrap();
}
}
#[tokio::test]
async fn request_identity_deduplicates_within_a_session_but_not_across_sessions() {
let caller = ThreadId::new();
let host = Arc::new(Host {
clock: AtomicI64::default(),
fail_clock: AtomicBool::new(false),
agent_path_calls: AtomicUsize::default(),
members: [(caller, AgentPath::root())].into(),
active: AtomicBool::new(true),
fail_notifications: AtomicBool::new(false),
notifications: Mutex::default(),
});
let board = Arc::new(InMemoryAgentMessageBoard::new(caller.into(), host));
board
.create_channel(
caller,
CreateChannelRequest {
channel_name: "general".into(),
description: None,
subscription: SubscriptionChange::Unsubscribe,
},
)
.await
.unwrap();
let mut posts = Vec::new();
for _ in 0..2 {
let adapter = MessageBoardMcpServer::new(
&[MessageBoardTool::Post],
board.clone(),
caller,
AgentPath::root(),
);
let (server_io, client_io) = tokio::io::duplex(/*max_buf_size*/ 65536);
let (server, client) = tokio::join!(adapter.serve(server_io), ().serve(client_io));
let server = server.unwrap();
let mut client = client.unwrap();
// Use the handler's real session with explicit IDs to exercise retransmission
// and distinguish the JSON-RPC number 7 from the string "7".
for id in [RequestId::Number(7), RequestId::String("7".into())] {
let request = CallToolRequestParams::new("post").with_arguments(
json!({"channel_name":"general", "text":"same request"})
.as_object()
.unwrap()
.clone(),
);
let context = RequestContext::new(id, server.peer().clone());
let first = server
.service()
.call_tool(request.clone(), context.clone())
.await
.unwrap();
let retry = server.service().call_tool(request, context).await.unwrap();
let CallToolResponse::Complete(first) = first else {
panic!("expected completed call")
};
let CallToolResponse::Complete(retry) = retry else {
panic!("expected completed retry")
};
assert_eq!(first.is_error, Some(false));
assert_eq!(first, retry);
posts.push(first);
}
client.close().await.unwrap();
server.waiting().await.unwrap();
}
for (index, post) in posts.iter().enumerate() {
assert!(posts[..index].iter().all(|previous| previous != post));
}
let stored = board
.search_posts(
caller,
PostQuery {
channel_name: Some("general".into()),
query: Some("same request".into()),
after_message_id: None,
author: None,
max_chars_per_post: NonZeroU32::new(100).unwrap(),
page: PageRequest::default(),
},
)
.await
.unwrap();
assert_eq!(stored.results.len(), 4);
}
#[tokio::test]
async fn read_only_connection_returns_the_existing_structured_permission_denial() {
let dir = tempfile::tempdir().unwrap();
let sqlite = SqliteConfig::new_for_testing(dir.path().to_path_buf().try_into().unwrap());
let caller = ThreadId::new();
let host = Arc::new(Host {
clock: AtomicI64::default(),
fail_clock: AtomicBool::new(false),
agent_path_calls: AtomicUsize::default(),
members: [(caller, AgentPath::root())].into(),
active: AtomicBool::new(true),
fail_notifications: AtomicBool::new(false),
notifications: Mutex::default(),
});
let board = Arc::new(
LocalBoard::new(sqlite, caller.into())
.read_only()
.open(host)
.await
.unwrap(),
);
let adapter = MessageBoardMcpServer::new(
&MessageBoardTool::DISCUSSION,
board,
caller,
AgentPath::root(),
);
let (server_io, client_io) = tokio::io::duplex(/*max_buf_size*/ 65536);
let (server, client) = tokio::join!(adapter.serve(server_io), ().serve(client_io));
let server = server.unwrap();
let mut client = client.unwrap();
let result = client
.call_tool(
CallToolRequestParams::new("post").with_arguments(
json!({"new_channel_name":"blocked", "text":"bad"})
.as_object()
.unwrap()
.clone(),
),
)
.await
.unwrap();
let mut expected = CallToolResult::structured_error(json!({"error": {
"code":"permission_denied", "message":"This board connection is read-only.",
"action":"channel.post", "resource":format!("board:{}", SessionId::from(caller)),
}}));
expected.result_type = None;
assert_eq!(result, expected);
client.close().await.unwrap();
server.waiting().await.unwrap();
}

View File

@@ -0,0 +1,257 @@
//! Fixed reads share SQLite storage while preserving the captured catalog and post boundary.
#![cfg(test)]
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn read_views_freeze_catalog_and_pages_without_changing_live_handles()
-> std::result::Result<(), Box<dyn std::error::Error>> {
let dir = tempfile::tempdir()?;
let sqlite = SqliteConfig::new_for_testing(dir.path().to_path_buf().try_into()?);
let root = ThreadId::new();
let host = Arc::new(Host {
clock: AtomicI64::default(),
fail_clock: AtomicBool::new(false),
agent_path_calls: AtomicUsize::default(),
members: [(root, AgentPath::root())].into(),
active: AtomicBool::new(true),
fail_notifications: AtomicBool::new(false),
notifications: Mutex::default(),
});
let writer = LocalAgentMessageBoard::open(
&sqlite,
&LocalBoardOptions::default(),
root.into(),
host.clone(),
)
.await?;
let reader = LocalBoard::new(sqlite.clone(), root.into())
.read_only()
.open(host.clone())
.await?;
for channel in ["alpha", "beta", "empty"] {
writer
.upsert_channel(
root,
UpsertChannelRequest {
channel_name: channel.into(),
description: "Original purpose".to_owned().try_into()?,
},
)
.await?;
}
let original = AppendRequest {
request_id: "original".into(),
destination: PostDestination::Channel("alpha".into()),
text: "proof original".into(),
};
let first = writer.append(root, original).await?;
for (request_id, destination) in [
("second", PostDestination::Channel("alpha".into())),
("reply-one", PostDestination::Thread(first.thread_id)),
("reply-two", PostDestination::Thread(first.thread_id)),
("beta", PostDestination::Channel("beta".into())),
] {
writer
.append(
root,
AppendRequest {
request_id: request_id.into(),
destination,
text: format!("proof {request_id}"),
},
)
.await?;
}
let catalog_query = ChannelQuery {
query: None,
direction: SortDirection::NewestFirst,
page: PageRequest::default(),
};
let before_catalog = reader.list_channels(root, catalog_query.clone()).await?;
let fixed = writer.read_view(root).await?;
assert_eq!(fixed.channels(), before_catalog.channels.results);
assert_eq!(
fixed.list_channels(root, catalog_query.clone()).await?,
before_catalog
);
let page = PageRequest {
cursor: None,
limit: NonZeroU32::MIN,
};
let search = PostQuery {
channel_name: Some("alpha".into()),
query: Some("PROOF".into()),
after_message_id: None,
author: Some(AgentPath::root()),
page: page.clone(),
max_chars_per_post: NonZeroU32::MAX,
};
let before_search = reader.search_posts(root, search.clone()).await?;
let next_search = PostQuery {
page: PageRequest {
cursor: Some(before_search.next_cursor.clone().unwrap()),
..page.clone()
},
..search.clone()
};
let before_next_search = reader.search_posts(root, next_search.clone()).await?;
let threads = ThreadQuery {
channel_name: "alpha".into(),
sort: ThreadSort::Activity,
direction: SortDirection::OldestFirst,
page: PageRequest::default(),
max_chars_per_post: NonZeroU32::MAX,
};
let before_threads = reader.list_threads(root, threads.clone()).await?;
let read_thread = ReadThreadRequest {
thread_id: first.thread_id,
page: page.clone(),
max_chars_per_post: NonZeroU32::MAX,
};
let before_replies = reader.read_thread(root, read_thread.clone()).await?;
let read = ReadPostRequest {
message_id: first.message_id,
offset_chars: 1,
limit_chars: NonZeroU32::MAX,
};
let content = reader.read_post(root, read.clone()).await?;
// Both newer and backdated appends must stay outside the fixed sequence boundary.
let mut later = Vec::new();
for clock in [100, -100] {
host.clock.store(clock, Ordering::SeqCst);
for destination in [
PostDestination::Channel("alpha".into()),
PostDestination::Thread(first.thread_id),
] {
later.push(
writer
.append(
root,
AppendRequest {
request_id: format!("later-{clock}-{destination:?}"),
destination,
text: "proof later".into(),
},
)
.await?,
);
}
}
for channel in ["alpha", "new"] {
writer
.upsert_channel(
root,
UpsertChannelRequest {
channel_name: channel.into(),
description: "Updated purpose".to_owned().try_into()?,
},
)
.await?;
}
assert_eq!(
fixed.search_posts(root, search.clone()).await?,
before_search
);
assert_eq!(
fixed.search_posts(root, next_search).await?,
before_next_search
);
assert_eq!(fixed.list_threads(root, threads).await?, before_threads);
assert_eq!(
fixed.read_thread(root, read_thread.clone()).await?,
before_replies
);
assert_eq!(fixed.read_post(root, read.clone()).await?, content);
assert_eq!(
fixed.list_channels(root, catalog_query.clone()).await?,
before_catalog
);
for post in later {
assert!(
fixed
.read_post(
root,
ReadPostRequest {
message_id: post.message_id,
..read.clone()
}
)
.await
.is_err()
);
assert!(
fixed
.search_posts(
root,
PostQuery {
after_message_id: Some(post.message_id),
..search.clone()
}
)
.await
.is_err()
);
if post.message_id == post.thread_id {
assert!(
fixed
.read_thread(
root,
ReadThreadRequest {
thread_id: post.thread_id,
..read_thread.clone()
}
)
.await
.is_err()
);
}
}
assert!(
fixed
.list_threads(
root,
ThreadQuery {
channel_name: "new".into(),
sort: ThreadSort::Created,
direction: SortDirection::NewestFirst,
page: page.clone(),
max_chars_per_post: NonZeroU32::MAX,
}
)
.await
.is_err()
);
assert_ne!(
reader.search_posts(root, search.clone()).await?,
fixed.search_posts(root, search).await?
);
assert_ne!(
reader.list_channels(root, catalog_query.clone()).await?,
before_catalog
);
assert_eq!(
writer.read_view(root).await?.channels(),
reader
.list_channels(root, catalog_query.clone())
.await?
.channels
.results
);
// A read-only live connection still permits its caller's subscription changes.
let subscription = SubscriptionRequest {
target: SubscriptionTarget::Channel("alpha".into()),
target_agent: None,
change: SubscriptionChange::Subscribe,
};
reader.set_subscription(root, subscription).await?;
assert_eq!(
reader.subscribed_channels(root, page).await?.results,
vec!["alpha".to_owned()]
);
Ok(())
}