Skip to main content

adk_agent/team/
blackboard.rs

1use std::collections::{BTreeSet, HashMap};
2use std::sync::{Arc, RwLock};
3
4use adk_core::{
5    Agent, Artifacts, CallbackContext, Content, EventStream, InvocationContext, Memory,
6    ReadonlyContext, Result, RunConfig, Session, State,
7};
8use async_trait::async_trait;
9use futures::StreamExt;
10use schemars::JsonSchema;
11use serde::{Deserialize, Serialize};
12
13use super::{
14    EventDisposition, RelationshipKind, ResolvedTeamMember, TeamBudget, TeamEdgeStart, TeamError,
15    TeamRuntimeRegistry, TeamTerminationPolicy,
16};
17
18/// Portable, governed shared-transcript team definition.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
20#[serde(rename_all = "camelCase", deny_unknown_fields)]
21pub struct BlackboardSpec {
22    /// Executable root name.
23    pub name: String,
24    /// Human-readable purpose.
25    #[serde(default, skip_serializing_if = "String::is_empty")]
26    pub description: String,
27    /// Exact participant names. Order is meaningful for round-robin scheduling.
28    pub members: Vec<String>,
29    /// Speaker selection strategy.
30    pub schedule: BlackboardSchedule,
31    /// Exact permitted speaker transitions for model-selected scheduling.
32    #[serde(default, skip_serializing_if = "Vec::is_empty")]
33    pub transitions: Vec<BlackboardTransition>,
34    /// Bounded execution and transcript policy.
35    #[serde(default)]
36    pub policy: BlackboardPolicy,
37}
38
39/// Speaker scheduling for a blackboard team.
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
41#[serde(rename_all = "camelCase", tag = "strategy")]
42pub enum BlackboardSchedule {
43    /// Every member speaks once per round in declared order.
44    RoundRobin,
45    /// A designated member selects one permitted speaker per round by emitting
46    /// a normal agent transfer event. The transfer is consumed internally.
47    Selector {
48        /// Selector member name.
49        selector: String,
50    },
51}
52
53/// One exact permitted speaker transition.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
55#[serde(rename_all = "camelCase", deny_unknown_fields)]
56pub struct BlackboardTransition {
57    /// Current speaker or selector.
58    pub from: String,
59    /// Next speaker.
60    pub to: String,
61}
62
63/// Bounded blackboard execution policy.
64#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
65#[serde(rename_all = "camelCase", deny_unknown_fields)]
66pub struct BlackboardPolicy {
67    /// Maximum complete scheduling rounds.
68    pub max_rounds: u32,
69    /// Maximum messages visible to each next speaker.
70    pub history: BlackboardHistoryPolicy,
71    /// Aggregate resource budget.
72    #[serde(default)]
73    pub budget: TeamBudget,
74    /// Clean termination conditions.
75    #[serde(default)]
76    pub termination: TeamTerminationPolicy,
77}
78
79impl Default for BlackboardPolicy {
80    fn default() -> Self {
81        Self {
82            max_rounds: 4,
83            history: BlackboardHistoryPolicy::Last { max_messages: 32 },
84            budget: TeamBudget { max_events: Some(128), ..TeamBudget::default() },
85            termination: TeamTerminationPolicy::default(),
86        }
87    }
88}
89
90/// Transcript projection visible to each blackboard speaker.
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
92#[serde(rename_all = "camelCase", tag = "mode")]
93pub enum BlackboardHistoryPolicy {
94    /// Broadcast the full transcript.
95    Full,
96    /// Broadcast only the most recent messages.
97    Last {
98        /// Maximum visible messages.
99        max_messages: usize,
100    },
101}
102
103impl BlackboardSpec {
104    /// Validates members, bounds, schedule, and exact transitions.
105    pub fn validate(&self) -> std::result::Result<(), TeamError> {
106        if self.name.trim().is_empty() {
107            return Err(TeamError::EmptyName { field: "blackboard.name" });
108        }
109        if self.members.is_empty() {
110            return Err(TeamError::InvalidPolicy("blackboard.members"));
111        }
112        if self.policy.max_rounds == 0 {
113            return Err(TeamError::InvalidPolicy("blackboard.maxRounds"));
114        }
115        if matches!(self.policy.history, BlackboardHistoryPolicy::Last { max_messages: 0 }) {
116            return Err(TeamError::InvalidPolicy("blackboard.history.maxMessages"));
117        }
118        let mut names = BTreeSet::new();
119        for member in &self.members {
120            if member.trim().is_empty() {
121                return Err(TeamError::EmptyName { field: "blackboard.member" });
122            }
123            if !names.insert(member.as_str()) {
124                return Err(TeamError::DuplicateMember(member.clone()));
125            }
126        }
127        if names.contains(self.name.as_str()) {
128            return Err(TeamError::TeamNameCollision(self.name.clone()));
129        }
130        if let BlackboardSchedule::Selector { selector } = &self.schedule {
131            if !names.contains(selector.as_str()) {
132                return Err(TeamError::UnknownCoordinator(selector.clone()));
133            }
134            if !self.transitions.iter().any(|transition| transition.from == *selector) {
135                return Err(TeamError::InvalidPolicy("blackboard.selectorTransitions"));
136            }
137        }
138        let mut transitions = BTreeSet::new();
139        for transition in &self.transitions {
140            if !names.contains(transition.from.as_str()) {
141                return Err(TeamError::UnknownRelationshipMember {
142                    endpoint: "source",
143                    name: transition.from.clone(),
144                });
145            }
146            if !names.contains(transition.to.as_str()) {
147                return Err(TeamError::UnknownRelationshipMember {
148                    endpoint: "target",
149                    name: transition.to.clone(),
150                });
151            }
152            if transition.from == transition.to {
153                return Err(TeamError::SelfRelationship(transition.from.clone()));
154            }
155            if !transitions.insert((transition.from.as_str(), transition.to.as_str())) {
156                return Err(TeamError::InvalidPolicy("blackboard.duplicateTransition"));
157            }
158        }
159        Ok(())
160    }
161
162    /// Binds exact member names and returns an executable blackboard root.
163    pub fn compile(
164        &self,
165        agents: impl IntoIterator<Item = Arc<dyn Agent>>,
166    ) -> std::result::Result<CompiledBlackboardTeam, TeamError> {
167        self.validate()?;
168        let declared: BTreeSet<&str> = self.members.iter().map(String::as_str).collect();
169        let mut registry = HashMap::new();
170        for agent in agents {
171            let name = agent.name().to_string();
172            if !declared.contains(name.as_str()) {
173                return Err(TeamError::UnexpectedAgentBinding(name));
174            }
175            if registry.insert(name.clone(), agent).is_some() {
176                return Err(TeamError::DuplicateAgentBinding(name));
177            }
178        }
179        let members: Vec<Arc<dyn Agent>> = self
180            .members
181            .iter()
182            .map(|name| {
183                registry.get(name).cloned().ok_or_else(|| TeamError::MissingAgent(name.clone()))
184            })
185            .collect::<std::result::Result<_, _>>()?;
186        let roster = self
187            .members
188            .iter()
189            .map(|name| ResolvedTeamMember {
190                member: name.clone(),
191                binding: name.clone(),
192                capabilities: Vec::new(),
193                version: None,
194                digest: None,
195                trust_labels: Vec::new(),
196            })
197            .collect();
198        Ok(CompiledBlackboardTeam {
199            spec: self.clone(),
200            name: self.name.clone(),
201            description: self.description.clone(),
202            members,
203            runtime: Arc::new(TeamRuntimeRegistry::new(
204                self.name.clone(),
205                roster,
206                self.policy.budget.clone(),
207                self.policy.termination.clone(),
208                Vec::new(),
209            )),
210        })
211    }
212}
213
214/// Executable blackboard/group-chat root.
215pub struct CompiledBlackboardTeam {
216    spec: BlackboardSpec,
217    name: String,
218    description: String,
219    members: Vec<Arc<dyn Agent>>,
220    runtime: Arc<TeamRuntimeRegistry>,
221}
222
223impl CompiledBlackboardTeam {
224    /// Returns the portable blackboard definition.
225    pub fn spec(&self) -> &BlackboardSpec {
226        &self.spec
227    }
228
229    /// Returns the latest serializable execution receipt.
230    pub fn execution_snapshot(&self, invocation_id: &str) -> Option<super::TeamExecutionSnapshot> {
231        self.runtime.snapshot(invocation_id)
232    }
233
234    /// Restores a persisted execution receipt for a matching team and roster.
235    pub fn restore_execution_snapshot(
236        &self,
237        snapshot: super::TeamExecutionSnapshot,
238    ) -> std::result::Result<(), TeamError> {
239        self.runtime.restore(snapshot)
240    }
241}
242
243impl std::fmt::Debug for CompiledBlackboardTeam {
244    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
245        formatter
246            .debug_struct("CompiledBlackboardTeam")
247            .field("name", &self.name)
248            .field("members", &self.spec.members)
249            .finish()
250    }
251}
252
253#[async_trait]
254impl Agent for CompiledBlackboardTeam {
255    fn name(&self) -> &str {
256        &self.name
257    }
258
259    fn description(&self) -> &str {
260        &self.description
261    }
262
263    fn sub_agents(&self) -> &[Arc<dyn Agent>] {
264        &self.members
265    }
266
267    fn supports_agent_transfer(&self) -> bool {
268        false
269    }
270
271    async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
272        // A call a person asked for needs an agent that holds it for their decision itself
273        // (spec 3.3 ยง7.4 rule 5).
274        if let Some(refused) = crate::requested_call::refused_by_root(
275            ctx.as_ref(),
276            &self.name,
277            crate::requested_call::RUNS_OTHER_AGENTS,
278        ) {
279            return Ok(refused);
280        }
281        let spec = self.spec.clone();
282        let members = self.members.clone();
283        let runtime = self.runtime.clone();
284        let root_invocation_id = ctx.orchestration_root_invocation_id().to_string();
285        // Attached before any other ledger access so the team budget chains to the run budget.
286        let team_tracker =
287            runtime.budget_tracker(&root_invocation_id, ctx.run_config().budget_tracker.clone());
288        runtime.check_budget(&root_invocation_id)?;
289        let active = runtime.enter(&root_invocation_id);
290        let stream = async_stream::stream! {
291            let _active = active;
292            for _round in 0..spec.policy.max_rounds {
293                let scheduled: Vec<Arc<dyn Agent>> = match &spec.schedule {
294                    BlackboardSchedule::RoundRobin => members.clone(),
295                    BlackboardSchedule::Selector { selector } => {
296                        let Some(selector_agent) = members.iter().find(|member| member.name() == selector).cloned() else {
297                            yield Err(adk_core::AdkError::agent(format!("blackboard selector '{selector}' is unavailable")));
298                            return;
299                        };
300                        vec![selector_agent]
301                    }
302                };
303                let mut selected = None;
304                for speaker in scheduled {
305                    let projected = Arc::new(BlackboardContext::new(
306                        ctx.clone(),
307                        speaker.clone(),
308                        spec.policy.history,
309                        team_tracker.clone(),
310                    ));
311                    let mut events = match speaker.run(projected).await {
312                        Ok(events) => events,
313                        Err(error) => {
314                            runtime.fail(&root_invocation_id, &error);
315                            yield Err(error);
316                            return;
317                        }
318                    };
319                    while let Some(result) = events.next().await {
320                        let mut event = match result {
321                            Ok(event) => event,
322                            Err(error) => {
323                                runtime.fail(&root_invocation_id, &error);
324                                yield Err(error);
325                                return;
326                            }
327                        };
328                        if event.author.is_empty() {
329                            event.author = speaker.name().to_string();
330                        }
331                        if let Some(target) = event.actions.transfer_to_agent.take() {
332                            let allowed = spec.transitions.iter().any(|transition| {
333                                transition.from == speaker.name() && transition.to == target
334                            });
335                            if !allowed {
336                                let error = adk_core::AdkError::agent(format!(
337                                    "blackboard speaker '{}' cannot select '{}'; transition is not declared",
338                                    speaker.name(), target
339                                ));
340                                runtime.fail(&root_invocation_id, &error);
341                                yield Err(error);
342                                return;
343                            }
344                            let edge_id = match runtime.start_edge(
345                                &root_invocation_id,
346                                TeamEdgeStart {
347                                    execution_id: None,
348                                    parent_id: ctx.orchestration_edge_id().map(str::to_string),
349                                    from: speaker.name(),
350                                    to: &target,
351                                    kind: RelationshipKind::Handoff,
352                                    attempt: 1,
353                                },
354                            ) {
355                                Ok(edge_id) => edge_id,
356                                Err(error) => {
357                                    yield Err(error);
358                                    return;
359                                }
360                            };
361                            runtime.finish_edge(&root_invocation_id, &edge_id, None);
362                            selected = Some(target);
363                        }
364                        match runtime.record_event(
365                            &root_invocation_id,
366                            ctx.orchestration_edge_id(),
367                            &mut event,
368                        ) {
369                            Ok(EventDisposition::Continue) => yield Ok(event),
370                            Ok(EventDisposition::Terminate) => {
371                                ctx.end_invocation();
372                                yield Ok(event);
373                                return;
374                            }
375                            // The event's model call already happened, so it is kept
376                            // before the run stops on the shared budget.
377                            Err(error) if error.code.starts_with("budget.") => {
378                                yield Ok(event);
379                                yield Err(error);
380                                return;
381                            }
382                            Err(error) => {
383                                yield Err(error);
384                                return;
385                            }
386                        }
387                    }
388                }
389
390                if let BlackboardSchedule::Selector { selector } = &spec.schedule {
391                    let Some(target) = selected.take() else {
392                        let error = adk_core::AdkError::agent(format!(
393                            "blackboard selector '{selector}' did not select a permitted speaker"
394                        ));
395                        runtime.fail(&root_invocation_id, &error);
396                        yield Err(error);
397                        return;
398                    };
399                    let Some(speaker) = members.iter().find(|member| member.name() == target).cloned() else {
400                        yield Err(adk_core::AdkError::agent(format!("selected blackboard speaker '{target}' is unavailable")));
401                        return;
402                    };
403                    let projected = Arc::new(BlackboardContext::new(
404                        ctx.clone(),
405                        speaker.clone(),
406                        spec.policy.history,
407                        team_tracker.clone(),
408                    ));
409                    let mut events = match speaker.run(projected).await {
410                        Ok(events) => events,
411                        Err(error) => {
412                            runtime.fail(&root_invocation_id, &error);
413                            yield Err(error);
414                            return;
415                        }
416                    };
417                    while let Some(result) = events.next().await {
418                        let mut event = match result {
419                            Ok(event) => event,
420                            Err(error) => {
421                                runtime.fail(&root_invocation_id, &error);
422                                yield Err(error);
423                                return;
424                            }
425                        };
426                        if event.author.is_empty() {
427                            event.author = speaker.name().to_string();
428                        }
429                        if event.actions.transfer_to_agent.is_some() {
430                            let error = adk_core::AdkError::agent(format!(
431                                "selected blackboard speaker '{}' cannot transfer during a selector-managed turn",
432                                speaker.name()
433                            ));
434                            runtime.fail(&root_invocation_id, &error);
435                            yield Err(error);
436                            return;
437                        }
438                        match runtime.record_event(&root_invocation_id, None, &mut event) {
439                            Ok(EventDisposition::Continue) => yield Ok(event),
440                            Ok(EventDisposition::Terminate) => {
441                                ctx.end_invocation();
442                                yield Ok(event);
443                                return;
444                            }
445                            // The event's model call already happened, so it is kept
446                            // before the run stops on the shared budget.
447                            Err(error) if error.code.starts_with("budget.") => {
448                                yield Ok(event);
449                                yield Err(error);
450                                return;
451                            }
452                            Err(error) => {
453                                yield Err(error);
454                                return;
455                            }
456                        }
457                    }
458                }
459            }
460        };
461        Ok(Box::pin(stream))
462    }
463}
464
465struct BlackboardContext {
466    inner: Arc<dyn InvocationContext>,
467    agent: Arc<dyn Agent>,
468    session: ProjectedSession,
469    /// The inner run config with the team budget tracker.
470    config: RunConfig,
471}
472
473impl BlackboardContext {
474    fn new(
475        inner: Arc<dyn InvocationContext>,
476        agent: Arc<dyn Agent>,
477        history_policy: BlackboardHistoryPolicy,
478        budget_tracker: Arc<adk_core::BudgetTracker>,
479    ) -> Self {
480        let mut config = inner.run_config().clone();
481        config.budget_tracker = Some(budget_tracker);
482        // What the other speakers said, called and got back reaches this speaker as
483        // other-agent context, never as turns it appears to have taken itself.
484        let mut history =
485            inner.session().conversation_history_with_context(agent.name(), inner.branch());
486        if let BlackboardHistoryPolicy::Last { max_messages } = history_policy
487            && history.len() > max_messages
488        {
489            history.drain(..history.len() - max_messages);
490        }
491        Self {
492            session: ProjectedSession {
493                id: inner.session().id().to_string(),
494                app_name: inner.session().app_name().to_string(),
495                user_id: inner.session().user_id().to_string(),
496                state: SnapshotState::new(inner.session().state().all()),
497                history,
498            },
499            inner,
500            agent,
501            config,
502        }
503    }
504}
505
506#[async_trait]
507impl ReadonlyContext for BlackboardContext {
508    fn invocation_id(&self) -> &str {
509        self.inner.invocation_id()
510    }
511    fn agent_name(&self) -> &str {
512        self.agent.name()
513    }
514    fn user_id(&self) -> &str {
515        self.inner.user_id()
516    }
517    fn app_name(&self) -> &str {
518        self.inner.app_name()
519    }
520    fn session_id(&self) -> &str {
521        self.inner.session_id()
522    }
523    fn branch(&self) -> &str {
524        self.inner.branch()
525    }
526    fn user_content(&self) -> &Content {
527        self.inner.user_content()
528    }
529
530    fn acting_context(&self) -> adk_core::ActingContext {
531        self.inner.acting_context()
532    }
533
534    fn is_authenticated(&self) -> bool {
535        self.inner.is_authenticated()
536    }
537}
538
539#[async_trait]
540impl CallbackContext for BlackboardContext {
541    fn artifacts(&self) -> Option<Arc<dyn Artifacts>> {
542        self.inner.artifacts()
543    }
544    fn tool_outcome(&self) -> Option<adk_core::ToolOutcome> {
545        self.inner.tool_outcome()
546    }
547    fn tool_name(&self) -> Option<&str> {
548        self.inner.tool_name()
549    }
550    fn tool_input(&self) -> Option<&serde_json::Value> {
551        self.inner.tool_input()
552    }
553    fn shared_state(&self) -> Option<Arc<adk_core::SharedState>> {
554        self.inner.shared_state()
555    }
556}
557
558#[async_trait]
559impl InvocationContext for BlackboardContext {
560    fn agent(&self) -> Arc<dyn Agent> {
561        self.agent.clone()
562    }
563    fn memory(&self) -> Option<Arc<dyn Memory>> {
564        self.inner.memory()
565    }
566    fn session(&self) -> &dyn Session {
567        &self.session
568    }
569    fn run_config(&self) -> &RunConfig {
570        &self.config
571    }
572    fn end_invocation(&self) {
573        self.inner.end_invocation();
574    }
575    fn ended(&self) -> bool {
576        self.inner.ended()
577    }
578    fn is_cancelled(&self) -> bool {
579        self.inner.is_cancelled()
580    }
581    fn user_scopes(&self) -> Vec<String> {
582        self.inner.user_scopes()
583    }
584    fn request_metadata(&self) -> HashMap<String, serde_json::Value> {
585        self.inner.request_metadata()
586    }
587    fn authoritative_transfer_targets(&self) -> bool {
588        true
589    }
590    fn delegation_depth(&self) -> u32 {
591        self.inner.delegation_depth()
592    }
593    fn max_delegation_depth(&self) -> Option<u32> {
594        self.inner.max_delegation_depth()
595    }
596    fn orchestration_root_invocation_id(&self) -> &str {
597        self.inner.orchestration_root_invocation_id()
598    }
599    fn orchestration_edge_id(&self) -> Option<&str> {
600        self.inner.orchestration_edge_id()
601    }
602    fn requires_tool_confirmation(&self, tool_name: &str) -> bool {
603        self.inner.requires_tool_confirmation(tool_name)
604    }
605    fn steering_inbox(&self) -> Option<adk_core::SteeringInbox> {
606        self.inner.steering_inbox()
607    }
608    async fn get_secret(&self, name: &str) -> Result<Option<String>> {
609        self.inner.get_secret(name).await
610    }
611    async fn get_secret_for(&self, request: &adk_core::SecretRequest) -> Result<Option<String>> {
612        self.inner.get_secret_for(request).await
613    }
614}
615
616struct ProjectedSession {
617    id: String,
618    app_name: String,
619    user_id: String,
620    state: SnapshotState,
621    history: Vec<Content>,
622}
623
624impl Session for ProjectedSession {
625    fn id(&self) -> &str {
626        &self.id
627    }
628    fn app_name(&self) -> &str {
629        &self.app_name
630    }
631    fn user_id(&self) -> &str {
632        &self.user_id
633    }
634    fn state(&self) -> &dyn State {
635        &self.state
636    }
637    fn conversation_history(&self) -> Vec<Content> {
638        self.history.clone()
639    }
640}
641
642struct SnapshotState(RwLock<HashMap<String, serde_json::Value>>);
643
644impl SnapshotState {
645    fn new(values: HashMap<String, serde_json::Value>) -> Self {
646        Self(RwLock::new(values))
647    }
648}
649
650impl State for SnapshotState {
651    fn get(&self, key: &str) -> Option<serde_json::Value> {
652        self.0.read().unwrap_or_else(|error| error.into_inner()).get(key).cloned()
653    }
654
655    fn set(&mut self, key: String, value: serde_json::Value) {
656        if adk_core::validate_state_key(&key).is_ok() {
657            self.0.write().unwrap_or_else(|error| error.into_inner()).insert(key, value);
658        }
659    }
660
661    fn all(&self) -> HashMap<String, serde_json::Value> {
662        self.0.read().unwrap_or_else(|error| error.into_inner()).clone()
663    }
664}
665
666#[cfg(test)]
667mod tests {
668    use super::*;
669    use adk_core::Event;
670    use std::sync::atomic::{AtomicUsize, Ordering};
671
672    struct EmptyState;
673
674    impl State for EmptyState {
675        fn get(&self, _key: &str) -> Option<serde_json::Value> {
676            None
677        }
678
679        fn set(&mut self, _key: String, _value: serde_json::Value) {}
680
681        fn all(&self) -> HashMap<String, serde_json::Value> {
682            HashMap::new()
683        }
684    }
685
686    /// A session whose agent-aware projection marks the agent it was built for, so a test
687    /// can tell which projection a speaker received.
688    struct TestSession {
689        context_marker: bool,
690    }
691
692    impl Session for TestSession {
693        fn id(&self) -> &str {
694            "blackboard-session"
695        }
696
697        fn app_name(&self) -> &str {
698            "blackboard-app"
699        }
700
701        fn user_id(&self) -> &str {
702            "blackboard-user"
703        }
704
705        fn state(&self) -> &dyn State {
706            &EmptyState
707        }
708
709        fn conversation_history(&self) -> Vec<Content> {
710            (0..4).map(|index| Content::new("user").with_text(format!("message-{index}"))).collect()
711        }
712
713        fn conversation_history_with_context(
714            &self,
715            agent_name: &str,
716            branch: &str,
717        ) -> Vec<Content> {
718            if !self.context_marker {
719                return self.conversation_history_scoped(None, branch);
720            }
721            vec![Content::new("user").with_text(format!("context-for:{agent_name}"))]
722        }
723    }
724
725    struct TestContext {
726        content: Content,
727        config: RunConfig,
728        session: TestSession,
729    }
730
731    #[async_trait]
732    impl ReadonlyContext for TestContext {
733        fn invocation_id(&self) -> &str {
734            "blackboard-invocation"
735        }
736
737        fn agent_name(&self) -> &str {
738            "blackboard"
739        }
740
741        fn user_id(&self) -> &str {
742            "blackboard-user"
743        }
744
745        fn app_name(&self) -> &str {
746            "blackboard-app"
747        }
748
749        fn session_id(&self) -> &str {
750            "blackboard-session"
751        }
752
753        fn branch(&self) -> &str {
754            ""
755        }
756
757        fn user_content(&self) -> &Content {
758            &self.content
759        }
760    }
761
762    #[async_trait]
763    impl CallbackContext for TestContext {
764        fn artifacts(&self) -> Option<Arc<dyn Artifacts>> {
765            None
766        }
767    }
768
769    #[async_trait]
770    impl InvocationContext for TestContext {
771        fn agent(&self) -> Arc<dyn Agent> {
772            panic!("not used")
773        }
774
775        fn memory(&self) -> Option<Arc<dyn Memory>> {
776            None
777        }
778
779        fn session(&self) -> &dyn Session {
780            &self.session
781        }
782
783        fn run_config(&self) -> &RunConfig {
784            &self.config
785        }
786
787        fn end_invocation(&self) {}
788
789        fn ended(&self) -> bool {
790            false
791        }
792    }
793
794    struct Speaker {
795        name: String,
796        transfer: Option<String>,
797        expected_history: usize,
798        runs: Arc<AtomicUsize>,
799    }
800
801    #[async_trait]
802    impl Agent for Speaker {
803        fn name(&self) -> &str {
804            &self.name
805        }
806
807        fn description(&self) -> &str {
808            "deterministic blackboard speaker"
809        }
810
811        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
812            &[]
813        }
814
815        async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
816            assert_eq!(ctx.session().conversation_history().len(), self.expected_history);
817            self.runs.fetch_add(1, Ordering::SeqCst);
818            let mut event = Event::new(ctx.invocation_id());
819            event.author = self.name.clone();
820            event.actions.transfer_to_agent.clone_from(&self.transfer);
821            event.llm_response.content = Some(Content::new("model").with_text(&self.name));
822            Ok(Box::pin(futures::stream::once(async { Ok(event) })))
823        }
824    }
825
826    fn context() -> Arc<TestContext> {
827        Arc::new(TestContext {
828            content: Content::new("user").with_text("discuss"),
829            config: RunConfig::default(),
830            session: TestSession { context_marker: false },
831        })
832    }
833
834    /// Records the history each run receives.
835    struct Recorder {
836        name: String,
837        seen: Arc<std::sync::Mutex<Vec<Vec<Content>>>>,
838    }
839
840    #[async_trait]
841    impl Agent for Recorder {
842        fn name(&self) -> &str {
843            &self.name
844        }
845
846        fn description(&self) -> &str {
847            "records the history it is given"
848        }
849
850        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
851            &[]
852        }
853
854        async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
855            self.seen.lock().unwrap().push(ctx.session().conversation_history());
856            let mut event = Event::new(ctx.invocation_id());
857            event.author = self.name.clone();
858            event.llm_response.content = Some(Content::new("model").with_text(&self.name));
859            Ok(Box::pin(futures::stream::once(async { Ok(event) })))
860        }
861    }
862
863    #[tokio::test]
864    async fn speakers_see_other_speakers_as_context() {
865        let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
866        let spec = BlackboardSpec {
867            name: "blackboard".to_string(),
868            description: String::new(),
869            members: vec!["first".to_string(), "second".to_string()],
870            schedule: BlackboardSchedule::RoundRobin,
871            transitions: Vec::new(),
872            policy: BlackboardPolicy {
873                max_rounds: 1,
874                history: BlackboardHistoryPolicy::Full,
875                ..BlackboardPolicy::default()
876            },
877        };
878        let team = spec
879            .compile(["first", "second"].map(|name| {
880                Arc::new(Recorder { name: name.to_string(), seen: seen.clone() }) as Arc<dyn Agent>
881            }))
882            .unwrap();
883        let ctx = Arc::new(TestContext {
884            content: Content::new("user").with_text("discuss"),
885            config: RunConfig::default(),
886            session: TestSession { context_marker: true },
887        });
888        let events = team.run(ctx).await.unwrap().collect::<Vec<_>>().await;
889        assert_eq!(events.len(), 2);
890        let seen: Vec<Vec<(String, String)>> = seen
891            .lock()
892            .unwrap()
893            .iter()
894            .map(|history| {
895                history
896                    .iter()
897                    .map(|content| {
898                        let text = content.parts.iter().filter_map(|part| part.text()).collect();
899                        (content.role.clone(), text)
900                    })
901                    .collect()
902            })
903            .collect();
904        let marker = |name: &str| vec![("user".to_string(), format!("context-for:{name}"))];
905        assert_eq!(seen, vec![marker("first"), marker("second")]);
906    }
907
908    #[tokio::test]
909    async fn round_robin_bounds_rounds_and_projects_history() {
910        let first_runs = Arc::new(AtomicUsize::new(0));
911        let second_runs = Arc::new(AtomicUsize::new(0));
912        let spec = BlackboardSpec {
913            name: "blackboard".to_string(),
914            description: String::new(),
915            members: vec!["first".to_string(), "second".to_string()],
916            schedule: BlackboardSchedule::RoundRobin,
917            transitions: Vec::new(),
918            policy: BlackboardPolicy {
919                max_rounds: 2,
920                history: BlackboardHistoryPolicy::Last { max_messages: 2 },
921                ..BlackboardPolicy::default()
922            },
923        };
924        let team = spec
925            .compile([
926                Arc::new(Speaker {
927                    name: "first".to_string(),
928                    transfer: None,
929                    expected_history: 2,
930                    runs: first_runs.clone(),
931                }) as Arc<dyn Agent>,
932                Arc::new(Speaker {
933                    name: "second".to_string(),
934                    transfer: None,
935                    expected_history: 2,
936                    runs: second_runs.clone(),
937                }),
938            ])
939            .unwrap();
940        let events = team.run(context()).await.unwrap().collect::<Vec<_>>().await;
941        assert_eq!(events.len(), 4);
942        assert_eq!(first_runs.load(Ordering::SeqCst), 2);
943        assert_eq!(second_runs.load(Ordering::SeqCst), 2);
944    }
945
946    #[tokio::test]
947    async fn selector_enforces_exact_transition_allowlist() {
948        let spec = BlackboardSpec {
949            name: "blackboard".to_string(),
950            description: String::new(),
951            members: vec!["selector".to_string(), "speaker".to_string()],
952            schedule: BlackboardSchedule::Selector { selector: "selector".to_string() },
953            transitions: vec![BlackboardTransition {
954                from: "selector".to_string(),
955                to: "speaker".to_string(),
956            }],
957            policy: BlackboardPolicy { max_rounds: 1, ..BlackboardPolicy::default() },
958        };
959        let team = spec
960            .compile([
961                Arc::new(Speaker {
962                    name: "selector".to_string(),
963                    transfer: Some("undeclared".to_string()),
964                    expected_history: 4,
965                    runs: Arc::new(AtomicUsize::new(0)),
966                }) as Arc<dyn Agent>,
967                Arc::new(Speaker {
968                    name: "speaker".to_string(),
969                    transfer: None,
970                    expected_history: 4,
971                    runs: Arc::new(AtomicUsize::new(0)),
972                }),
973            ])
974            .unwrap();
975        let events = team.run(context()).await.unwrap().collect::<Vec<_>>().await;
976        assert!(events[0].as_ref().unwrap_err().to_string().contains("not declared"));
977    }
978}