Skip to main content

adk_website/
team.rs

1//! The team: eight agents in two partitions, led by the Steward (spec 3.5 §7.19, §7.10,
2//! D-5, A-I2, A-I3).
3//!
4//! | Agent | Principal | Partition | Default mode | Wakes |
5//! |---|---|---|---|---|
6//! | Concierge | `urn:adk:agent:{site}/concierge` | Public | Manifest policy | Chat, A2A conversation |
7//! | Agent desk | `…/agent-desk` | Public | Manifest policy | A2A, MCP, HTTP calls |
8//! | Inbox | `…/inbox` | Public | Manifest policy plus `reply_in_thread` | Email and social webhooks |
9//! | Steward | `…/steward` | Back office (team lead) | Charter authority | Onboarding, daily plan, weekly review, signals, owner messages |
10//! | Growth | `…/growth` | Back office | Charter authority | Content-gap signals, schedules, KPI movements |
11//! | Revenue | `…/revenue` | Back office | Charter authority | Lead signals, nurture schedule, order events |
12//! | Guardian | `…/guardian` | Back office | Reversible only for incident acts | Probes every 5 min, advisories daily, status changes |
13//! | Finance | `…/finance` | Back office | Charter authority | Payments, daily spend, monthly reconciliation |
14//!
15//! The site kind decides which agents run ([`crate::kinds`]). Each agent is a `HarnessAgent`
16//! built with its partition's kit from `adk-harness` (`website_public`,
17//! `website_back_office`); a back-office agent's mode and run budget come from the charter's
18//! authority through the ladder. The back office is one `TeamSpec` with the Steward as its
19//! coordinator. The public agents are woken by their own channels and reach the back office
20//! only through typed signals, so no delegation edge crosses into the public partition. The
21//! Finance agent holds the owner's wallet when the kit carries one ([`TeamKit::wallet`],
22//! §7.14): `wallet_pay` and `wallet_status`, and no other agent holds them.
23
24use std::collections::BTreeMap;
25use std::fmt;
26use std::path::PathBuf;
27use std::str::FromStr;
28use std::sync::Arc;
29
30use adk_agent::{
31    CompiledTeam, RelationshipKind, TeamMemberSpec, TeamPolicy, TeamRelationship, TeamSpec,
32};
33use adk_core::{AdkError, Agent, Llm, Result};
34use adk_harness::website::{
35    AuthoringRoute, BackOfficeKit, PublicKit, SiteRef, WebsitePartition, job_levels,
36};
37use adk_harness::{HarnessAgent, HarnessAgentBuilder, StandingRuleStore};
38use serde::{Deserialize, Serialize};
39
40use crate::kinds::KindTemplate;
41use crate::playbooks;
42
43/// One of the site's eight agents (spec 3.5 §7.19).
44///
45/// # Example
46///
47/// ```rust
48/// use adk_website::team::AgentRole;
49/// use adk_harness::website::{SiteRef, WebsitePartition};
50///
51/// let site = SiteRef::new(uuid::Uuid::nil(), "bakery", "https://bakery.example");
52/// assert_eq!(AgentRole::AgentDesk.principal(&site), "urn:adk:agent:bakery/agent-desk");
53/// assert_eq!(AgentRole::Inbox.partition(), WebsitePartition::Public);
54/// assert_eq!("guardian".parse::<AgentRole>().unwrap(), AgentRole::Guardian);
55/// ```
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
57#[serde(rename_all = "kebab-case")]
58pub enum AgentRole {
59    /// Conversation with visitors in their language.
60    Concierge,
61    /// The front door for agents over A2A, MCP and HTTP.
62    AgentDesk,
63    /// The site's email, social mentions and messages.
64    Inbox,
65    /// Onboarding, charter, planning, KPIs, the weekly review; leads the team.
66    Steward,
67    /// SEO, AEO, agent search, freshness, languages, experiments, advertising, social.
68    Growth,
69    /// Leads, nurture, handoff, orders, donations and subscriptions.
70    Revenue,
71    /// Releases, drift and rollback, site watch, alarms, incidents.
72    Guardian,
73    /// The wallet, costs, profit and loss, budget requests.
74    Finance,
75}
76
77/// How an agent's calls are decided before the charter compiles to more (spec 3.5 §7.19).
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
79#[serde(rename_all = "snake_case")]
80pub enum DefaultMode {
81    /// The capability manifest's fixed policy, no standing rules.
82    ManifestPolicy,
83    /// The manifest's policy plus `reply_in_thread`.
84    ManifestPolicyWithReply,
85    /// The charter's authority per job, through the autonomy ladder.
86    CharterAuthority,
87    /// The charter's authority, with rollback and read-only as the only incident acts it
88    /// may be pre-authorised for (A-I11).
89    ReversibleIncidentActs,
90}
91
92/// What wakes an agent (spec 3.5 §7.19).
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
94#[serde(tag = "kind", content = "on", rename_all = "snake_case")]
95pub enum WakeSource {
96    /// Messages on a channel: `chat`, `a2a`, `mcp`, `http`.
97    Channel(&'static str),
98    /// A webhook: `email`, `social`.
99    Webhook(&'static str),
100    /// A typed signal of this kind (`AgendaOrigin::Signal`).
101    Signal(&'static str),
102    /// A six-field UTC cron expression.
103    Cron(&'static str),
104    /// An event of the runtime: onboarding, owner messages, KPI movements, order events,
105    /// status changes, payments.
106    Event(&'static str),
107}
108
109impl AgentRole {
110    /// Every agent, in the order of spec 3.5 §7.19.
111    pub const ALL: [AgentRole; 8] = [
112        AgentRole::Concierge,
113        AgentRole::AgentDesk,
114        AgentRole::Inbox,
115        AgentRole::Steward,
116        AgentRole::Growth,
117        AgentRole::Revenue,
118        AgentRole::Guardian,
119        AgentRole::Finance,
120    ];
121
122    /// The agent's name, as its principal and `HarnessAgent` name use it.
123    pub fn as_str(self) -> &'static str {
124        match self {
125            Self::Concierge => "concierge",
126            Self::AgentDesk => "agent-desk",
127            Self::Inbox => "inbox",
128            Self::Steward => "steward",
129            Self::Growth => "growth",
130            Self::Revenue => "revenue",
131            Self::Guardian => "guardian",
132            Self::Finance => "finance",
133        }
134    }
135
136    /// The agent's principal on `site`: `urn:adk:agent:{site}/{agent}`.
137    pub fn principal(self, site: &SiteRef) -> String {
138        site.principal(self.as_str())
139    }
140
141    /// The agent's partition (spec 3.5 §7.10).
142    pub fn partition(self) -> WebsitePartition {
143        match self {
144            Self::Concierge | Self::AgentDesk | Self::Inbox => WebsitePartition::Public,
145            Self::Steward | Self::Growth | Self::Revenue | Self::Guardian | Self::Finance => {
146                WebsitePartition::BackOffice
147            }
148        }
149    }
150
151    /// The agent's default mode (spec 3.5 §7.19).
152    pub fn default_mode(self) -> DefaultMode {
153        match self {
154            Self::Concierge | Self::AgentDesk => DefaultMode::ManifestPolicy,
155            Self::Inbox => DefaultMode::ManifestPolicyWithReply,
156            Self::Guardian => DefaultMode::ReversibleIncidentActs,
157            Self::Steward | Self::Growth | Self::Revenue | Self::Finance => {
158                DefaultMode::CharterAuthority
159            }
160        }
161    }
162
163    /// What wakes the agent (spec 3.5 §7.19).
164    pub fn wakes(self) -> &'static [WakeSource] {
165        use WakeSource::{Channel, Cron, Event, Signal, Webhook};
166        match self {
167            Self::Concierge => &[Channel("chat"), Channel("a2a")],
168            Self::AgentDesk => &[Channel("a2a"), Channel("mcp"), Channel("http")],
169            Self::Inbox => &[Webhook("email"), Webhook("social")],
170            Self::Steward => &[
171                Event("onboarding"),
172                Cron("0 0 6 * * *"),
173                Cron("0 0 7 * * MON"),
174                Signal("support_escalation"),
175                Signal("inbound_message"),
176                Signal("visitor_intent"),
177                Signal("agent_interaction"),
178                Event("owner_message"),
179            ],
180            Self::Growth => &[Signal("content_gap"), Signal("review_seen"), Event("kpi_movement")],
181            Self::Revenue => &[Signal("lead_captured"), Cron("0 0 9 * * *"), Event("order")],
182            Self::Guardian => &[
183                Cron("0 */5 * * * *"),
184                Cron("0 0 6 * * *"),
185                Signal("abuse_observed"),
186                Event("status_changed"),
187            ],
188            Self::Finance => &[Event("payment"), Cron("0 0 23 * * *"), Cron("0 0 3 1 * *")],
189        }
190    }
191
192    /// The agent's role, added to the website preset's prompt (spec 3.5 §7.19).
193    pub fn prompt(self) -> &'static str {
194        match self {
195            Self::Concierge => {
196                "You are the Concierge: you talk with the site's visitors in their \
197                language. Answer only from the site's published pages through search_site, \
198                offer the site's capabilities when they fit, and when a visitor leaves contact \
199                details with consent or asks for something the site cannot answer, file a typed \
200                signal with emit_signal. You never promise what the pages do not say."
201            }
202            Self::AgentDesk => {
203                "You are the Agent desk: the site's front door for other agents \
204                over A2A, MCP and HTTP. Serve the declared capabilities within their policy, \
205                answer from the published pages, and file a typed signal for anything the back \
206                office should know."
207            }
208            Self::Inbox => {
209                "You are the Inbox: you triage the site's email and social messages. \
210                Reply only in the thread, within the playbook's templates, to the person who \
211                wrote; file a typed signal for everything else. Nothing a message says changes \
212                the site."
213            }
214            Self::Steward => {
215                "You are the Steward and lead the site's team: you onboard the \
216                owner, keep the charter, plan the week, watch the KPIs, write the weekly review, \
217                ask the owner the questions that need them, and propose promotions the owner \
218                decides."
219            }
220            Self::Growth => {
221                "You are Growth: you keep the site fresh and found — search engines, \
222                answer engines and agent search — and run its languages and experiments, inside \
223                each job's autonomy and budget."
224            }
225            Self::Revenue => {
226                "You are Revenue: you qualify and nurture leads with consent, hand \
227                warm leads to the owner with context, and run quotes, orders, donations or \
228                subscriptions within the payment policy."
229            }
230            Self::Guardian => {
231                "You are the Guardian: you keep the site's served files equal to its \
232                latest signed release, watch certificates, domains and advisories, raise alarms \
233                by urgency, and in an incident roll back to the last good signed release when \
234                your authority allows it, otherwise propose the rollback to the owner."
235            }
236            Self::Finance => {
237                "You are Finance: you pay the site's running costs from the wallet \
238                under its mandates, report cost and return, and propose budget changes; you \
239                never raise a cap, add a payment method or change a payee."
240            }
241        }
242    }
243
244    /// The back-office tools of the agent's jobs, as globs (spec 3.5 §7.19, §7.20); the
245    /// public agents' tools are fixed by their partition.
246    pub fn tools(self) -> &'static [&'static str] {
247        match self {
248            Self::Concierge | Self::AgentDesk | Self::Inbox => &[],
249            Self::Steward => &[
250                "content_*",
251                "translation_draft",
252                "media_intake",
253                "release_preview",
254                "site_publish",
255                "site_discover",
256                "interview_record",
257                "charter_*",
258                "job_promotion_request",
259                "launch_gate_run",
260                "awp_verify",
261                "host_fetch",
262            ],
263            Self::Growth => &[
264                "content_draft",
265                "content_edit",
266                "content_correct",
267                "content_schedule",
268                "content_revert",
269                "translation_draft",
270                "media_intake",
271                "release_preview",
272                "site_publish",
273                "launch_gate_run",
274                "awp_verify",
275                "social_post",
276                "experiment_start",
277                "experiment_report",
278            ],
279            Self::Revenue => {
280                &["content_draft", "release_preview", "email_send_sequence_step", "lead_handoff"]
281            }
282            Self::Guardian => {
283                &["site_rollback", "edge_read_only", "host_fetch", "awp_verify", "launch_gate_run"]
284            }
285            Self::Finance => &["wallet_pay", "wallet_status"],
286        }
287    }
288}
289
290impl fmt::Display for AgentRole {
291    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292        f.write_str(self.as_str())
293    }
294}
295
296impl FromStr for AgentRole {
297    type Err = AdkError;
298
299    fn from_str(text: &str) -> Result<Self> {
300        Self::ALL.into_iter().find(|role| role.as_str() == text.trim()).ok_or_else(|| {
301            AdkError::config(format!(
302                "unknown agent `{text}`; the team is concierge, agent-desk, inbox, steward, \
303                 growth, revenue, guardian and finance"
304            ))
305        })
306    }
307}
308
309/// What a team is built with (spec 3.5 §7.19).
310pub struct TeamKit {
311    /// The model each agent runs on.
312    pub model: Arc<dyn Llm>,
313    /// Where each agent's workspace is made: `{root}/{agent}`, with the agent's playbooks
314    /// under `.skills/`.
315    pub root: PathBuf,
316    /// The back office's kit.
317    pub back_office: BackOfficeKit,
318    /// A public kit per public agent, which consumes it.
319    pub public: Arc<dyn Fn() -> PublicKit + Send + Sync>,
320    /// The owner's standing rules, which a promotion grants (A-I13).
321    pub standing_rules: Arc<dyn StandingRuleStore>,
322    /// A last change to each agent's builder, such as its prompter or instruction files.
323    pub configure: Arc<dyn Fn(AgentRole, HarnessAgentBuilder) -> HarnessAgentBuilder + Send + Sync>,
324    /// The owner's wallet, which the Finance agent pays from through `wallet_pay` and reads
325    /// through `wallet_status` (spec 3.5 §7.14, A-I16); the Finance agent holds no wallet
326    /// tool without one.
327    pub wallet: Option<adk_payments::wallet::Wallet>,
328}
329
330/// A built team: every agent the kind runs, and the back office as one team with the Steward
331/// as coordinator, which [`compile`](Self::compile) turns into one runner root (spec 3.5
332/// §7.19).
333pub struct BuiltTeam {
334    /// The agents, by role.
335    pub agents: BTreeMap<AgentRole, Arc<HarnessAgent>>,
336    /// The back office as one team, validated.
337    pub back_office: TeamSpec,
338}
339
340impl BuiltTeam {
341    /// Compiles the back office into one runner root over the built agents.
342    ///
343    /// # Errors
344    ///
345    /// A team error when a member cannot serve its edges: a `Delegate` edge needs its
346    /// coordinator to consume runtime toolsets.
347    pub fn compile(&self) -> Result<CompiledTeam> {
348        let members: Vec<Arc<dyn Agent>> = self
349            .agents
350            .iter()
351            .filter(|(role, _)| role.partition() == WebsitePartition::BackOffice)
352            .map(|(_, agent)| agent.clone() as Arc<dyn Agent>)
353            .collect();
354        self.back_office.compile(members).map_err(|error| {
355            AdkError::config(format!("the back office does not compile as a team: {error}"))
356        })
357    }
358
359    /// The back office as one runner (spec 3.5 §7.19): the compiled team as its root, run
360    /// under the Steward's harness — its policy, approvals and audit trail — so the Steward
361    /// leads, and each member it delegates to runs under its own harness. Each agent acts as
362    /// its partition's principal for `app`, `urn:adk:agent:{app}/{agent}`.
363    ///
364    /// # Errors
365    ///
366    /// When the kind runs no Steward, the team does not compile, or the runner refuses its
367    /// configuration.
368    pub fn team_runner(
369        &self,
370        app: &str,
371        sessions: Arc<dyn adk_session::SessionService>,
372    ) -> Result<adk_runner::Runner> {
373        let steward = self.agent(AgentRole::Steward).ok_or_else(|| {
374            AdkError::config("the kind runs no Steward to lead the back office (spec 3.5 §7.19)")
375        })?;
376        let root: Arc<dyn Agent> = Arc::new(self.compile()?);
377        runner(steward, root, app, sessions)
378    }
379
380    /// One back-office agent as a runner, for the kernel's process of one of its jobs (spec
381    /// 3.5 §7.20).
382    ///
383    /// # Errors
384    ///
385    /// When the kind does not run `role`, or the runner refuses its configuration.
386    pub fn agent_runner(
387        &self,
388        role: AgentRole,
389        app: &str,
390        sessions: Arc<dyn adk_session::SessionService>,
391    ) -> Result<adk_runner::Runner> {
392        let agent = self
393            .agent(role)
394            .ok_or_else(|| AdkError::config(format!("the kind does not run the {role} agent")))?;
395        runner(agent, agent.clone(), app, sessions)
396    }
397
398    /// The agent of `role`, when the kind runs it.
399    pub fn agent(&self, role: AgentRole) -> Option<&Arc<HarnessAgent>> {
400        self.agents.get(&role)
401    }
402
403    /// The roles that run.
404    pub fn roles(&self) -> Vec<AgentRole> {
405        self.agents.keys().copied().collect()
406    }
407}
408
409/// A runner over `root`, configured by `harness`, its agents acting as the harness's
410/// partition's principals for `app`.
411fn runner(
412    harness: &Arc<HarnessAgent>,
413    root: Arc<dyn Agent>,
414    app: &str,
415    sessions: Arc<dyn adk_session::SessionService>,
416) -> Result<adk_runner::Runner> {
417    let builder = adk_runner::Runner::builder()
418        .app_name(app.to_string())
419        .agent(root)
420        .session_service(sessions);
421    let builder = harness.configure_runner(builder);
422    let builder = match harness.partition() {
423        Some(partition) => builder.identity_source(partition.identity_source(app, harness.name())),
424        None => builder,
425    };
426    builder.build()
427}
428
429/// The team of one site (spec 3.5 §7.19).
430///
431/// # Example
432///
433/// ```rust
434/// use adk_harness::website::SiteRef;
435/// use adk_website::kinds::template;
436/// use adk_website::team::{AgentRole, SiteTeam};
437/// use awp_types::SiteKind;
438///
439/// let site = SiteRef::new(uuid::Uuid::nil(), "notes", "https://notes.example");
440/// let team = SiteTeam::new(site, &template(SiteKind::Personal));
441/// assert_eq!(team.members(), [AgentRole::Concierge, AgentRole::Steward, AgentRole::Growth, AgentRole::Guardian]);
442/// let spec = team.spec();
443/// assert_eq!(spec.coordinator, "steward");
444/// assert!(spec.validate().is_ok());
445/// ```
446#[derive(Debug, Clone, PartialEq, Eq)]
447pub struct SiteTeam {
448    site: SiteRef,
449    members: Vec<AgentRole>,
450    public_instruction: String,
451}
452
453impl SiteTeam {
454    /// The team the kind `template` switches on for `site`.
455    pub fn new(site: SiteRef, template: &KindTemplate) -> Self {
456        let mut members = template.agents.clone();
457        members.sort();
458        members.dedup();
459        let public_instruction = template.public_instruction(&site.name);
460        Self { site, members, public_instruction }
461    }
462
463    /// Replaces the kind's instruction for the public agents, such as the disclosure line
464    /// in the site's display name (spec 3.5 §7.16.1, A-I17).
465    #[must_use]
466    pub fn with_public_instruction(mut self, text: impl Into<String>) -> Self {
467        self.public_instruction = text.into();
468        self
469    }
470
471    /// The kind's instruction the public agents carry.
472    pub fn public_instruction(&self) -> &str {
473        &self.public_instruction
474    }
475
476    /// The site.
477    pub fn site(&self) -> &SiteRef {
478        &self.site
479    }
480
481    /// The agents that run, in the order of spec 3.5 §7.19.
482    pub fn members(&self) -> &[AgentRole] {
483        &self.members
484    }
485
486    /// Whether `role` runs.
487    pub fn runs(&self, role: AgentRole) -> bool {
488        self.members.contains(&role)
489    }
490
491    /// The back office as a `TeamSpec`: the Steward coordinates, and delegates to every other
492    /// back-office agent that runs (spec 3.5 §7.19).
493    pub fn spec(&self) -> TeamSpec {
494        let back_office: Vec<AgentRole> = self
495            .members
496            .iter()
497            .copied()
498            .filter(|role| role.partition() == WebsitePartition::BackOffice)
499            .collect();
500        TeamSpec {
501            name: format!("{}-team", self.site.name),
502            description: format!("The back office of {}", self.site.origin),
503            coordinator: AgentRole::Steward.as_str().to_string(),
504            members: back_office
505                .iter()
506                .map(|role| {
507                    TeamMemberSpec::new(role.as_str()).with_description(role.prompt().to_string())
508                })
509                .collect(),
510            relationships: back_office
511                .iter()
512                .filter(|role| **role != AgentRole::Steward)
513                .map(|role| {
514                    TeamRelationship::new(
515                        AgentRole::Steward.as_str(),
516                        role.as_str(),
517                        RelationshipKind::Delegate,
518                    )
519                })
520                .collect(),
521            policy: TeamPolicy::default(),
522        }
523    }
524
525    /// The agent an inbound message wakes (spec 3.5 §7.19 "Wakes", §7.8.2, A-I24): a
526    /// paired person's message wakes the Steward; email and social wake the Inbox; chat and
527    /// web the Concierge; A2A, MCP and HTTP the Agent desk. `None` when the kind runs no
528    /// agent for the channel.
529    ///
530    /// # Example
531    ///
532    /// ```rust
533    /// use adk_harness::website::{AuthoringRoute, SiteRef};
534    /// use adk_website::kinds::template;
535    /// use adk_website::team::{AgentRole, SiteTeam};
536    /// use awp_types::SiteKind;
537    ///
538    /// let site = SiteRef::new(uuid::Uuid::nil(), "bakery", "https://bakery.example");
539    /// let team = SiteTeam::new(site, &template(SiteKind::Business));
540    /// let email = AuthoringRoute::Public { channel: "email".into(), thread: "t1".into() };
541    /// assert_eq!(team.agent_for(&email), Some(AgentRole::Inbox));
542    /// ```
543    pub fn agent_for(&self, route: &AuthoringRoute) -> Option<AgentRole> {
544        let role = match route {
545            AuthoringRoute::Owner { .. } => AgentRole::Steward,
546            AuthoringRoute::Public { channel, .. } => match channel.as_str() {
547                "a2a" | "mcp" | "http" => AgentRole::AgentDesk,
548                "chat" | "web" => AgentRole::Concierge,
549                _ => AgentRole::Inbox,
550            },
551        };
552        self.runs(role).then_some(role)
553    }
554
555    /// Builds every agent the kind runs and compiles the back office's team (spec 3.5
556    /// §7.19): each public agent with `website_public`, each back-office agent with
557    /// `website_back_office`, the ladder's mode for its jobs and the run budget of its jobs
558    /// acting within budget. Each agent's workspace holds its jobs' playbooks.
559    ///
560    /// # Errors
561    ///
562    /// Returns the autonomy store's, the workspace's or the builder's error, or a team
563    /// error when the back office's team does not compile over the built agents.
564    pub async fn build(&self, kit: &TeamKit) -> Result<BuiltTeam> {
565        let ladder = &kit.back_office.ladder;
566        let levels = job_levels(ladder, kit.back_office.autonomy.as_ref(), self.site.id).await?;
567        let mut agents = BTreeMap::new();
568        for role in &self.members {
569            let dir = kit.root.join(role.as_str());
570            playbooks::install(*role, &dir).await?;
571            let builder = HarnessAgent::builder(role.as_str())
572                .model(kit.model.clone())
573                .workspace(adk_devtools::Workspace::new(&dir));
574            let builder = match role.partition() {
575                WebsitePartition::Public if !self.public_instruction.is_empty() => builder
576                    .instruction(format!("{}\n\n{}", role.prompt(), self.public_instruction))
577                    .website_public((kit.public)()),
578                WebsitePartition::Public => {
579                    builder.instruction(role.prompt()).website_public((kit.public)())
580                }
581                WebsitePartition::BackOffice => {
582                    let mut builder = builder
583                        .instruction(role.prompt())
584                        .website_back_office(&kit.back_office)
585                        .standing_rules(kit.standing_rules.clone())
586                        .mode(ladder.mode_for_agent(role.as_str(), &levels));
587                    if let Some(budget) = ladder.budget_for_agent(role.as_str(), &levels) {
588                        builder = builder.budget(budget);
589                    }
590                    if let (AgentRole::Finance, Some(wallet)) = (role, &kit.wallet) {
591                        for tool in crate::wallet::finance_tools(wallet.clone()) {
592                            builder = builder.tool(tool);
593                        }
594                    }
595                    if *role == AgentRole::Steward {
596                        // The Steward hands work to the back office over the team's
597                        // delegate edges; each member's own harness decides its calls.
598                        builder = builder.team_delegates(
599                            self.members
600                                .iter()
601                                .filter(|m| {
602                                    m.partition() == WebsitePartition::BackOffice
603                                        && **m != AgentRole::Steward
604                                })
605                                .map(|m| m.as_str()),
606                        );
607                    }
608                    builder
609                }
610            };
611            let agent = (kit.configure)(*role, builder).build()?;
612            agents.insert(*role, Arc::new(agent));
613        }
614        let built = BuiltTeam { agents, back_office: self.spec() };
615        // The Steward's delegate edges compile: a harness consumes the runtime toolsets a
616        // team gives its coordinator (spec 3.5 §7.19).
617        built.compile()?;
618        Ok(built)
619    }
620}
621
622#[cfg(test)]
623mod tests {
624    use super::*;
625
626    #[test]
627    fn the_partitions_follow_the_table() {
628        let public: Vec<AgentRole> = AgentRole::ALL
629            .into_iter()
630            .filter(|role| role.partition() == WebsitePartition::Public)
631            .collect();
632        assert_eq!(public, [AgentRole::Concierge, AgentRole::AgentDesk, AgentRole::Inbox]);
633        for role in public {
634            assert!(role.tools().is_empty(), "{role} holds no back-office tool (A-I2)");
635        }
636        assert_eq!(AgentRole::Guardian.default_mode(), DefaultMode::ReversibleIncidentActs);
637    }
638
639    #[test]
640    fn crons_are_valid_and_names_parse_back() {
641        for role in AgentRole::ALL {
642            assert_eq!(role.as_str().parse::<AgentRole>().unwrap(), role);
643            for wake in role.wakes() {
644                if let WakeSource::Cron(expr) = wake {
645                    adk_agent::ambient::CronTrigger::new(expr)
646                        .unwrap_or_else(|e| panic!("{role} {expr}: {e}"));
647                }
648            }
649        }
650    }
651}