Skip to main content

adk_website/ui/
mod.rs

1//! Onboarding and owner views on the web home (spec 3.5 §7.16 `ui`, §7.8.2 "Web editor",
2//! §7.18, §7.21, §7.24, §8.2; spec 3.3 §5.1, §8, §9).
3//!
4//! [`WebsiteDesk`] is what a surface reads and acts through: it turns the product's library
5//! types — the setup gate, discovery, the charter template, the live preview, the launch
6//! gate, the publishing pipeline, the autonomy ladder, the KPI tracker, the wallet, the
7//! update engine and the weekly review — into views in plain words, and carries out the
8//! decisions a person makes on them. `adk-surface`'s `website` feature serves it on the web
9//! home; any other surface can read the same views.
10//!
11//! | View | Reads | A person decides | Spec 3.5 |
12//! |---|---|---|---|
13//! | [`setup`] | The setup gate | The setup code pairs the owner's device; nothing else is accepted before it | §7.17, A-I20 |
14//! | [`onboarding`] | Discovery, the interview's facts, the live preview, the design directions, the launch gate, the connections, the deployment | Start, confirm or fix each found fact, the kind, the freeze, the interview's answers, the design, each connection, going live | §7.18, A-I18, A-I19, A-I21 |
15//! | [`charter`] | The charter draft, section by section | Each section looks right or is changed; every required signer signs | §7.6, §7.18 stage 5, A-I14, A-I23 |
16//! | [`site`] | Status, releases and their page changes, KPIs with trends, jobs and their levels, signals, the wallet, held batches | Promote or lower a job; release or discard a held item or feed delivery | §7.24, §7.11, §7.8.3, A-I13, A-I27 |
17//! | [`review`] | The weekly review | Compose it; send its summary to the owner's channel | §7.21 |
18//! | [`editor`] | Content per kind | Draft with a form per kind and Markdown, upload media, preview with page diffs, schedule, publish, approve under a chain, correct, withdraw | §7.8.2, A-I23, A-I24, Q13 |
19//!
20//! **Who may do what.** Every action names the person who takes it, as the server
21//! authenticated them. Roles come from the charter in force (spec 3.5 §7.6); before the first
22//! charter, the owner the desk was built for holds the owner, editor and publisher roles.
23//! Onboarding input is accepted only from the device the setup code paired (A-I20); a
24//! charter is signed and a job promoted only by a person who holds the role (A-I13, A-I23);
25//! content is authored only by people holding an editing role (A-I24). No agent acts here:
26//! an agent principal is refused every role.
27//!
28//! **What it keeps.** The views are rebuilt from the stores on every read. The desk holds the
29//! state of the person's own work in progress — the paired device, the onboarding answers, the
30//! charter under review, the editor's drafts — and, with a [`DeskStore`], saves it after every
31//! command and reads it back with [`WebsiteDesk::restore`], so a restart loses none of it.
32
33pub mod charter;
34pub mod editor;
35pub mod onboarding;
36pub mod review;
37mod saved;
38pub mod setup;
39pub mod site;
40mod words;
41
42use std::collections::BTreeMap;
43use std::sync::Arc;
44use std::sync::atomic::{AtomicU64, Ordering};
45
46use adk_core::audit_log::AuditTrail;
47use adk_core::{AdkError, Clock, ErrorCategory, ErrorComponent, Result, SystemClock};
48use adk_harness::website::{SiteRef, SiteRuntime};
49use adk_harness::{FactScope, FactStore, StandingRuleStore};
50use adk_kernel::PartitionId;
51use adk_kernel::channels::ChannelSink;
52use adk_kernel::charter::{AutonomyLadder, CharterStore, KpiTracker, SignalStore};
53use adk_payments::wallet::{Wallet, WalletStore};
54use adk_site::media::MediaPipeline;
55use adk_site::migrate::{SiteSource, SourceContext};
56use adk_site::updates::UpdateEngine;
57use async_trait::async_trait;
58use awp_types::{LanguageTag, Role};
59use schemars::JsonSchema;
60use serde::{Deserialize, Serialize};
61use tokio::sync::{Mutex, RwLock};
62
63use crate::alarms::AlarmRouter;
64use crate::incident::{IncidentPath, StatusSink};
65use crate::onboarding::cost::CostInputs;
66use crate::review::{ReviewComposer, ReviewInputs};
67use crate::themes::ThemeId;
68use crate::wallet::WalletKpi;
69
70pub use charter::{CharterReview, SectionCard, SignerLine};
71pub use editor::{DraftView, EditorCommand, EditorHome, EditorOutcome, KindForm};
72pub use onboarding::{OnboardingCommand, OnboardingOutcome, OnboardingView};
73pub use review::{ReviewCommand, ReviewPage, ReviewView};
74pub use saved::{DeskStore, FileDeskStore, InMemoryDeskStore, SavedDesk};
75pub use setup::{ClaimedView, SetupView};
76pub use site::{SiteCommand, SiteOutcome, SiteViewModel};
77
78/// The tone of a pill: a word always comes with it, so status is never colour alone (spec
79/// 3.3 §9).
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
81#[serde(rename_all = "camelCase")]
82pub enum Tone {
83    /// Done, passed, up.
84    Good,
85    /// Waiting for someone.
86    Waiting,
87    /// Failed, held, down.
88    Bad,
89    /// Worth knowing.
90    Info,
91    /// Neither.
92    Neutral,
93}
94
95/// A status word and its tone (spec 3.3 §9).
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
97#[serde(rename_all = "camelCase")]
98pub struct Pill {
99    /// The word, in sentence case.
100    pub text: String,
101    /// Its tone.
102    pub tone: Tone,
103}
104
105impl Pill {
106    /// A pill saying `text` in `tone`.
107    pub fn new(text: impl Into<String>, tone: Tone) -> Self {
108        Self { text: text.into(), tone }
109    }
110}
111
112/// A label and its value, for a card's lines.
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
114#[serde(rename_all = "camelCase")]
115pub struct Line {
116    /// The label.
117    pub label: String,
118    /// The value, in words.
119    pub value: String,
120}
121
122impl Line {
123    pub(crate) fn new(label: impl Into<String>, value: impl Into<String>) -> Self {
124        Self { label: label.into(), value: value.into() }
125    }
126}
127
128/// What a form field takes.
129#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
130#[serde(rename_all = "camelCase")]
131pub enum FieldKind {
132    /// One line of text.
133    Text,
134    /// Several lines of text.
135    LongText,
136    /// Markdown, with the editor's formatting buttons and preview (spec 3.5 §13 Q13).
137    Markdown,
138    /// An email address.
139    Email,
140    /// A telephone number.
141    Tel,
142    /// A web address.
143    Url,
144    /// A number.
145    Number,
146    /// A date and time.
147    DateTime,
148    /// A time of day, `HH:MM`.
149    Time,
150    /// One of `options`.
151    Choice,
152}
153
154/// One choice of a [`FieldKind::Choice`] field.
155#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
156#[serde(rename_all = "camelCase")]
157pub struct FieldOption {
158    /// The value sent back.
159    pub value: String,
160    /// What the person reads.
161    pub label: String,
162}
163
164/// One field of a form: the interview's, a charter section's or the web editor's.
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
166#[serde(rename_all = "camelCase")]
167pub struct FieldSpec {
168    /// The field's id, the key of its value.
169    pub id: String,
170    /// Its label.
171    pub label: String,
172    /// What it takes.
173    pub kind: FieldKind,
174    /// Whether it must be filled in.
175    pub required: bool,
176    /// A line under the field.
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub hint: Option<String>,
179    /// The choices of a [`FieldKind::Choice`] field.
180    #[serde(default, skip_serializing_if = "Vec::is_empty")]
181    pub options: Vec<FieldOption>,
182    /// The value it starts with.
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub value: Option<String>,
185}
186
187impl FieldSpec {
188    pub(crate) fn new(id: &str, label: &str, kind: FieldKind) -> Self {
189        Self {
190            id: id.into(),
191            label: label.into(),
192            kind,
193            required: false,
194            hint: None,
195            options: Vec::new(),
196            value: None,
197        }
198    }
199
200    pub(crate) fn required(mut self) -> Self {
201        self.required = true;
202        self
203    }
204
205    pub(crate) fn hint(mut self, hint: impl Into<String>) -> Self {
206        self.hint = Some(hint.into());
207        self
208    }
209
210    pub(crate) fn value(mut self, value: impl Into<String>) -> Self {
211        let value = value.into();
212        self.value = (!value.is_empty()).then_some(value);
213        self
214    }
215
216    pub(crate) fn options(mut self, options: impl IntoIterator<Item = (String, String)>) -> Self {
217        self.options =
218            options.into_iter().map(|(value, label)| FieldOption { value, label }).collect();
219        self
220    }
221}
222
223/// Builds the site runtime with the owner's chosen design (spec 3.5 §7.18 stage 6): the host
224/// assembles the runtime over its stores, host and log with the theme the owner picked.
225///
226/// # Example
227///
228/// ```rust,ignore
229/// struct Assembly { /* the site's stores, host and log */ }
230/// impl SiteAssembly for Assembly {
231///     fn runtime(&self, theme: Option<ThemeId>) -> Arc<SiteRuntime> { /* … */ }
232/// }
233/// ```
234pub trait SiteAssembly: Send + Sync {
235    /// The runtime with `theme`, or with the site's current look for `None`.
236    fn runtime(&self, theme: Option<ThemeId>) -> Arc<SiteRuntime>;
237}
238
239/// What a connection is for (spec 3.5 §7.18 stage 8).
240#[derive(
241    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
242)]
243#[serde(rename_all = "camelCase")]
244pub enum ConnectionKind {
245    /// The site's domain and DNS.
246    Domain,
247    /// The site's email.
248    Email,
249    /// Where alarms and cards reach the owner.
250    OwnerChannel,
251    /// Analytics and search consoles.
252    Analytics,
253    /// Payments and the wallet.
254    Payment,
255}
256
257/// How a connection is made; never by a password typed into the site (A-I19).
258#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
259#[serde(rename_all = "camelCase")]
260pub enum ConnectMethod {
261    /// The service's own sign-in page.
262    OAuth,
263    /// A credential broker the owner already uses.
264    Broker,
265    /// Pairing a device or an account with a code.
266    Pairing,
267}
268
269/// The next step of a connection, for the person to take outside the site (A-I19).
270#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
271#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
272pub enum ConnectStep {
273    /// Open the service's own page: its sign-in or the broker's grant.
274    Open {
275        /// The page.
276        url: String,
277    },
278    /// Send or enter this code where the text says.
279    Code {
280        /// The code.
281        code: String,
282        /// Where to use it.
283        how: String,
284    },
285    /// Connected; nothing more to do.
286    Done,
287}
288
289/// One service the site can connect to (spec 3.5 §7.18 stage 8, §7.13, A-I19): an OAuth
290/// grant, a credential broker or a pairing. Implementations never take a password, an API key
291/// or a card number from the person.
292#[async_trait]
293pub trait Connector: Send + Sync {
294    /// A stable id.
295    fn id(&self) -> &str;
296    /// What it is for.
297    fn kind(&self) -> ConnectionKind;
298    /// The service's name, such as "Cloudflare DNS".
299    fn service(&self) -> &str;
300    /// How it connects.
301    fn method(&self) -> ConnectMethod;
302    /// Starts connecting for `person`.
303    ///
304    /// # Errors
305    ///
306    /// Returns the connector's error.
307    async fn start(&self, person: &str) -> Result<ConnectStep>;
308    /// The account it is connected to, or `None`.
309    ///
310    /// # Errors
311    ///
312    /// Returns the connector's error.
313    async fn connected(&self) -> Result<Option<String>>;
314}
315
316/// What the jobs recorded for a week's review that no store keeps (spec 3.5 §7.21): what
317/// each agent did, experiments, leads handed off and questions.
318#[async_trait]
319pub trait ReviewNotes: Send + Sync {
320    /// The notes for the week starting `week_start`.
321    ///
322    /// # Errors
323    ///
324    /// Returns the source's error.
325    async fn notes(&self, week_start: chrono::NaiveDate) -> Result<ReviewInputs>;
326}
327
328/// The wallet as the site view reads it (spec 3.5 §7.14, §7.24).
329#[derive(Clone)]
330pub struct WalletParts {
331    /// The wallet: its balance and policy.
332    pub wallet: Wallet,
333    /// The wallet's payments, for the held ones.
334    pub store: Arc<dyn WalletStore>,
335    /// Its spend as a KPI source.
336    pub kpi: Arc<WalletKpi>,
337}
338
339pub(crate) struct Desk {
340    pub(crate) site: SiteRef,
341    pub(crate) name: String,
342    pub(crate) owner: String,
343    pub(crate) languages: Vec<LanguageTag>,
344    pub(crate) currency: String,
345    pub(crate) clock: Arc<dyn Clock>,
346    pub(crate) audit: Option<AuditTrail>,
347    pub(crate) runtime: RwLock<Arc<SiteRuntime>>,
348    pub(crate) assembly: Option<Arc<dyn SiteAssembly>>,
349    pub(crate) setup: Option<Arc<crate::onboarding::SetupGate>>,
350    pub(crate) facts: Option<(Arc<dyn FactStore>, FactScope)>,
351    pub(crate) charters: Option<Arc<dyn CharterStore>>,
352    pub(crate) ladder: Option<AutonomyLadder>,
353    pub(crate) rules: Option<Arc<dyn StandingRuleStore>>,
354    pub(crate) status: Option<Arc<dyn StatusSink>>,
355    pub(crate) tracker: Option<KpiTracker>,
356    pub(crate) signals: Option<(Arc<dyn SignalStore>, PartitionId)>,
357    pub(crate) wallet: Option<WalletParts>,
358    pub(crate) updates: Option<Arc<UpdateEngine>>,
359    pub(crate) alarms: Option<Arc<AlarmRouter>>,
360    pub(crate) incidents: Option<Arc<IncidentPath>>,
361    pub(crate) composer: Option<ReviewComposer>,
362    pub(crate) notes: Option<Arc<dyn ReviewNotes>>,
363    pub(crate) store: Option<saved::SharedDeskStore>,
364    pub(crate) quotes: Option<Arc<crate::quotes::ReviewQuotes>>,
365    pub(crate) channel: Option<(Arc<dyn ChannelSink>, String)>,
366    pub(crate) discovery: Option<(SourceContext, Option<Arc<dyn SiteSource>>)>,
367    pub(crate) connectors: Vec<Arc<dyn Connector>>,
368    pub(crate) cost: Option<CostInputs>,
369    pub(crate) shape: String,
370    pub(crate) jurisdictions: Vec<String>,
371    pub(crate) media: MediaPipeline,
372    pub(crate) paired: Mutex<Option<String>>,
373    pub(crate) onboarding: Mutex<onboarding::State>,
374    pub(crate) charter: Mutex<charter::State>,
375    pub(crate) reviews: Mutex<review::State>,
376    pub(crate) editor: Mutex<editor::State>,
377    next: AtomicU64,
378}
379
380/// The owner's desk of one site: its views and the decisions people make on them (spec 3.5
381/// §7.16 `ui`). Cheap to clone; every clone is the same desk.
382///
383/// # Example
384///
385/// ```rust,ignore
386/// let desk = WebsiteDesk::builder(site, "Juniper Bakery", "amina", runtime)
387///     .languages(vec!["en".parse()?])
388///     .currency("KES")
389///     .setup(gate)
390///     .facts(facts, scope)
391///     .charters(charters)
392///     .ladder(ladder, rules)
393///     .build();
394/// let view = desk.site_view("amina").await?;
395/// ```
396#[derive(Clone)]
397pub struct WebsiteDesk {
398    pub(crate) inner: Arc<Desk>,
399}
400
401impl std::fmt::Debug for WebsiteDesk {
402    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
403        f.debug_struct("WebsiteDesk").field("site", &self.inner.site).finish_non_exhaustive()
404    }
405}
406
407/// Builds a [`WebsiteDesk`].
408pub struct WebsiteDeskBuilder {
409    desk: Desk,
410}
411
412macro_rules! setter {
413    ($(#[$doc:meta])* $name:ident, $field:ident: $ty:ty) => {
414        $(#[$doc])*
415        #[must_use]
416        pub fn $name(mut self, value: $ty) -> Self {
417            self.desk.$field = Some(value);
418            self
419        }
420    };
421}
422
423impl WebsiteDeskBuilder {
424    /// The site's languages; the first is the default (`en` unless set).
425    #[must_use]
426    pub fn languages(mut self, languages: Vec<LanguageTag>) -> Self {
427        if !languages.is_empty() {
428            self.desk.languages = languages;
429        }
430        self
431    }
432
433    /// The budget's ISO 4217 currency (`USD` unless set).
434    #[must_use]
435    pub fn currency(mut self, currency: impl Into<String>) -> Self {
436        self.desk.currency = currency.into().to_ascii_uppercase();
437        self
438    }
439
440    /// The clock.
441    #[must_use]
442    pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
443        self.desk.clock = clock;
444        self
445    }
446
447    /// Where onboarding and charter records go (spec 3.5 §9.3).
448    #[must_use]
449    pub fn audit(mut self, trail: AuditTrail) -> Self {
450        self.desk.audit = Some(trail);
451        self
452    }
453
454    /// Rebuilds the runtime with the owner's chosen design (spec 3.5 §7.18 stage 6).
455    #[must_use]
456    pub fn assembly(mut self, assembly: Arc<dyn SiteAssembly>) -> Self {
457        self.desk.assembly = Some(assembly);
458        self
459    }
460
461    /// The setup gate of a fresh deployment (spec 3.5 §7.17, A-I20).
462    #[must_use]
463    pub fn setup(mut self, gate: Arc<crate::onboarding::SetupGate>) -> Self {
464        self.desk.setup = Some(gate);
465        self
466    }
467
468    /// The site's long-term facts and their scope (A-I18).
469    #[must_use]
470    pub fn facts(mut self, facts: Arc<dyn FactStore>, scope: FactScope) -> Self {
471        self.desk.facts = Some((facts, scope));
472        self
473    }
474
475    setter!(
476        /// The charter store (spec 3.5 §7.11).
477        charters, charters: Arc<dyn CharterStore>
478    );
479
480    /// The autonomy ladder and the standing-rule store a promotion grants rules in (spec 3.5
481    /// §7.11, A-I13).
482    #[must_use]
483    pub fn ladder(mut self, ladder: AutonomyLadder, rules: Arc<dyn StandingRuleStore>) -> Self {
484        self.desk.ladder = Some(ladder);
485        self.desk.rules = Some(rules);
486        self
487    }
488
489    setter!(
490        /// The site's status (spec 3.5 §7.5).
491        status, status: Arc<dyn StatusSink>
492    );
493    setter!(
494        /// The KPI tracker (spec 3.5 §7.11).
495        tracker, tracker: KpiTracker
496    );
497
498    /// The signal store and the back office's partition (spec 3.5 §7.10).
499    #[must_use]
500    pub fn signals(mut self, store: Arc<dyn SignalStore>, partition: PartitionId) -> Self {
501        self.desk.signals = Some((store, partition));
502        self
503    }
504
505    setter!(
506        /// The wallet (spec 3.5 §7.14).
507        wallet, wallet: WalletParts
508    );
509    setter!(
510        /// The update engine whose held batches the site view shows (spec 3.5 §7.8.3).
511        updates, updates: Arc<UpdateEngine>
512    );
513    setter!(
514        /// The alarm router (spec 3.5 §7.21).
515        alarms, alarms: Arc<AlarmRouter>
516    );
517    setter!(
518        /// The incident path (spec 3.5 §7.20).
519        incidents, incidents: Arc<IncidentPath>
520    );
521    setter!(
522        /// The weekly review's composer (spec 3.5 §7.21).
523        composer, composer: ReviewComposer
524    );
525    setter!(
526        /// What the jobs recorded for each week's review.
527        notes, notes: Arc<dyn ReviewNotes>
528    );
529
530    /// Where the desk saves the person's work in progress, so a restart keeps it (spec 3.5
531    /// §8.2); restore it with [`WebsiteDesk::restore`].
532    #[must_use]
533    pub fn store(mut self, store: Arc<dyn DeskStore>) -> Self {
534        self.desk.store = Some(store);
535        self
536    }
537
538    /// The reviews the site may quote: discovery adds what it found, and the owner decides
539    /// each from its card (spec 3.5 S2).
540    #[must_use]
541    pub fn quotes(mut self, quotes: Arc<crate::quotes::ReviewQuotes>) -> Self {
542        self.desk.quotes = Some(quotes);
543        self
544    }
545
546    /// The owner's channel and thread the review's summary goes to (spec 3.5 §7.21).
547    #[must_use]
548    pub fn channel(mut self, sink: Arc<dyn ChannelSink>, thread: impl Into<String>) -> Self {
549        self.desk.channel = Some((sink, thread.into()));
550        self
551    }
552
553    /// How discovery reads an existing site or online presence: the signed client of
554    /// `context`, and `source` in place of the default crawl or presence reader, such as a
555    /// WordPress export or a recorded inventory (spec 3.5 §7.18 stage 2).
556    #[must_use]
557    pub fn discovery(
558        mut self,
559        context: SourceContext,
560        source: Option<Arc<dyn SiteSource>>,
561    ) -> Self {
562        self.desk.discovery = Some((context, source));
563        self
564    }
565
566    /// Adds a service the owner can connect (spec 3.5 §7.18 stage 8).
567    #[must_use]
568    pub fn connector(mut self, connector: Arc<dyn Connector>) -> Self {
569        self.desk.connectors.push(connector);
570        self
571    }
572
573    /// What a month of the site looks like, for the running-cost estimate (spec 3.5 §7.22).
574    #[must_use]
575    pub fn cost(mut self, inputs: CostInputs) -> Self {
576        self.desk.cost = Some(inputs);
577        self
578    }
579
580    /// The deployment shape's name, such as "Single server or container" (spec 3.5 §7.22).
581    #[must_use]
582    pub fn shape(mut self, shape: impl Into<String>) -> Self {
583        self.desk.shape = shape.into();
584        self
585    }
586
587    /// The jurisdictions whose legal pages release 1 carries, such as `KE` (spec 3.5 §7.8.1
588    /// "Legal").
589    #[must_use]
590    pub fn jurisdictions(mut self, jurisdictions: Vec<String>) -> Self {
591        self.desk.jurisdictions = jurisdictions;
592        self
593    }
594
595    /// The media pipeline uploads go through (spec 3.5 §7.8.2 "Media").
596    #[must_use]
597    pub fn media(mut self, media: MediaPipeline) -> Self {
598        self.desk.media = media;
599        self
600    }
601
602    /// The desk.
603    pub fn build(self) -> WebsiteDesk {
604        WebsiteDesk { inner: Arc::new(self.desk) }
605    }
606}
607
608impl WebsiteDesk {
609    /// A desk for `site`, named `name` on screen, whose onboarding `owner` holds every role
610    /// until the first charter names its people, over `runtime`.
611    pub fn builder(
612        site: SiteRef,
613        name: impl Into<String>,
614        owner: impl Into<String>,
615        runtime: Arc<SiteRuntime>,
616    ) -> WebsiteDeskBuilder {
617        WebsiteDeskBuilder {
618            desk: Desk {
619                site,
620                name: name.into(),
621                owner: owner.into(),
622                languages: vec![LanguageTag::parse("en").expect("a valid tag")],
623                currency: "USD".into(),
624                clock: Arc::new(SystemClock),
625                audit: None,
626                runtime: RwLock::new(runtime),
627                assembly: None,
628                setup: None,
629                facts: None,
630                charters: None,
631                ladder: None,
632                rules: None,
633                status: None,
634                tracker: None,
635                signals: None,
636                wallet: None,
637                updates: None,
638                alarms: None,
639                incidents: None,
640                composer: None,
641                notes: None,
642                store: None,
643                quotes: None,
644                channel: None,
645                discovery: None,
646                connectors: Vec::new(),
647                cost: None,
648                shape: "Single server or container".into(),
649                jurisdictions: Vec::new(),
650                media: MediaPipeline::default(),
651                paired: Mutex::new(None),
652                onboarding: Mutex::new(onboarding::State::default()),
653                charter: Mutex::new(charter::State::default()),
654                reviews: Mutex::new(review::State::default()),
655                editor: Mutex::new(editor::State::default()),
656                next: AtomicU64::new(1),
657            },
658        }
659    }
660
661    /// The site.
662    pub fn site(&self) -> &SiteRef {
663        &self.inner.site
664    }
665
666    /// The site's name on screen.
667    pub fn name(&self) -> &str {
668        &self.inner.name
669    }
670
671    /// The site runtime as it stands: the owner's chosen design replaces it during onboarding.
672    pub async fn runtime(&self) -> Arc<SiteRuntime> {
673        self.inner.runtime.read().await.clone()
674    }
675
676    pub(crate) fn bump_next(&self, at_least: u64) {
677        self.inner.next.fetch_max(at_least, Ordering::Relaxed);
678    }
679
680    pub(crate) fn next_id(&self, prefix: &str) -> String {
681        let n = self.inner.next.fetch_add(1, Ordering::Relaxed);
682        format!("{prefix}-{n}")
683    }
684
685    pub(crate) fn now(&self) -> chrono::DateTime<chrono::Utc> {
686        self.inner.clock.now()
687    }
688
689    /// The roles `person` holds (spec 3.5 §7.6): the charter in force names them; before the
690    /// first charter, the onboarding owner holds owner, editor and publisher. An agent holds
691    /// none.
692    ///
693    /// # Errors
694    ///
695    /// Returns the charter store's error.
696    pub async fn roles(&self, person: &str) -> Result<Vec<Role>> {
697        if adk_kernel::charter::is_agent_principal(person) {
698            return Ok(Vec::new());
699        }
700        if let Some(charters) = &self.inner.charters
701            && let Some(current) = charters.current(self.inner.site.id).await.map_err(kernel)?
702        {
703            return Ok(current
704                .charter
705                .governance
706                .roles
707                .iter()
708                .filter(|held| held.principal == person)
709                .flat_map(|held| held.roles.iter().copied())
710                .collect());
711        }
712        Ok(if person == self.inner.owner {
713            vec![Role::Owner, Role::Editor, Role::Publisher]
714        } else {
715            Vec::new()
716        })
717    }
718
719    /// Refuses `person` unless they hold one of `any`.
720    pub(crate) async fn require(&self, person: &str, any: &[Role], what: &str) -> Result<()> {
721        let held = self.roles(person).await?;
722        if any.iter().any(|role| held.contains(role)) {
723            return Ok(());
724        }
725        let names: Vec<&str> = any.iter().map(|role| words::role(*role)).collect();
726        Err(forbidden(
727            "website.ui.not_allowed",
728            format!(
729                "{what} needs the {} role in the site's charter; {person} does not hold it",
730                names.join(" or ").to_lowercase()
731            ),
732        ))
733    }
734}
735
736pub(crate) fn forbidden(code: &'static str, message: impl Into<String>) -> AdkError {
737    AdkError::new(ErrorComponent::Server, ErrorCategory::Forbidden, code, message)
738}
739
740pub(crate) fn invalid(code: &'static str, message: impl Into<String>) -> AdkError {
741    AdkError::new(ErrorComponent::Server, ErrorCategory::InvalidInput, code, message)
742}
743
744pub(crate) fn not_found(code: &'static str, message: impl Into<String>) -> AdkError {
745    AdkError::new(ErrorComponent::Server, ErrorCategory::NotFound, code, message)
746}
747
748pub(crate) fn unavailable(what: &str) -> AdkError {
749    AdkError::new(
750        ErrorComponent::Server,
751        ErrorCategory::Unsupported,
752        "website.ui.not_configured",
753        format!(
754            "{what} is not set up on this site's desk; the host adds it to WebsiteDesk::builder"
755        ),
756    )
757}
758
759pub(crate) fn kernel(error: adk_kernel::KernelError) -> AdkError {
760    let category = match &error {
761        adk_kernel::KernelError::Unauthorized { .. } => ErrorCategory::Forbidden,
762        adk_kernel::KernelError::Config { .. } => ErrorCategory::InvalidInput,
763        _ => ErrorCategory::Internal,
764    };
765    AdkError::new(ErrorComponent::Server, category, "website.ui.kernel", error.to_string())
766}
767
768pub(crate) fn site(error: adk_site::SiteError) -> AdkError {
769    let category = match &error {
770        adk_site::SiteError::NotFound(_) | adk_site::SiteError::ReleaseNotFound { .. } => {
771            ErrorCategory::NotFound
772        }
773        adk_site::SiteError::InvalidContent { .. }
774        | adk_site::SiteError::GateFailed(_)
775        | adk_site::SiteError::MediaRefused { .. } => ErrorCategory::InvalidInput,
776        adk_site::SiteError::ServerCode { .. } => ErrorCategory::Forbidden,
777        _ => ErrorCategory::Internal,
778    };
779    AdkError::new(ErrorComponent::Server, category, "website.ui.site", error.to_string())
780}
781
782/// Values a form sent back, by field id.
783pub type FormValues = BTreeMap<String, String>;
784
785/// A required value of `values`, trimmed.
786pub(crate) fn required<'a>(values: &'a FormValues, field: &str, label: &str) -> Result<&'a str> {
787    values
788        .get(field)
789        .map(|value| value.trim())
790        .filter(|value| !value.is_empty())
791        .ok_or_else(|| invalid("website.ui.missing", format!("{label} is needed")))
792}
793
794/// An optional value of `values`, trimmed; `None` when blank.
795pub(crate) fn optional<'a>(values: &'a FormValues, field: &str) -> Option<&'a str> {
796    values.get(field).map(|value| value.trim()).filter(|value| !value.is_empty())
797}