Skip to main content

adk_website/deploy/
site.rs

1//! One running site, assembled from its project and the kernel's stores (spec 3.5 §7.8.3,
2//! §7.9, §7.12, §7.17, §7.21): the runtime, the edge, the update engine, experiments and
3//! measurement, the weekly review and the owner's alarms.
4//!
5//! | Part | Built from |
6//! |---|---|
7//! | Runtime | The content repository, `ExperimentGenerator` around the built-in generator, the SQLite site log signed with `data/keys/release.jwk`, the `DirectoryHost`, the history, the charter store, the kind's launch gate with [`ReleaseDelegation`] |
8//! | Edge | The kind's capabilities with the packs' handlers under the owner's `approvals.json` thresholds; SQLite edge stores, event log and beacon counts in `data/edge.db`, with the deliveries a restart left resumed; the kernel's approvals and signals; the consent policy; `MeteredActionLedger` and `EdgeMeter`; inbox threads, the calendar and a payment desk (`SiteOptions::payments`, such as an AP2 desk, else the `payments.json` links) when configured; `card.jwk` and `receipt.jwk` |
9//! | Updates | `UpdateEngine` over the runtime's pipeline, the edge's live store and the stream lane signed with the receipt key, its held items and deliveries in `data/updates/held.json`; the feeds in `feeds.json`; [`UpdateDriver`] with its journal and cards |
10//! | Experiments | `ExperimentRunner` with `BeaconKpi`, the job pauses, the ladder, the alarms and `RepublishOnStop`; its daily trigger |
11//! | Measurement | `KpiTracker` with the beacon, commerce, spend and agent-search sources (and AEO with search providers), their counts in `data/edge.db` |
12//! | Review | `ReviewComposer` with the alarms, the experiments and the updates |
13//! | Learning | [`PlaybookLearning`](crate::learning::PlaybookLearning) over the review, the experiments and the ladder: proposals in `data/learning/proposals.json` and the owner's cards, playbook versions in `data/playbooks/`; its weekly trigger (spec 3.5 §7.15) |
14//! | Leads | The contact book and nurture counts in `data/edge.db` ([`SqliteLeadRecords`]), scored against the kind's threshold; the email outbox, when configured, reading consent from the edge's receipts |
15//! | Upkeep | [`UpkeepCheck`] over the edge's lockfile and the certificate, when configured |
16//! | Repository | [`RepositoryEntry`](crate::repository::RepositoryEntry) from `repository.json`: its signed hooks on the edge, each push a kernel run, its decision cards in the kernel's approvals (spec 3.5 §7.8.2) |
17//! | Durable state | In `data/edge.db`: the back office's drafts and requests (`SqliteSiteDraftStore`), quotes, orders and the bookings of `calendar.json`'s slots ([`SqliteCommerceStore`], [`StoredCalendar`]), the owner's open, deferred and waiting alarms ([`SqliteAlarmStore`]), and the edge's rate-limit windows |
18//! | Packs | The built-in capability packs and those installed in `packs/`, verified against `packs/trust.json` ([`PackDir::load`](crate::packs::installed::PackDir::load)): their capabilities on the edge, their playbooks in the agents' workspaces (spec 3.5 §7.23) |
19//! | Audit trail | `data/audit.jsonl` (`adk-core`'s `FileAuditRecorder`): the pipeline's, the edge's, the update engine's, the alarms', the review's, the experiments', the ladder's, the tracker's and the signals' records, and the kernel's serving the site (spec 3.5 §9.3) |
20
21use std::collections::BTreeMap;
22use std::path::Path;
23use std::sync::Arc;
24use std::time::Duration;
25
26use adk_awp::signing::jws::{DocumentSigner, Ed25519DocumentSigner};
27use adk_core::{AdkError, Result, SpendLedger, Url};
28use adk_drivers::{ReplyInThread, ThreadReplier};
29use adk_harness::web::SearchProvider;
30use adk_harness::website::{SitePartitions, SiteRef, SiteRuntime};
31use adk_kernel::channels::ChannelSink;
32use adk_kernel::charter::{AutonomyLadder, CharterStore, JobPauses, KpiStore, KpiTracker};
33use adk_kernel::wake::Trigger;
34use adk_server::awp::stores::SqliteEdgeStores;
35use adk_server::awp::{BeaconStore, ConsentPolicy, EdgeKeys, EdgeTiers, WebBotAuthTrustAssigner};
36use adk_site::content::{FileContentHistory, FsContentStore, SiteProject};
37use adk_site::generator::BuiltinGenerator;
38use adk_site::host::DirectoryHost;
39use adk_site::log::SiteLog;
40use adk_site::signer::Ed25519ReleaseSigner;
41use adk_site::stream::StreamLane;
42use adk_site::updates::{FileHeldStore, UpdateEngine};
43use awp_types::{Cadence, Charter, Reporting, SiteKind};
44use tokio::task::JoinHandle;
45
46use super::checks::{PaymentLinks, ReleaseDelegation, metered_trail};
47use super::kernel::SiteStores;
48use super::project::{self, KeyFile, ProjectPaths};
49use super::updates::{SiteAlarms, UpdateCards, UpdateDriver, UpdateJournal};
50use crate::alarms::{AlarmRouter, SqliteAlarmStore};
51use crate::edge::adapters::{
52    DeferredAnnouncer, InboxThreads, KernelSignals, ReceiptEntrySigner, ReleaseSearch,
53};
54use crate::edge::commerce::{SqliteCommerceStore, StoredCalendar};
55use crate::edge::handlers::{Calendar, PaymentDesk};
56use crate::edge::{SiteEdge, SiteEdgeParts, consent_config, site_router, stream_router};
57use crate::experiments::{
58    ExperimentGenerator, ExperimentRunner, FileExperimentStore, RepublishOnStop,
59};
60use crate::incident::{GuardianProbe, IncidentPath};
61use crate::kinds::{KindTemplate, template};
62use crate::leads::{LeadScorer, Leads, SqliteLeadRecords};
63use crate::measurement::{
64    AeoKpi, AeoTracker, AgentSearchKpi, BeaconKpi, CommerceKpi, MeteredSpendLedger, SpendLedgerKpi,
65};
66use crate::quotes::{QuotedReviews, ReviewQuotes};
67use crate::review::ReviewComposer;
68use crate::team::AgentRole;
69use crate::upkeep::{AdvisorySource, CertificateSource, UpkeepCheck};
70
71fn config(error: impl std::fmt::Display) -> AdkError {
72    AdkError::config(error.to_string())
73}
74
75/// What a site is served with beyond its project.
76#[derive(Clone, Default)]
77pub struct SiteOptions {
78    /// The edge's public URL; the site's base URL when not set.
79    pub edge_url: Option<String>,
80    /// The person the owner's decision cards and approvals go to.
81    pub owner: String,
82    /// The owner's channels and threads, for alarms and the weekly review.
83    pub channels: Vec<(Arc<dyn ChannelSink>, String)>,
84    /// The inbox drivers' repliers; in-thread replies are off without them.
85    pub repliers: Vec<Arc<dyn ThreadReplier>>,
86    /// The playbook template in-thread replies use.
87    pub reply_template: Option<String>,
88    /// A payment desk; otherwise `payments.json`, otherwise payments are refused.
89    pub payments: Option<Arc<dyn PaymentDesk>>,
90    /// A calendar; otherwise the CalDAV calendar in `caldav.json`, otherwise `calendar.json`,
91    /// otherwise no slot is open.
92    pub calendar: Option<Arc<dyn Calendar>>,
93    /// `web_search` providers for AEO tracking, with the questions to ask.
94    pub search: Vec<Arc<dyn SearchProvider>>,
95    /// The questions AEO tracking asks.
96    pub questions: Vec<String>,
97    /// The experiments' daily look, a six-field cron expression; `0 30 3 * * *` by default.
98    pub experiments_cron: Option<String>,
99    /// How often the update engine and measurement wake at the least; a minute by default.
100    pub idle: Option<Duration>,
101    /// The model the Concierge answers visitors with; no public agent without one.
102    pub model: Option<Arc<dyn adk_core::Llm>>,
103    /// The edge's rate limits, made for each site.
104    pub limits: Option<Arc<dyn Fn() -> adk_server::awp::EdgeLimits + Send + Sync>>,
105    /// The site's email: nurture sequences and the outbox are off without it (spec 3.5 §5 S8).
106    pub email: Option<EmailOptions>,
107    /// How long a page the site drafts on its own waits before it can go live; 24 hours by
108    /// default (spec 3.5 §5 S10).
109    pub publish_delay: Option<chrono::Duration>,
110    /// The edge's `Cargo.lock` and where its advisories come from, for the hosting job's
111    /// upgrade proposals (spec 3.5 §7.20).
112    pub advisories: Option<(std::path::PathBuf, Arc<dyn AdvisorySource>)>,
113    /// Where the certificate's expiry is read, for renewal proposals (spec 3.5 §7.20).
114    pub certificate: Option<Arc<dyn CertificateSource>>,
115    /// The owner's wallet the Finance agent pays running costs from (spec 3.5 §7.14); no
116    /// wallet tools without it.
117    pub wallet: Option<adk_payments::wallet::Wallet>,
118    /// The Guardian's probe (spec 3.5 §7.20, §7.8 "Probes", A-I9): the resolver that proves
119    /// the owner's domain claim again on every run; no probe without it.
120    pub probe: Option<ProbeOptions>,
121    /// The kernel's chat pairings: a paired account's message is the owner's, so the Inbox
122    /// does not read it (spec 3.5 A-I24); without them the Inbox reads every chat message
123    /// handed to it.
124    pub channel_bindings: Option<Arc<dyn adk_kernel::channels::ChannelBindingStore>>,
125    /// The chat platforms the site talks on (spec 3.5 §10 X12): a served site runs a channel
126    /// gateway over them — a paired account's messages are turns of the Steward, a
127    /// stranger's go to the Inbox — and its edge serves their routes, such as WhatsApp's
128    /// webhook. Pairings are kept in [`channel_bindings`](Self::channel_bindings), else in
129    /// the kernel's store.
130    pub chat: Option<Arc<dyn super::chat::ChatAdapters>>,
131}
132
133/// What the Guardian's probe of a served site needs beyond the project (spec 3.5 §7.20,
134/// §7.8 "Probes", A-I9): the resolver that proves the owner's domain claim again on every
135/// run, and the claim, the client and what to probe when the defaults do not fit.
136///
137/// # Example
138///
139/// ```rust
140/// use std::sync::Arc;
141/// use adk_site::migrate::claim::StaticDnsResolver;
142/// use adk_website::deploy::ProbeOptions;
143///
144/// let options = ProbeOptions::new(Arc::new(StaticDnsResolver::new()));
145/// assert!(options.claim.is_none(), "the project's own claim file by default");
146/// ```
147#[derive(Clone)]
148pub struct ProbeOptions {
149    /// The resolver the claim is proven with on every run.
150    pub resolver: Arc<dyn adk_site::migrate::claim::DnsResolver>,
151    /// The owner's claim of the site's domain; when not set, the project's
152    /// `data/claims/{domain}.json`, which `adk-rust site migrate` keeps. A claim on another
153    /// domain is not used.
154    pub claim: Option<adk_site::migrate::claim::DomainClaim>,
155    /// The client that reads the public origin; when not set, a client that reaches only
156    /// the site's origin.
157    pub http: Option<Arc<adk_site::migrate::http::HttpClient>>,
158    /// What to probe; the site's domain and origin with the prober's defaults when not set.
159    pub config: Option<adk_site::migrate::probe::ProbeConfig>,
160}
161
162impl ProbeOptions {
163    /// A probe proving the claim with `resolver`, with every other part from the project.
164    pub fn new(resolver: Arc<dyn adk_site::migrate::claim::DnsResolver>) -> Self {
165        Self { resolver, claim: None, http: None, config: None }
166    }
167
168    /// A probe proving the claim with the system's resolver.
169    pub fn system() -> Self {
170        Self::new(Arc::new(adk_site::migrate::claim::SystemDnsResolver))
171    }
172}
173
174impl std::fmt::Debug for ProbeOptions {
175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176        f.debug_struct("ProbeOptions").field("claim", &self.claim).finish_non_exhaustive()
177    }
178}
179
180/// The site's email (spec 3.5 §7.13): the driver, the address it sends from, and the
181/// domain-authentication check bulk sends wait for.
182#[derive(Clone)]
183pub struct EmailOptions {
184    /// The driver.
185    pub driver: Arc<dyn adk_drivers::email::EmailDriver>,
186    /// The address the site sends from.
187    pub from: adk_drivers::email::Mailbox,
188    /// The DNS lookup and sender policy SPF, DKIM and DMARC are checked against.
189    pub domain_auth:
190        Option<(Arc<dyn adk_drivers::email::TxtLookup>, adk_drivers::email::SenderPolicy)>,
191}
192
193impl std::fmt::Debug for EmailOptions {
194    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195        f.debug_struct("EmailOptions").field("from", &self.from).finish_non_exhaustive()
196    }
197}
198
199impl std::fmt::Debug for SiteOptions {
200    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201        f.debug_struct("SiteOptions").field("owner", &self.owner).finish_non_exhaustive()
202    }
203}
204
205/// A site's id and kind: the committed charter's or the drafted one's, else a business site
206/// with a new id.
207fn identity(paths: &ProjectPaths) -> (uuid::Uuid, SiteKind, Option<Charter>) {
208    ["charter.json", "charter.draft.json"]
209        .iter()
210        .filter_map(|name| std::fs::read(paths.root().join(name)).ok())
211        .find_map(|bytes| serde_json::from_slice::<Charter>(&bytes).ok())
212        .map_or_else(
213            || (uuid::Uuid::new_v4(), SiteKind::Business, None),
214            |charter| (charter.site_id, charter.kind, Some(charter)),
215        )
216}
217
218/// What [`guardian`] builds the Guardian's probe from.
219struct GuardianParts<'a> {
220    probe: &'a ProbeOptions,
221    paths: &'a ProjectPaths,
222    domain: &'a str,
223    site: &'a SiteRef,
224    host: Arc<DirectoryHost>,
225    release_key: adk_auth::signed_audit::NoteVerifier,
226    audit: (Arc<dyn adk_core::audit_log::AuditRecorder>, &'a str),
227    incidents: Arc<IncidentPath>,
228}
229
230/// The Guardian's probe of the served site (spec 3.5 §7.20, A-I9): the owner's claim on the
231/// site's domain — [`ProbeOptions::claim`], else the project's claim file — proven again with
232/// the resolver on every run; `None`, with a warning, when the site has no claim.
233fn guardian(parts: GuardianParts<'_>) -> Result<Option<Arc<GuardianProbe>>> {
234    use adk_site::migrate::claim::DomainClaim;
235    let GuardianParts { probe, paths, domain, site, host, release_key, audit, incidents } = parts;
236    let file = paths.data().join("claims").join(format!("{domain}.json"));
237    let claim = match probe.claim.clone() {
238        Some(claim) => Some(claim),
239        None => match std::fs::read(&file) {
240            Ok(bytes) => Some(
241                serde_json::from_slice::<DomainClaim>(&bytes)
242                    .map_err(|e| config(format!("{}: not a domain claim: {e}", file.display())))?,
243            ),
244            Err(_) => None,
245        },
246    }
247    .filter(|claim| claim.domain.eq_ignore_ascii_case(domain));
248    let Some(claim) = claim else {
249        tracing::warn!(
250            site.domain = domain,
251            "the Guardian does not probe: the site has no domain claim; `adk-rust site migrate` makes one in data/claims/"
252        );
253        return Ok(None);
254    };
255    let origin = Url::parse(&site.origin).map_err(config)?;
256    let http = match &probe.http {
257        Some(http) => http.clone(),
258        None => {
259            let only =
260                std::collections::BTreeSet::from([adk_site::migrate::http::origin_of(&origin)]);
261            Arc::new(
262                adk_site::migrate::http::HttpClient::builder()
263                    .egress(adk_site::migrate::http::EgressScope::Only(only))
264                    .build()
265                    .map_err(config)?,
266            )
267        }
268    };
269    let config = probe
270        .config
271        .clone()
272        .unwrap_or_else(|| adk_site::migrate::probe::ProbeConfig::new(domain, origin));
273    let (recorder, owner) = audit;
274    let acting = adk_core::ActingContext::derived(
275        &site.name,
276        AgentRole::Guardian.as_str(),
277        owner,
278        adk_core::SubjectKind::Service,
279    );
280    Ok(Some(Arc::new(GuardianProbe {
281        claim,
282        resolver: probe.resolver.clone(),
283        host,
284        http,
285        trusted: vec![release_key],
286        config,
287        audit: Some((recorder, acting)),
288        incidents,
289    })))
290}
291
292/// The owner's amount thresholds (spec 3.5 §7.4, §7.6): the `amountThresholds` of the charter
293/// in force, else of the drafted one, else `approvals.json`. They are applied to the edge's
294/// declarations, which the capability manifest publishes, so a committed change takes effect
295/// when the site next starts.
296fn amount_thresholds(
297    committed: Option<&Charter>,
298    drafted: Option<&Charter>,
299    paths: &ProjectPaths,
300) -> Result<crate::packs::ApprovalThresholds> {
301    match committed.or(drafted).filter(|charter| !charter.amount_thresholds.is_empty()) {
302        Some(charter) => {
303            let thresholds = charter.amount_thresholds.iter().fold(
304                crate::packs::ApprovalThresholds::new(),
305                |thresholds, (capability, amount)| thresholds.above(capability.clone(), *amount),
306            );
307            thresholds.validate()?;
308            Ok(thresholds)
309        }
310        None => project::approval_thresholds(paths),
311    }
312}
313
314/// A key file's id for a key made now: `{name}-{year}-{month}`.
315fn month_kid(name: &str) -> String {
316    format!("{name}-{}", chrono::Utc::now().format("%Y-%m"))
317}
318
319/// The 32-byte secret at `path`, made on first use, readable by its owner only.
320fn secret(path: &Path) -> Result<[u8; 32]> {
321    if let Ok(bytes) = std::fs::read(path)
322        && let Ok(secret) = <[u8; 32]>::try_from(bytes.as_slice())
323    {
324        return Ok(secret);
325    }
326    let mut fresh = [0u8; 32];
327    getrandom::fill(&mut fresh).map_err(config)?;
328    if let Some(parent) = path.parent() {
329        std::fs::create_dir_all(parent).map_err(config)?;
330    }
331    std::fs::write(path, fresh).map_err(config)?;
332    #[cfg(unix)]
333    {
334        use std::os::unix::fs::PermissionsExt;
335        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(config)?;
336    }
337    Ok(fresh)
338}
339
340/// One running site.
341pub struct RunningSite {
342    /// The site.
343    pub site: SiteRef,
344    /// Its domain.
345    pub domain: String,
346    /// Its kind's template.
347    pub template: KindTemplate,
348    /// Its project.
349    pub paths: ProjectPaths,
350    /// The runtime the back office acts on.
351    pub runtime: Arc<SiteRuntime>,
352    /// Its partitions.
353    pub partitions: SitePartitions,
354    /// The edge.
355    pub edge: SiteEdge,
356    /// The capability packs it loaded (spec 3.5 §7.23).
357    pub packs: crate::packs::installed::PackSet,
358    /// The update engine.
359    pub updates: Arc<UpdateEngine>,
360    /// The engine's driver: journal and cards.
361    pub driver: Arc<UpdateDriver>,
362    /// Held deliveries and items as the owner's decision cards.
363    pub cards: Arc<UpdateCards>,
364    /// Experiments.
365    pub experiments: Arc<ExperimentRunner>,
366    /// The ladder of the site's jobs.
367    pub ladder: AutonomyLadder,
368    /// The job pauses guardrails set.
369    pub pauses: Arc<JobPauses>,
370    /// The owner's alarms.
371    pub alarms: Arc<AlarmRouter>,
372    /// The weekly review.
373    pub review: Arc<ReviewComposer>,
374    /// The spend ledger agents' runs commit to, metered for the `spend` KPI source.
375    pub spend: Arc<MeteredSpendLedger>,
376    /// The site's leads: scores, consent for nurture, one handoff each (spec 3.5 §5 S8).
377    pub leads: Arc<Leads>,
378    /// The reviews the site may quote, with the owner's approvals (spec 3.5 S2).
379    pub quotes: Arc<ReviewQuotes>,
380    /// The site's email outbox, when the site has email (spec 3.5 §7.13).
381    pub outbox: Option<Arc<adk_drivers::email::EmailOutbox>>,
382    /// The incident path over the edge's status, the alarms and the ladder (spec 3.5 §7.20).
383    pub incidents: Arc<IncidentPath>,
384    /// The Inbox, when the site has a model and its kind runs one (spec 3.5 §7.19): it reads
385    /// the site's email while the site serves, and the chat messages of unpaired accounts
386    /// handed to it.
387    pub inbox: Option<Arc<crate::inbox::SiteInbox>>,
388    /// The Guardian's probe, when the site has [`SiteOptions::probe`] and a domain claim; the
389    /// kernel runs it every five minutes (spec 3.5 §7.20).
390    pub guardian: Option<Arc<GuardianProbe>>,
391    /// Files and git as an entry point, when the project has a `repository.json`: its hooks
392    /// on the edge at `/hooks/{name}` (spec 3.5 §7.8.2).
393    pub repository: Option<Arc<crate::repository::RepositoryEntry>>,
394    /// The playbook-learning job: proposals from the week's outcomes, decided by the owner
395    /// (spec 3.5 §7.15).
396    pub learning: Arc<crate::learning::PlaybookLearning>,
397    pub(crate) reporting: Reporting,
398    /// The site's audit trail in `data/audit.jsonl`, which the kernel serving the site
399    /// records into too.
400    pub(crate) audit: adk_core::audit_log::AuditTrail,
401    pub(crate) publish_delay: chrono::Duration,
402    pub(crate) wallet: Option<adk_payments::wallet::Wallet>,
403    /// The edge's signals into the back office, which wake the kernel's processes once the
404    /// kernel serving the site exists.
405    pub(crate) signals: Arc<KernelSignals>,
406    /// The router serving the edge, the stream feed and the release.
407    pub router: axum::Router,
408    triggers: Vec<Trigger>,
409    tracker: KpiTracker,
410    aeo: Option<AeoTracker>,
411    tasks: Vec<JoinHandle<()>>,
412}
413
414impl std::fmt::Debug for RunningSite {
415    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
416        f.debug_struct("RunningSite").field("site", &self.site).finish_non_exhaustive()
417    }
418}
419
420impl Drop for RunningSite {
421    fn drop(&mut self) {
422        for task in &self.tasks {
423            task.abort();
424        }
425    }
426}
427
428impl RunningSite {
429    /// Opens the site at `paths` over the kernel's `stores` (spec 3.5 §7.17): continues after
430    /// the release its host serves, and brings a committed charter's jobs onto the ladder.
431    ///
432    /// # Errors
433    ///
434    /// A project that does not load, a key file that is not valid, or a store that does not
435    /// open.
436    pub async fn open(
437        paths: ProjectPaths,
438        stores: &SiteStores,
439        options: &SiteOptions,
440    ) -> Result<Self> {
441        let (id, kind, drafted) = identity(&paths);
442        let template = template(kind);
443        let mut project =
444            SiteProject::load(paths.root(), chrono::Utc::now()).await.map_err(config)?;
445        project.documents = project::documents(&paths)?;
446        let domain = project.config.domain.clone();
447        let site = SiteRef::new(id, domain.replace('.', "-"), project.config.base_url());
448        let edge_url = options.edge_url.clone().unwrap_or_else(|| project.config.base_url());
449
450        let release = KeyFile::load_or_create(&paths.key_file("release"), &month_kid("release"))?;
451        let card = KeyFile::load_or_create(&paths.key_file("card"), &month_kid("card"))?;
452        let receipt = match paths.key_file("receipt") {
453            path if path.exists() => KeyFile::read(&path)?,
454            _ => KeyFile::read(&paths.key_file("card"))?,
455        };
456        let release_signer = Ed25519DocumentSigner::from_seed(release.kid.clone(), release.seed())
457            .map_err(config)?;
458        let card_signer: Arc<dyn DocumentSigner> = Arc::new(
459            Ed25519DocumentSigner::from_seed(card.kid.clone(), card.seed()).map_err(config)?,
460        );
461        let receipt_signer: Arc<dyn DocumentSigner> = Arc::new(
462            Ed25519DocumentSigner::from_seed(receipt.kid.clone(), receipt.seed())
463                .map_err(config)?,
464        );
465
466        // The site's audit trail survives a restart (spec 3.5 §9.3).
467        let recorder: Arc<dyn adk_core::audit_log::AuditRecorder> = Arc::new(
468            adk_core::audit_log::FileAuditRecorder::open(paths.data().join("audit.jsonl"))?
469                .with_log_id(&domain),
470        );
471        let trail = adk_core::audit_log::AuditTrail::new(recorder.clone());
472        let pool = sqlx::SqlitePool::connect(&paths.database("edge")).await.map_err(config)?;
473        // The back office's drafts and requests, kept beside the edge's stores (§7.8.2).
474        let drafts = adk_harness::website::SqliteSiteDraftStore::new(pool.clone());
475        drafts.migrate().await?;
476        let audit = adk_session::SqliteAuditLogStore::new(&paths.database("site-log")).await?;
477        audit.migrate().await?;
478        let signer = Ed25519ReleaseSigner::from_seed(&domain, release.seed()).map_err(config)?;
479        let release_key: adk_auth::signed_audit::NoteVerifier = {
480            use adk_site::signer::ReleaseSigner as _;
481            signer.verifier_key().parse().map_err(|e| config(format!("release key: {e:?}")))?
482        };
483        let log = Arc::new(
484            SiteLog::open(Arc::new(audit), &domain, Arc::new(signer)).await.map_err(config)?,
485        );
486        let host = Arc::new(DirectoryHost::new(paths.host_dir()));
487        let previous = project::previous_release(host.as_ref(), log.size().await).await?;
488        let experiment_store = Arc::new(FileExperimentStore::new(paths.experiments()));
489        let generator = Arc::new(ExperimentGenerator::new(
490            Arc::new(BuiltinGenerator),
491            experiment_store.clone(),
492            site.id,
493            format!("{edge_url}/awp/v2/beacon"),
494        ));
495        let delegation = ReleaseDelegation::new(
496            release.kid.clone(),
497            release_signer.public_key(),
498            "data/keys/release.jwk",
499        );
500        let announcer = Arc::new(DeferredAnnouncer::default());
501        let verify_edge = Arc::new(crate::edge::adapters::DeferredFetcher::default());
502        let quotes = Arc::new(ReviewQuotes::open(paths.data().join("reviews.json"))?);
503        let charters: Arc<dyn CharterStore> = stores.kernel.charter.charters.clone();
504        let mut builder = SiteRuntime::builder(
505            site.clone(),
506            project.clone(),
507            Arc::new(FsContentStore::new(paths.root())),
508            generator,
509            host.clone(),
510            log,
511            paths.work(),
512        )
513        .history(Arc::new(FileContentHistory::new(paths.history())))
514        .charters(charters.clone())
515        .drafts(Arc::new(drafts))
516        // The site's decisions are the kernel's requests: one record for the desk, the back
517        // office, the kernel's inbox and chat cards (spec 3.5 A-I23, #1280).
518        .approvals(stores.approvals.clone())
519        .governance(stores.governance.clone())
520        .require_durable()
521        .audit(trail.clone())
522        .gate(
523            template
524                .gate(&site.origin)
525                .with_extension(Arc::new(delegation))
526                // Pages quote a found review only as its owner approved (S2).
527                .with_extension(Arc::new(QuotedReviews::new(quotes.clone())))
528                .with_extension(Arc::new(super::checks::preview_verification(
529                    &project,
530                    host.clone(),
531                    verify_edge.clone(),
532                ))),
533        )
534        .announcer(announcer.clone());
535        if let Some(previous) = previous {
536            builder = builder.previous(previous);
537        }
538        let runtime = builder.build()?;
539        runtime.restore_drafts().await?;
540
541        let partitions = SitePartitions::new(&site);
542        let reporting = drafted.as_ref().map_or_else(
543            || Reporting { review: Cadence::Weekly, routes: Vec::new(), quiet_hours: None },
544            |charter| charter.reporting.clone(),
545        );
546        let alarm_store = SqliteAlarmStore::new(pool.clone());
547        alarm_store.migrate().await?;
548        let mut router = AlarmRouter::new(site.id, &reporting)
549            .with_store(Arc::new(alarm_store))
550            .with_audit(trail.clone());
551        for (sink, thread) in &options.channels {
552            router = router.with_sink(sink.clone(), thread.clone());
553        }
554        let alarms = Arc::new(router);
555        let ladder = AutonomyLadder::new(stores.kernel.charter.autonomy.clone())
556            .with_charters(charters.clone())
557            .with_audit(trail.clone());
558        if let Some(current) = charters.current(site.id).await.map_err(config)? {
559            crate::jobs::register(&ladder, &current.charter).await?;
560        }
561
562        // The contact book, kept beside the edge's leads so the people behind them are still
563        // reachable after a restart, and erased with them (spec 3.5 §7.5, S8).
564        let records = Arc::new(SqliteLeadRecords::new(pool.clone()));
565        records.migrate().await?;
566        let edge_stores = SqliteEdgeStores::new(pool.clone()).with_site(site.name.clone());
567        edge_stores.migrate().await.map_err(config)?;
568        let served_stores = edge_stores.edge_stores();
569        let leads = Arc::new(
570            Leads::new(
571                served_stores.leads.clone(),
572                records.clone(),
573                served_stores.consent.clone(),
574                LeadScorer::default(),
575            )
576            .with_charters(charters.clone(), site.id),
577        );
578        let reply_template = options.reply_template.clone().unwrap_or_else(|| "reply".into());
579        let outbox = options.email.as_ref().map(|email| {
580            let disclosure = adk_drivers::Disclosure::new(&project.config.name)
581                .or_else(|_| adk_drivers::Disclosure::new(&domain))
582                .map_err(config)?;
583            let mut builder = adk_drivers::email::EmailOutbox::builder(
584                email.driver.clone(),
585                email.from.clone(),
586                disclosure,
587            )
588            .consent(leads.clone())
589            // The Inbox answers an email's thread with the reply template's body (§7.19).
590            .templates(
591                adk_drivers::ReplyTemplates::new().template(reply_template.clone(), "{body}"),
592            );
593            if let Some((lookup, policy)) = &email.domain_auth {
594                builder = builder.domain_auth(lookup.clone(), policy.clone());
595            }
596            Ok::<_, AdkError>(Arc::new(builder.build()))
597        });
598        let outbox = outbox.transpose()?;
599        // Counts the edge's meters write and the measurement sources read, kept beside the
600        // edge's own beacon counts in a namespace of their own, so both survive a restart.
601        let counts: Arc<dyn BeaconStore> =
602            Arc::new(edge_stores.clone().with_site(format!("{}#measurement", site.name)));
603        let terms = std::fs::read(paths.root().join("public-terms.json")).unwrap_or_default();
604        let policy = ConsentPolicy { digest: adk_site::release::file_digest(&terms), ttl: None };
605        let subject_key = secret(&paths.data().join("keys/subject.key"))?.to_vec();
606        let directory = adk_auth::web_bot_auth::HttpKeyDirectorySource::new().map_err(config)?;
607        let tiers = EdgeTiers::builder()
608            .verifier(WebBotAuthTrustAssigner::new(
609                adk_auth::web_bot_auth::HttpSignatureVerifier::builder(Arc::new(directory)).build(),
610            ))
611            .build();
612        // Quotes, orders and bookings outlive a restart (spec 3.5 §7.5, §7.9).
613        let commerce = SqliteCommerceStore::new(pool.clone()).with_site(site.name.clone());
614        commerce.migrate().await?;
615        let commerce: Arc<dyn crate::edge::commerce::CommerceStore> = Arc::new(commerce);
616        let caldav = project::caldav(&paths)?.map(|c| Arc::new(c) as Arc<dyn Calendar>);
617        let calendar = match &options.calendar {
618            Some(calendar) => Some(calendar.clone()),
619            None if caldav.is_some() => caldav,
620            None => project::slots(&paths)?.map(|slots| {
621                Arc::new(StoredCalendar::new(slots, commerce.clone())) as Arc<dyn Calendar>
622            }),
623        };
624        let payments = match &options.payments {
625            Some(desk) => Some(desk.clone()),
626            None => project::payment_links(&paths)?
627                .map(|links| Arc::new(PaymentLinks::new(links)) as Arc<dyn PaymentDesk>),
628        };
629        // In-thread replies go back through the channel a message came in on: the inbox
630        // drivers, the site's email, and the chat channels the owner's sinks serve (§7.19).
631        let mut repliers: Vec<Arc<dyn ThreadReplier>> = options.repliers.clone();
632        if let Some(outbox) = &outbox {
633            repliers.push(outbox.clone());
634        }
635        let mut chats = std::collections::BTreeSet::new();
636        // The site's own chat platforms too (spec 3.5 §10 X12), so the Inbox answers a
637        // stranger in their thread.
638        let platforms = options.chat.iter().flat_map(|chat| chat.sinks());
639        let sinks: Vec<Arc<dyn ChannelSink>> =
640            options.channels.iter().map(|(sink, _)| sink.clone()).chain(platforms).collect();
641        for sink in &sinks {
642            if chats.insert(sink.channel().to_string()) {
643                repliers.push(Arc::new(crate::inbox::ChannelReplier::new(
644                    sink.clone(),
645                    reply_template.clone(),
646                )));
647            }
648        }
649        let threads = (!repliers.is_empty()).then(|| {
650            Arc::new(InboxThreads::new(Arc::new(ReplyInThread::new(repliers)), reply_template))
651                as Arc<dyn adk_server::awp::ThreadSink>
652        });
653        let signals = partitions
654            .signal_sink(stores.kernel.charter.signals.clone(), stores.kernel.agenda.clone())
655            .with_audit(trail.clone());
656        let edge_signals = Arc::new(KernelSignals::new(signals));
657        // The edge's rate-limit windows are shared through `data/edge.db` (spec 3.5 §7.9).
658        let limits = options
659            .limits
660            .as_ref()
661            .map_or_else(adk_server::awp::EdgeLimits::default, |limits| limits())
662            .store(Arc::new(edge_stores.clone()));
663        // The installed packs verify again on every start; one that does not is not loaded.
664        let packs = crate::packs::installed::PackDir::new(paths.root()).load()?;
665        let public_tools = Arc::new(std::sync::OnceLock::new());
666        let edge = SiteEdge::build_with_packs(
667            SiteEdgeParts {
668                template: template.clone(),
669                runtime: runtime.clone(),
670                keys: EdgeKeys { card: card_signer, receipt: receipt_signer.clone() },
671                edge_url: Url::parse(&edge_url).map_err(config)?,
672                stores: served_stores,
673                signals: edge_signals.clone(),
674                search: Arc::new(ReleaseSearch::new(Arc::new(
675                    adk_harness::website::SiteSearch::new(),
676                ))),
677                contacts: records,
678                calendar,
679                payments,
680                thresholds: amount_thresholds(
681                    charters.current(site.id).await.map_err(config)?.map(|v| v.charter).as_ref(),
682                    drafted.as_ref(),
683                    &paths,
684                )?,
685                approvals: Some(stores.approvals.clone()),
686                tiers: Some(tiers),
687                consent: Some(consent_config(&template, policy, subject_key)),
688                threads,
689                quote_validity: chrono::Duration::days(7),
690                action_ledger: Some(Arc::new(crate::measurement::MeteredActionLedger::new(
691                    stores.kernel.actions.clone(),
692                    counts.clone(),
693                ))),
694                audit: Some(metered_trail(recorder.clone(), counts.clone())),
695                beacon: None,
696                limits: Some(limits),
697                public_agent: options.model.clone().map(|model| {
698                    let concierge = crate::edge::concierge(
699                        &crate::team::SiteTeam::new(site.clone(), &template),
700                        &partitions,
701                        stores.partitions.clone(),
702                        model,
703                        paths.data().join("agents/concierge"),
704                    );
705                    // The Inbox runs over the same public tools the edge gives the Concierge.
706                    let captured = public_tools.clone();
707                    Box::new(move |tools: &adk_server::awp::PublicTools| {
708                        let _ = captured.set(tools.clone());
709                        concierge(tools)
710                    }) as crate::edge::PublicAgentFactory
711                }),
712            },
713            commerce,
714            &packs,
715        )?;
716        announcer.set(edge.announcer());
717        let team = crate::team::SiteTeam::new(site.clone(), &template);
718        let inbox = match (&options.model, public_tools.get()) {
719            (Some(model), Some(tools)) if team.runs(AgentRole::Inbox) => {
720                // The Inbox's jobs' playbooks are in its workspace, as every agent's are.
721                crate::playbooks::install(AgentRole::Inbox, &paths.data().join("agents/inbox"))
722                    .await?;
723                let mut inbox = crate::inbox::SiteInbox::new(crate::inbox::InboxParts {
724                    team,
725                    partitions: partitions.clone(),
726                    table: stores.partitions.clone(),
727                    model: model.clone(),
728                    tools: tools.clone(),
729                    workspace: paths.data().join("agents/inbox"),
730                    signals: edge_signals.clone(),
731                    audit: Some(trail.clone()),
732                })?;
733                if let Some(bindings) = &options.channel_bindings {
734                    inbox = inbox.with_bindings(bindings.clone());
735                }
736                Some(Arc::new(inbox))
737            }
738            _ => None,
739        };
740        let incidents = Arc::new(
741            IncidentPath::new(
742                runtime.clone(),
743                ladder.clone(),
744                alarms.clone(),
745                Arc::new(edge.status()),
746            )
747            .with_audit(trail.clone()),
748        );
749        let guardian = match &options.probe {
750            Some(probe) => guardian(GuardianParts {
751                probe,
752                paths: &paths,
753                domain: &domain,
754                site: &site,
755                host: host.clone(),
756                release_key,
757                audit: (recorder.clone(), options.owner.as_str()),
758                incidents: incidents.clone(),
759            })?,
760            None => None,
761        };
762
763        let lane = Arc::new(StreamLane::new(Arc::new(ReceiptEntrySigner::new(receipt_signer))));
764        let updates = Arc::new(
765            UpdateEngine::builder(runtime.shared_pipeline(), edge.live.clone())
766                // Held items and deliveries outlive a restart, so the owner's cards still
767                // decide them.
768                .held_store(Arc::new(FileHeldStore::new(paths.journal().join("held.json"))))
769                .streams(lane)
770                .alarms(Arc::new(SiteAlarms::new(alarms.clone(), site.id)))
771                .audit(
772                    recorder.clone(),
773                    adk_core::ActingContext::derived(
774                        &site.name,
775                        "updates",
776                        &options.owner,
777                        adk_core::SubjectKind::Service,
778                    ),
779                )
780                .build()
781                .map_err(config)?,
782        );
783        for feed in project::feeds(&paths)? {
784            updates.add_feed(feed.mapping, feed.bounds).await.map_err(config)?;
785        }
786        let cards = Arc::new(UpdateCards::new(
787            updates.clone(),
788            stores.approvals.clone(),
789            site.id,
790            site.name.clone(),
791            options.owner.clone(),
792        ));
793        let driver = Arc::new(UpdateDriver::new(
794            updates.clone(),
795            UpdateJournal::new(paths.journal()),
796            Some(cards.clone()),
797        ));
798
799        let pauses = Arc::new(JobPauses::new());
800        let kpis: Arc<dyn KpiStore> = stores.kernel.charter.kpis.clone();
801        let experiments = Arc::new(
802            ExperimentRunner::new(site.id, charters.clone(), experiment_store)
803                .with_source(Arc::new(BeaconKpi::new(site.id, edge.edge.beacon())))
804                .with_kpis(kpis.clone())
805                .with_control(pauses.clone())
806                .with_ladder(ladder.clone())
807                .with_events(alarms.clone())
808                .with_audit(trail.clone())
809                .with_stop_hook(Arc::new(RepublishOnStop::new(
810                    runtime.clone(),
811                    AgentRole::Growth.principal(&site),
812                ))),
813        );
814        let inner_spend: Arc<dyn SpendLedger> = stores.kernel.spend.clone();
815        let spend = Arc::new(MeteredSpendLedger::new(inner_spend, counts.clone()));
816        let aeo = (!options.search.is_empty()).then(|| {
817            let mut tracker = AeoTracker::new(site.id, domain.clone(), counts.clone());
818            for provider in &options.search {
819                tracker = tracker.provider(provider.clone());
820            }
821            for question in &options.questions {
822                tracker = tracker.question(question.clone());
823            }
824            tracker
825        });
826        let tracker = |aeo: bool| {
827            let mut tracker = KpiTracker::new(site.id, charters.clone(), kpis.clone())
828                .with_source(Arc::new(BeaconKpi::new(site.id, edge.edge.beacon())))
829                .with_source(Arc::new(CommerceKpi::new(site.id, counts.clone())))
830                .with_source(Arc::new(SpendLedgerKpi::new(site.id, counts.clone())))
831                .with_source(Arc::new(AgentSearchKpi::new(site.id, counts.clone())))
832                .with_control(pauses.clone())
833                .with_ladder(ladder.clone())
834                .with_events(alarms.clone())
835                .with_audit(trail.clone());
836            if aeo {
837                tracker = tracker.with_source(Arc::new(AeoKpi::new(site.id, counts.clone())));
838            }
839            tracker
840        };
841        let review = Arc::new(
842            ReviewComposer::new(site.id, tracker(aeo.is_some()), ladder.clone(), charters.clone())
843                .with_audit(trail.clone())
844                .with_alarms(alarms.clone())
845                .with_experiments(experiments.clone())
846                .with_updates(updates.clone())
847                .with_incidents(incidents.clone()),
848        );
849        let cron = options.experiments_cron.clone().unwrap_or_else(|| "0 30 3 * * *".into());
850        let learning =
851            Arc::new(crate::learning::PlaybookLearning::open(crate::learning::LearningParts {
852                site: site.clone(),
853                team: crate::team::SiteTeam::new(site.clone(), &template),
854                owner: options.owner.clone(),
855                composer: (*review).clone(),
856                experiments: experiments.clone(),
857                charters: charters.clone(),
858                ladder: ladder.clone(),
859                approvals: stores.approvals.clone(),
860                data: paths.data(),
861            })?);
862        let triggers = vec![
863            experiments.trigger(&site.name, &cron),
864            learning.trigger(&site.name, crate::learning::LEARNING_CRON),
865        ];
866        let repository = crate::repository::RepositoryEntry::open(
867            &paths,
868            crate::repository::RepositoryParts {
869                site: site.clone(),
870                owner: options.owner.clone(),
871                runtime: runtime.clone(),
872                approvals: stores.approvals.clone(),
873                signals: edge_signals.clone(),
874                source: None,
875            },
876        )?
877        .map(Arc::new);
878        let mut router = site_router(&edge.edge, host, &project.config.name)
879            .merge(stream_router(updates.clone()));
880        if let Some(entry) = &repository {
881            router = router.merge(entry.router(stores.kernel.runs.clone()));
882        }
883        verify_edge.set(Arc::new(adk_awp::verify::fetch::RouterFetcher::new(router.clone())));
884        Ok(Self {
885            tracker: tracker(aeo.is_some()),
886            site,
887            domain,
888            template,
889            paths,
890            runtime,
891            partitions,
892            edge,
893            packs,
894            updates,
895            driver,
896            cards,
897            experiments,
898            ladder,
899            pauses,
900            alarms,
901            review,
902            spend,
903            leads,
904            quotes,
905            outbox,
906            incidents,
907            inbox,
908            guardian,
909            repository,
910            learning,
911            reporting,
912            audit: trail,
913            wallet: options.wallet.clone(),
914            signals: edge_signals,
915            publish_delay: options.publish_delay.unwrap_or_else(|| {
916                chrono::Duration::hours(crate::publish_delay::DEFAULT_PUBLISH_DELAY_HOURS)
917            }),
918            router,
919            triggers,
920            aeo,
921            tasks: Vec::new(),
922        })
923    }
924
925    /// The edge's signals into the back office (spec 3.5 §7.10): what a public agent or a
926    /// form files, which wakes the back office's processes while the site serves.
927    pub fn signals(&self) -> Arc<KernelSignals> {
928        self.signals.clone()
929    }
930
931    /// The KPI tracker the site measures with, for the owner's site view (spec 3.5 §7.24).
932    pub fn tracker(&self) -> &KpiTracker {
933        &self.tracker
934    }
935
936    /// The kernel triggers the site's own processes run on: the experiments' daily look.
937    pub fn triggers(&self) -> &[Trigger] {
938        &self.triggers
939    }
940
941    /// Starts the site's background work: the update engine on its schedule, AEO once a day
942    /// (checked every `idle`), and the edge's trust resolver. The KPI tracker runs as the
943    /// kernel's `kernel.kpi` process ([`CharterKit`](adk_kernel::charter::CharterKit)).
944    pub fn start(&mut self, idle: Duration) {
945        self.tasks.push(self.driver.clone().spawn(idle));
946        if let Some(aeo) = self.aeo.take() {
947            self.tasks.push(tokio::spawn(async move {
948                let mut last_aeo: Option<chrono::NaiveDate> = None;
949                loop {
950                    let today = chrono::Utc::now().date_naive();
951                    if last_aeo != Some(today) {
952                        match aeo.run().await {
953                            Ok(_) => last_aeo = Some(today),
954                            Err(error) => tracing::warn!(error = %error, "AEO tracking failed"),
955                        }
956                    }
957                    tokio::time::sleep(idle).await;
958                }
959            }));
960        }
961        // The Inbox reads the site's email while the site serves; the cursor survives a
962        // restart, so no message is read twice (spec 3.5 §7.19).
963        if let (Some(inbox), Some(outbox)) = (self.inbox.clone(), self.outbox.clone()) {
964            let file = self.paths.data().join("inbox").join("email.cursor");
965            self.tasks.push(tokio::spawn(async move {
966                let mut cursor = std::fs::read_to_string(&file).ok().map(|c| c.trim().to_string());
967                loop {
968                    match inbox.read_email(&outbox, cursor.as_deref(), 20).await {
969                        Ok(next) if next != cursor => {
970                            if let Some(next) = &next
971                                && let Err(error) = file
972                                    .parent()
973                                    .map_or(Ok(()), std::fs::create_dir_all)
974                                    .and_then(|()| std::fs::write(&file, next))
975                            {
976                                tracing::warn!(error = %error, "the Inbox's email cursor was not kept");
977                            }
978                            cursor = next;
979                        }
980                        Ok(_) => {}
981                        Err(error) => tracing::warn!(error = %error, "the Inbox could not read the site's email"),
982                    }
983                    tokio::time::sleep(idle).await;
984                }
985            }));
986        }
987        if let Some(entry) = self.repository.clone() {
988            self.tasks.push(entry.spawn(idle));
989        }
990        self.tasks.push(self.learning.clone().spawn(idle));
991        let _resolver = self.edge.edge.spawn_resolver(Duration::from_secs(5));
992        // Deliveries a stopped process left in `data/edge.db` resume once their lease passes.
993        let _deliveries = self.edge.edge.spawn_delivery_resumer(Duration::from_secs(30));
994    }
995
996    /// The hosting job's upkeep check (spec 3.5 §7.20), when the site has a lockfile with an
997    /// advisory source or a certificate source: proposals go to `owner`'s approval inbox.
998    pub fn upkeep(&self, stores: &SiteStores, options: &SiteOptions) -> Option<Arc<UpkeepCheck>> {
999        if options.advisories.is_none() && options.certificate.is_none() {
1000            return None;
1001        }
1002        let mut check = UpkeepCheck::new(
1003            self.site.id,
1004            self.domain.clone(),
1005            self.site.name.clone(),
1006            options.owner.clone(),
1007            stores.approvals.clone(),
1008        )
1009        .with_alarms(self.alarms.clone());
1010        if let Some((lockfile, source)) = &options.advisories {
1011            check = check.with_advisories(lockfile, source.clone());
1012        }
1013        if let Some(source) = &options.certificate {
1014            check = check.with_certificate(source.clone());
1015        }
1016        Some(Arc::new(check))
1017    }
1018
1019    /// The owner's channel for the weekly review, when one is configured.
1020    pub(crate) fn digest_target(
1021        &self,
1022        options: &SiteOptions,
1023    ) -> Option<crate::workflows::DigestTarget> {
1024        options.channels.first().map(|(sink, thread)| crate::workflows::DigestTarget {
1025            composer: self.review.clone(),
1026            sink: sink.clone(),
1027            thread: thread.clone(),
1028        })
1029    }
1030}
1031
1032/// The served workflows: the site's model-free jobs and each site's experiments look, by
1033/// the site a run names.
1034pub struct ServedWorkflows {
1035    sites: crate::workflows::SiteWorkflows,
1036    experiments: BTreeMap<uuid::Uuid, Arc<ExperimentRunner>>,
1037}
1038
1039impl ServedWorkflows {
1040    /// `sites` with each runner's look.
1041    pub fn new(
1042        sites: crate::workflows::SiteWorkflows,
1043        experiments: impl IntoIterator<Item = Arc<ExperimentRunner>>,
1044    ) -> Self {
1045        Self {
1046            sites,
1047            experiments: experiments.into_iter().map(|runner| (runner.site(), runner)).collect(),
1048        }
1049    }
1050}
1051
1052#[async_trait::async_trait]
1053impl adk_server::background::WorkflowExecutor for ServedWorkflows {
1054    fn has_workflow(&self, workflow_id: &str) -> bool {
1055        workflow_id == crate::experiments::EXPERIMENTS_WORKFLOW
1056            || self.sites.has_workflow(workflow_id)
1057    }
1058
1059    async fn execute(
1060        &self,
1061        workflow_id: &str,
1062        input: adk_server::background::WorkflowState,
1063        cancel_token: tokio_util::sync::CancellationToken,
1064    ) -> std::result::Result<serde_json::Value, String> {
1065        if workflow_id != crate::experiments::EXPERIMENTS_WORKFLOW {
1066            return self.sites.execute(workflow_id, input, cancel_token).await;
1067        }
1068        let site = input
1069            .get("site")
1070            .and_then(serde_json::Value::as_str)
1071            .and_then(|site| site.parse::<uuid::Uuid>().ok())
1072            .ok_or_else(|| format!("a `{workflow_id}` run names its site"))?;
1073        let runner = self
1074            .experiments
1075            .get(&site)
1076            .ok_or_else(|| format!("no experiments run for site {site}"))?;
1077        runner.execute(workflow_id, input, cancel_token).await
1078    }
1079}