1use std::collections::{BTreeMap, BTreeSet};
20use std::sync::Arc;
21
22use adk_core::Result;
23use adk_core::principal::SubjectRef;
24use adk_harness::website::CONNECTION_NOTICE;
25use adk_harness::{
26 FACT_TEXT_MAX_CHARS, FactFilter, FactKind, FactSource, FactStatus, MemoryFact, Provenance,
27 fact_digest, redact_fact_text,
28};
29use adk_site::gate::GateReport;
30use adk_site::migrate::SourceKind;
31use adk_site::pipeline::{Change, EntryPoint};
32use awp_types::{Channel, ContentId, LanguageTag, RedLine, RedLineKind, Role, SiteKind};
33use chrono::{DateTime, Utc};
34use schemars::JsonSchema;
35use serde::{Deserialize, Serialize};
36
37use super::charter::{CharterCommand, CharterReview};
38use super::editor::{ApprovalView, PendingRelease, ReleaseStep};
39use super::words::{self, money};
40use super::{
41 ConnectMethod, ConnectStep, ConnectionKind, FieldKind, FieldOption, FieldSpec, FormValues,
42 Line, Pill, Tone, WebsiteDesk, forbidden, invalid, not_found, optional, site, unavailable,
43};
44use crate::kinds::{CharterInputs, KindProposal, template};
45use crate::onboarding::build::{
46 LivePreview, PreviewSnapshot, SitePlan, known_facts, stage_release_one,
47};
48use crate::onboarding::discovery::{DesignChoice, Discovery, OwnerCard, record_facts};
49use crate::onboarding::{OnboardingProgress, RunPlan, Stage, StartingPoint};
50use crate::team::{AgentRole, SiteTeam};
51use crate::themes::{ThemeId, tokens};
52
53const DESK_SESSION: &str = "website-desk";
55
56#[derive(Default)]
57pub(crate) struct State {
58 name: Option<String>,
59 started: Option<Started>,
60 progress: Option<Arc<OnboardingProgress>>,
61 done: BTreeSet<Stage>,
62 found: Option<Found>,
63 kind: Option<SiteKind>,
64 protect: Option<bool>,
65 decisions: BTreeMap<String, String>,
66 answers: BTreeMap<String, FormValues>,
67 answer_facts: BTreeMap<String, Vec<String>>,
68 preview: Option<(PreviewSnapshot, DateTime<Utc>)>,
69 design: Option<DesignChoice>,
70 built: Option<Built>,
71 gate: Option<(GateReport, Vec<PageView>)>,
72 skipped: BTreeSet<String>,
73 pending: Option<PendingRelease>,
74 live: Option<(u64, DateTime<Utc>)>,
75}
76
77struct Started {
78 start: StartingPoint,
79 phone: Option<String>,
80}
81
82struct Found {
83 source: Option<String>,
84 facts: usize,
85 pages: usize,
86 items: usize,
87 legacy: bool,
88 proposal: Option<KindProposal>,
89 cards: Vec<OwnerCard>,
90}
91
92struct Built {
93 held: Vec<String>,
94 summary: String,
95}
96
97impl WebsiteDesk {
98 pub(crate) async fn save_onboarding(&self) -> super::saved::SavedOnboarding {
99 let state = self.inner.onboarding.lock().await;
100 super::saved::SavedOnboarding {
101 name: state.name.clone(),
102 start: state.started.as_ref().map(|started| started.start.clone()),
103 phone: state.started.as_ref().and_then(|started| started.phone.clone()),
104 done: state.done.clone(),
105 found: state.found.as_ref().map(|found| super::saved::SavedFound {
106 source: found.source.clone(),
107 facts: found.facts,
108 pages: found.pages,
109 items: found.items,
110 legacy: found.legacy,
111 proposal: found.proposal.clone(),
112 cards: found.cards.clone(),
113 }),
114 kind: state.kind,
115 protect: state.protect,
116 decisions: state.decisions.clone(),
117 answers: state.answers.clone(),
118 answer_facts: state.answer_facts.clone(),
119 design: state.design,
120 built: state.built.as_ref().map(|built| (built.held.clone(), built.summary.clone())),
121 skipped: state.skipped.clone(),
122 live: state.live,
123 }
124 }
125
126 pub(crate) async fn restore_onboarding(&self, saved: super::saved::SavedOnboarding) {
127 let mut state = self.inner.onboarding.lock().await;
128 state.progress = saved.start.as_ref().map(|_| {
129 Arc::new(OnboardingProgress::resumed(
130 self.inner.site.clone(),
131 self.inner.audit.clone(),
132 saved.done.iter().copied(),
133 ))
134 });
135 state.started = saved.start.map(|start| Started { start, phone: saved.phone });
136 state.name = saved.name;
137 state.done = saved.done;
138 state.found = saved.found.map(|found| Found {
139 source: found.source,
140 facts: found.facts,
141 pages: found.pages,
142 items: found.items,
143 legacy: found.legacy,
144 proposal: found.proposal,
145 cards: found.cards,
146 });
147 state.kind = saved.kind;
148 state.protect = saved.protect;
149 state.decisions = saved.decisions;
150 state.answers = saved.answers;
151 state.answer_facts = saved.answer_facts;
152 state.design = saved.design;
153 state.built = saved.built.map(|(held, summary)| Built { held, summary });
154 state.skipped = saved.skipped;
155 state.live = saved.live;
156 }
157}
158
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
161#[serde(rename_all = "camelCase")]
162pub enum StartFrom {
163 Site,
165 Presence,
167 Nothing,
169}
170
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
173#[serde(rename_all = "camelCase")]
174pub enum FactAnswer {
175 Right,
177 Fix,
179 Forget,
181}
182
183#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
185#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
186pub enum OnboardingCommand {
187 Start {
190 from: StartFrom,
192 #[serde(default)]
194 url: Option<String>,
195 #[serde(default)]
197 profiles: Vec<String>,
198 #[serde(default)]
200 name: Option<String>,
201 #[serde(default)]
203 phone: Option<String>,
204 },
205 Fact {
207 id: String,
209 answer: FactAnswer,
211 #[serde(default)]
213 text: Option<String>,
214 },
215 Kind {
217 kind: String,
219 },
220 Protect {
222 freeze: bool,
224 },
225 Decide {
227 card: String,
229 choice: String,
231 },
232 Answer {
234 form: String,
236 values: FormValues,
238 },
239 FinishInterview,
241 Charter {
243 command: CharterCommand,
245 },
246 Design {
248 design: String,
250 },
251 RunGate,
253 Connect {
255 connection: String,
257 },
258 Skip {
260 connection: String,
262 },
263 GoLive,
265 Approve {
267 role: String,
269 },
270}
271
272#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
274#[serde(rename_all = "camelCase")]
275pub enum StageState {
276 Done,
278 Current,
280 Later,
282}
283
284#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
286#[serde(rename_all = "camelCase")]
287pub struct StageLine {
288 pub id: String,
290 pub number: usize,
292 pub title: String,
294 pub state: StageState,
296}
297
298#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
300#[serde(rename_all = "camelCase")]
301pub struct StartView {
302 pub started: bool,
304 #[serde(default, skip_serializing_if = "Option::is_none")]
306 pub from: Option<String>,
307 pub phone: bool,
309}
310
311#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
313#[serde(rename_all = "camelCase")]
314pub struct FactView {
315 pub id: String,
317 pub text: String,
319 #[serde(default, skip_serializing_if = "Option::is_none")]
321 pub source: Option<String>,
322 pub status: Pill,
324 pub open: bool,
326}
327
328#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
330#[serde(rename_all = "camelCase")]
331pub struct KindView {
332 #[serde(default, skip_serializing_if = "Option::is_none")]
334 pub proposed: Option<String>,
335 pub reasons: Vec<String>,
337 #[serde(default, skip_serializing_if = "Option::is_none")]
339 pub confirmed: Option<String>,
340 pub options: Vec<FieldOption>,
342}
343
344#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
346#[serde(rename_all = "camelCase")]
347pub struct DecisionView {
348 pub id: String,
350 pub title: String,
352 pub detail: String,
354 pub evidence: Vec<String>,
356 pub options: Vec<FieldOption>,
358 #[serde(default, skip_serializing_if = "Option::is_none")]
360 pub default: Option<String>,
361 #[serde(default, skip_serializing_if = "Option::is_none")]
363 pub chosen: Option<String>,
364}
365
366#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
368#[serde(rename_all = "camelCase")]
369pub struct DiscoveryView {
370 pub ran: bool,
372 #[serde(default, skip_serializing_if = "Option::is_none")]
374 pub source: Option<String>,
375 pub found: Vec<Line>,
377 pub facts: Vec<FactView>,
379 pub kind: KindView,
381 pub decisions: Vec<DecisionView>,
383}
384
385#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
387#[serde(rename_all = "camelCase")]
388pub struct ProtectView {
389 pub url: String,
391 pub text: String,
393 #[serde(default, skip_serializing_if = "Option::is_none")]
395 pub freeze: Option<bool>,
396}
397
398#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
400#[serde(rename_all = "camelCase")]
401pub struct FormView {
402 pub id: String,
404 pub question: String,
406 pub fields: Vec<FieldSpec>,
408 pub answered: bool,
410 pub from_discovery: bool,
412}
413
414#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
416#[serde(rename_all = "camelCase")]
417pub struct PreviewPage {
418 pub title: String,
420 pub summary: String,
422}
423
424#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
426#[serde(rename_all = "camelCase")]
427pub struct PreviewView {
428 pub site_name: String,
430 pub pages: Vec<PreviewPage>,
432 #[serde(default, skip_serializing_if = "Option::is_none")]
434 pub about: Option<String>,
435 pub facts: usize,
437 pub rebuilt_at: DateTime<Utc>,
439 pub published: bool,
441}
442
443#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
445#[serde(rename_all = "camelCase")]
446pub struct InterviewView {
447 pub forms: Vec<FormView>,
449 pub done: bool,
451 #[serde(default, skip_serializing_if = "Option::is_none")]
453 pub preview: Option<PreviewView>,
454}
455
456#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
458#[serde(rename_all = "camelCase")]
459pub struct Swatch {
460 pub background: String,
462 pub text: String,
464 pub accent: String,
466 pub link: String,
468 pub border: String,
470}
471
472#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
474#[serde(rename_all = "camelCase")]
475pub struct DesignOption {
476 pub id: String,
478 pub name: String,
480 pub direction: String,
482 #[serde(default, skip_serializing_if = "Option::is_none")]
484 pub light: Option<Swatch>,
485 #[serde(default, skip_serializing_if = "Option::is_none")]
487 pub dark: Option<Swatch>,
488}
489
490#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
492#[serde(rename_all = "camelCase")]
493pub struct DesignView {
494 pub options: Vec<DesignOption>,
496 #[serde(default, skip_serializing_if = "Option::is_none")]
498 pub chosen: Option<String>,
499 #[serde(default, skip_serializing_if = "Option::is_none")]
501 pub built: Option<String>,
502 pub held: Vec<String>,
504}
505
506#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
508#[serde(rename_all = "camelCase")]
509pub struct CheckView {
510 pub name: String,
512 pub status: Pill,
514 pub findings: Vec<String>,
516 #[serde(default, skip_serializing_if = "Option::is_none")]
518 pub note: Option<String>,
519}
520
521#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
523#[serde(rename_all = "camelCase")]
524pub struct PageView {
525 pub path: String,
527 pub title: String,
529 pub change: Pill,
531 #[serde(default, skip_serializing_if = "Option::is_none")]
533 pub markdown: Option<String>,
534}
535
536#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
538#[serde(rename_all = "camelCase")]
539pub struct GateView {
540 pub passed: bool,
542 pub text: String,
544 pub checks: Vec<CheckView>,
546 pub pages: Vec<PageView>,
548}
549
550#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
552#[serde(rename_all = "camelCase")]
553pub struct ConnectionCard {
554 pub id: String,
556 pub kind: String,
558 pub service: String,
560 pub method: String,
562 pub status: Pill,
564 #[serde(default, skip_serializing_if = "Option::is_none")]
566 pub account: Option<String>,
567 pub can_connect: bool,
569}
570
571#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
573#[serde(rename_all = "camelCase")]
574pub struct ConnectionsView {
575 pub notice: String,
577 pub cards: Vec<ConnectionCard>,
579}
580
581#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
583#[serde(rename_all = "camelCase")]
584pub struct DeployView {
585 pub shape: String,
587 pub cost: Vec<Line>,
589 #[serde(default, skip_serializing_if = "Option::is_none")]
591 pub fits: Option<bool>,
592 pub can_go_live: bool,
594 #[serde(default, skip_serializing_if = "Option::is_none")]
596 pub waiting: Option<ApprovalView>,
597 #[serde(default, skip_serializing_if = "Option::is_none")]
599 pub live: Option<String>,
600}
601
602#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
604#[serde(rename_all = "camelCase")]
605pub struct RunView {
606 pub first_review: DateTime<Utc>,
608 pub propose_until: DateTime<Utc>,
610 pub phases: Vec<Vec<String>>,
612 pub promotions: Vec<Line>,
614}
615
616#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
618#[serde(rename_all = "camelCase")]
619pub struct OnboardingView {
620 pub site_name: String,
622 pub stages: Vec<StageLine>,
624 pub current: String,
626 pub start: StartView,
628 pub discovery: DiscoveryView,
630 #[serde(default, skip_serializing_if = "Option::is_none")]
632 pub protect: Option<ProtectView>,
633 pub interview: InterviewView,
635 #[serde(default, skip_serializing_if = "Option::is_none")]
637 pub charter: Option<CharterReview>,
638 pub design: DesignView,
640 #[serde(default, skip_serializing_if = "Option::is_none")]
642 pub gate: Option<GateView>,
643 pub connections: ConnectionsView,
645 pub deploy: DeployView,
647 #[serde(default, skip_serializing_if = "Option::is_none")]
649 pub run: Option<RunView>,
650}
651
652#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
654#[serde(rename_all = "camelCase")]
655pub struct OnboardingOutcome {
656 pub view: OnboardingView,
658 #[serde(default, skip_serializing_if = "Option::is_none")]
660 pub next: Option<ConnectStep>,
661 #[serde(default, skip_serializing_if = "Option::is_none")]
663 pub note: Option<String>,
664}
665
666fn stage_title(stage: Stage) -> &'static str {
667 match stage {
668 Stage::Start => "Start",
669 Stage::Discover => "What we found",
670 Stage::Protect => "Protect the old site",
671 Stage::Interview => "A few questions",
672 Stage::Charter => "Your charter",
673 Stage::Build => "Design and build",
674 Stage::LaunchGate => "Launch check",
675 Stage::ConnectAndDeploy => "Connect and go live",
676 Stage::Run => "Run",
677 }
678}
679
680struct Form {
683 id: &'static str,
684 question: String,
685 fields: Vec<FieldSpec>,
686 covered_by: &'static [&'static str],
687}
688
689fn channel_options() -> Vec<(String, String)> {
690 [
691 ("sms", "Text message"),
692 ("whatsapp", "WhatsApp"),
693 ("telegram", "Telegram"),
694 ("slack", "Slack"),
695 ("discord", "Discord"),
696 ("matrix", "Matrix"),
697 ("email", "Email"),
698 ]
699 .into_iter()
700 .map(|(id, label)| (id.to_string(), label.to_string()))
701 .collect()
702}
703
704fn forms(kind: SiteKind, name: &str) -> Vec<Form> {
705 let mut forms = vec![
706 Form {
707 id: "about",
708 question: format!("What is {name} for, in a sentence or two?"),
709 fields: vec![
710 FieldSpec::new("mission", "In your words", FieldKind::LongText)
711 .required()
712 .hint("This becomes the mission on your home page"),
713 ],
714 covered_by: &[],
715 },
716 Form {
717 id: "who",
718 question: format!("Who is behind {name}?"),
719 fields: vec![
720 FieldSpec::new(
721 "who",
722 "Names and roles you are happy to publish",
723 FieldKind::LongText,
724 )
725 .required(),
726 ],
727 covered_by: &[],
728 },
729 Form {
730 id: "contact",
731 question: "How can people reach you?".into(),
732 fields: vec![
733 FieldSpec::new("email", "Email", FieldKind::Email).required(),
734 FieldSpec::new("phone", "Telephone", FieldKind::Tel),
735 FieldSpec::new("address", "Address", FieldKind::Text),
736 ],
737 covered_by: &[],
738 },
739 ];
740 if matches!(
741 kind,
742 SiteKind::Business
743 | SiteKind::Health
744 | SiteKind::Community
745 | SiteKind::Education
746 | SiteKind::Government
747 | SiteKind::Nonprofit
748 ) {
749 forms.push(Form {
750 id: "hours",
751 question: "When are you open?".into(),
752 fields: vec![
753 FieldSpec::new("hours", "Opening hours", FieldKind::Text)
754 .required()
755 .hint("For example: Monday to Saturday, 07:00 to 18:00"),
756 ],
757 covered_by: &["openinghours"],
758 });
759 }
760 forms.push(Form {
761 id: "alarms",
762 question: "If something goes badly wrong, how should the site reach you?".into(),
763 fields: vec![
764 FieldSpec::new("urgent", "Urgent alarms", FieldKind::Choice)
765 .required()
766 .options(channel_options())
767 .hint("Even in quiet time, until you acknowledge them"),
768 FieldSpec::new("soon", "Within the hour", FieldKind::Choice).options(channel_options()),
769 ],
770 covered_by: &[],
771 });
772 forms.push(Form {
773 id: "never",
774 question: "Is there anything the site must never say or do?".into(),
775 fields: vec![
776 FieldSpec::new("never", "One per line", FieldKind::LongText)
777 .hint("For example: never promise same-day delivery"),
778 ],
779 covered_by: &[],
780 });
781 forms
782}
783
784fn answer_facts(form: &str, values: &FormValues, name: &str) -> Vec<String> {
786 let value = |field: &str| optional(values, field).map(str::to_string);
787 match form {
788 "about" => {
789 value("mission").map(|mission| format!("{name}: {mission}")).into_iter().collect()
790 }
791 "who" => value("who").map(|who| format!("{name} is run by {who}")).into_iter().collect(),
792 "contact" => [
794 value("phone").map(|v| format!("Telephone: {v}")),
795 value("address").map(|v| format!("Address: {v}")),
796 ]
797 .into_iter()
798 .flatten()
799 .collect(),
800 "hours" => value("hours").map(|v| format!("Opening hours: {v}")).into_iter().collect(),
801 _ => Vec::new(),
802 }
803}
804
805fn swatch(colors: &adk_site::theme::ColorTokens) -> Swatch {
806 Swatch {
807 background: colors.background.to_string(),
808 text: colors.text.to_string(),
809 accent: colors.accent.to_string(),
810 link: colors.link.to_string(),
811 border: colors.border.to_string(),
812 }
813}
814
815fn design_id(design: DesignChoice) -> String {
816 match design {
817 DesignChoice::KeepCurrent => "keep_current".into(),
818 DesignChoice::NewTheme(theme) => theme.as_str().into(),
819 }
820}
821
822fn source_words(kind: SourceKind, url: Option<&str>) -> String {
823 let at = url.map(|url| format!(" of {url}")).unwrap_or_default();
824 match kind {
825 SourceKind::WordPressRest => format!("The WordPress site{at}, through its public API"),
826 SourceKind::Wxr => "A WordPress export file".into(),
827 SourceKind::Crawl => format!("A polite crawl{at}"),
828 SourceKind::Presence => "Your profiles, listings and reviews".into(),
829 SourceKind::IsolatedReplay => "A sealed copy of the old site's database".into(),
830 _ => "Your existing site".into(),
831 }
832}
833
834fn slug_of(path: &str) -> String {
836 let trimmed = path.trim_start_matches('/').trim_end_matches("index.html").trim_end_matches('/');
837 if trimmed.is_empty() {
838 "home".into()
839 } else {
840 trimmed.rsplit('/').next().unwrap_or(trimmed).into()
841 }
842}
843
844const PAGE_MARKDOWN_MAX: usize = 6_000;
845const PREVIEW_PAGES_MAX: usize = 40;
846
847impl WebsiteDesk {
848 pub async fn site_name(&self) -> String {
850 self.inner.onboarding.lock().await.name.clone().unwrap_or_else(|| self.inner.name.clone())
851 }
852
853 fn steward(&self) -> String {
854 AgentRole::Steward.principal(&self.inner.site)
855 }
856
857 async fn complete(&self, state: &mut State, stage: Stage, release: Option<u64>) {
858 if state.done.insert(stage)
859 && let Some(progress) = &state.progress
860 {
861 progress.complete(stage, release).await;
862 }
863 }
864
865 fn inputs(&self, state: &State, name: &str) -> CharterInputs {
866 let answer = |form: &str, field: &str| {
867 state.answers.get(form).and_then(|values| optional(values, field)).map(str::to_string)
868 };
869 let mut inputs = CharterInputs::new(
870 self.inner.site.id,
871 name,
872 self.inner.owner.clone(),
873 answer("about", "mission").unwrap_or_else(|| name.to_string()),
874 self.inner.languages.clone(),
875 self.inner.currency.clone(),
876 );
877 let phone = state.started.as_ref().and_then(|s| s.phone.clone());
878 let urgent = answer("alarms", "urgent").or_else(|| phone.map(|_| "sms".to_string()));
879 inputs.p1_channels = urgent.map(|c| Channel::from(c.as_str())).into_iter().collect();
880 inputs.p2_channels =
881 answer("alarms", "soon").map(|c| Channel::from(c.as_str())).into_iter().collect();
882 inputs.contact_email = answer("contact", "email");
883 inputs
884 }
885
886 fn preview_charter(&self, state: &State, kind: SiteKind, name: &str) -> awp_types::Charter {
889 let template = template(kind);
890 let team = SiteTeam::new(self.inner.site.clone(), &template);
891 template.draft_charter(&team, &self.inputs(state, name))
892 }
893
894 async fn refresh_preview(&self, state: &mut State) -> Result<()> {
895 let (Some(kind), Some((facts, scope))) = (state.kind, self.inner.facts.clone()) else {
896 return Ok(());
897 };
898 let name = state.name.clone().unwrap_or_else(|| self.inner.name.clone());
899 let charter = self.preview_charter(state, kind, &name);
900 let preview = LivePreview::new(self.runtime().await, facts, scope, name, self.steward());
901 let snapshot = preview.refresh(&charter).await?;
902 state.preview = Some((snapshot, self.now()));
903 Ok(())
904 }
905
906 pub async fn onboarding_view(
913 &self,
914 person: &str,
915 token: Option<&str>,
916 ) -> Result<OnboardingView> {
917 match self.admit(person, token).await {
918 Ok(actor) => self.build_onboarding_view(&actor).await,
919 Err(error) => {
922 let committed = self.inner.charter.lock().await.committed.is_some();
923 if committed && !self.roles(person).await?.is_empty() {
924 self.build_onboarding_view(person).await
925 } else {
926 Err(error)
927 }
928 }
929 }
930 }
931
932 async fn build_onboarding_view(&self, actor: &str) -> Result<OnboardingView> {
933 let charter = self.charter_review(actor).await?;
934 let state = self.inner.onboarding.lock().await;
935 let name = state.name.clone().unwrap_or_else(|| self.inner.name.clone());
936 let current = Stage::ALL.into_iter().find(|stage| !state.done.contains(stage));
937 let stages = Stage::ALL
938 .into_iter()
939 .map(|stage| StageLine {
940 id: stage.as_str().into(),
941 number: stage.number(),
942 title: stage_title(stage).into(),
943 state: if state.done.contains(&stage) {
944 StageState::Done
945 } else if Some(stage) == current {
946 StageState::Current
947 } else {
948 StageState::Later
949 },
950 })
951 .collect();
952
953 let start = StartView {
954 started: state.started.is_some(),
955 from: state.started.as_ref().map(|s| match &s.start {
956 StartingPoint::ExistingSite { url } => format!("Your site at {url}"),
957 StartingPoint::Presence { profiles } => {
958 format!(
959 "{} profile{} and listing{}",
960 profiles.len(),
961 plural(profiles.len()),
962 plural(profiles.len())
963 )
964 }
965 StartingPoint::Nothing => "Nothing yet: we start from your answers".into(),
966 }),
967 phone: state.started.as_ref().is_some_and(|s| s.phone.is_some()),
968 };
969
970 let discovery = self.discovery_view(&state).await?;
971 let protect = match (&state.started, &state.found) {
972 (Some(Started { start: StartingPoint::ExistingSite { url }, .. }), Some(found))
973 if found.legacy =>
974 {
975 Some(ProtectView {
976 url: url.clone(),
977 text: "Your site runs on a server that runs code for every visitor. Freezing \
978 it serves a signed copy of every page instead, and takes the old \
979 server off the public path. Nothing is deleted; the old site and its \
980 data stay yours."
981 .into(),
982 freeze: state.protect,
983 })
984 }
985 _ => None,
986 };
987
988 let interview = match state.kind {
989 None => InterviewView { forms: Vec::new(), done: false, preview: None },
990 Some(kind) => {
991 let covered = self.confirmed_keys().await?;
992 let forms = forms(kind, &name)
993 .into_iter()
994 .map(|form| {
995 let values = state.answers.get(form.id);
996 let from_discovery = values.is_none()
997 && !form.covered_by.is_empty()
998 && form.covered_by.iter().all(|key| covered.contains(*key));
999 FormView {
1000 id: form.id.into(),
1001 question: form.question,
1002 answered: values.is_some() || from_discovery,
1003 from_discovery,
1004 fields: form
1005 .fields
1006 .into_iter()
1007 .map(|field| {
1008 let value = values.and_then(|v| v.get(&field.id)).cloned();
1009 match value {
1010 Some(value) => field.value(value),
1011 None => field,
1012 }
1013 })
1014 .collect(),
1015 }
1016 })
1017 .collect();
1018 let preview = state.preview.as_ref().map(|(snapshot, at)| {
1019 let charter = self.preview_charter(&state, kind, &name);
1020 PreviewView {
1021 site_name: name.clone(),
1022 pages: SitePlan::new(&charter, &name)
1023 .pages
1024 .into_iter()
1025 .filter(|page| page.legal.is_none())
1026 .map(|page| PreviewPage { title: page.title, summary: page.summary })
1027 .collect(),
1028 about: snapshot.about.clone(),
1029 facts: snapshot.facts,
1030 rebuilt_at: *at,
1031 published: snapshot.published,
1032 }
1033 });
1034 InterviewView { forms, done: state.done.contains(&Stage::Interview), preview }
1035 }
1036 };
1037
1038 let mut options = Vec::new();
1039 if matches!(
1040 state.started.as_ref().map(|s| &s.start),
1041 Some(StartingPoint::ExistingSite { .. })
1042 ) {
1043 options.push(DesignOption {
1044 id: "keep_current".into(),
1045 name: "Keep your current design".into(),
1046 direction: "The new site looks like the old one; the launch check compares them \
1047 page by page."
1048 .into(),
1049 light: None,
1050 dark: None,
1051 });
1052 }
1053 for theme in ThemeId::ALL {
1054 let tokens = tokens(theme);
1055 let mut name = theme.as_str().to_string();
1056 name[..1].make_ascii_uppercase();
1057 options.push(DesignOption {
1058 id: theme.as_str().into(),
1059 name,
1060 direction: theme.direction().into(),
1061 light: Some(swatch(&tokens.light.colors)),
1062 dark: Some(swatch(&tokens.dark)),
1063 });
1064 }
1065 let design = DesignView {
1066 options,
1067 chosen: state.design.map(design_id),
1068 built: state.built.as_ref().map(|built| built.summary.clone()),
1069 held: state.built.as_ref().map(|built| built.held.clone()).unwrap_or_default(),
1070 };
1071
1072 let gate = state.gate.as_ref().map(|(report, pages)| {
1073 let failed = report
1074 .checks
1075 .iter()
1076 .filter(|c| c.status == adk_site::gate::CheckStatus::Failed)
1077 .count();
1078 GateView {
1079 passed: report.passed(),
1080 text: if report.passed() {
1081 "Every check passed. Review each page, then connect and go live.".into()
1082 } else {
1083 format!(
1084 "{failed} check{} need{} a fix before launch.",
1085 plural(failed),
1086 if failed == 1 { "s" } else { "" }
1087 )
1088 },
1089 checks: report
1090 .checks
1091 .iter()
1092 .map(|check| CheckView {
1093 name: words::check(check.check).into(),
1094 status: words::check_status(check.status),
1095 findings: check
1096 .findings
1097 .iter()
1098 .filter(|f| f.blocking)
1099 .take(5)
1100 .map(|f| f.message.clone())
1101 .collect(),
1102 note: check.note.clone(),
1103 })
1104 .collect(),
1105 pages: pages.clone(),
1106 }
1107 });
1108
1109 let mut cards = Vec::new();
1110 for connector in &self.inner.connectors {
1111 let account = connector.connected().await?;
1112 let status = match (&account, state.skipped.contains(connector.id())) {
1113 (Some(_), _) => Pill::new("Connected", Tone::Good),
1114 (None, true) => Pill::new("Later", Tone::Neutral),
1115 (None, false) => Pill::new("Not connected", Tone::Waiting),
1116 };
1117 cards.push(ConnectionCard {
1118 id: connector.id().into(),
1119 kind: connection_kind(connector.kind()).into(),
1120 service: connector.service().into(),
1121 method: connect_method(connector.method()).into(),
1122 status,
1123 can_connect: account.is_none(),
1124 account,
1125 });
1126 }
1127 let offered: BTreeSet<ConnectionKind> =
1128 self.inner.connectors.iter().map(|c| c.kind()).collect();
1129 for kind in [
1130 ConnectionKind::Domain,
1131 ConnectionKind::Email,
1132 ConnectionKind::OwnerChannel,
1133 ConnectionKind::Analytics,
1134 ConnectionKind::Payment,
1135 ] {
1136 if !offered.contains(&kind) {
1137 cards.push(ConnectionCard {
1138 id: format!("later-{}", connection_kind(kind).to_lowercase().replace(' ', "-")),
1139 kind: connection_kind(kind).into(),
1140 service: "Not set up on this site yet".into(),
1141 method: "You can add it later".into(),
1142 status: Pill::new("Later", Tone::Neutral),
1143 account: None,
1144 can_connect: false,
1145 });
1146 }
1147 }
1148 let connections = ConnectionsView { notice: CONNECTION_NOTICE.into(), cards };
1149
1150 let committed = charter.as_ref().and_then(|c| c.committed.as_ref()).is_some();
1151 let draft = self.inner.charter.lock().await.draft.clone();
1152 let estimate = match &draft {
1153 Some(draft) => self.estimate(draft).await,
1154 None => None,
1155 };
1156 let currency = self.inner.currency.clone();
1157 let deploy = DeployView {
1158 shape: self.inner.shape.clone(),
1159 cost: estimate
1160 .as_ref()
1161 .map(|e| {
1162 e.monthly
1163 .iter()
1164 .map(|(category, amount)| {
1165 Line::new(words::category(*category), money(*amount, ¤cy))
1166 })
1167 .chain(std::iter::once(Line::new("Each month", money(e.total, ¤cy))))
1168 .collect()
1169 })
1170 .unwrap_or_default(),
1171 fits: match (&estimate, &draft) {
1172 (Some(e), Some(d)) => Some(e.fits(&d.budget)),
1173 _ => None,
1174 },
1175 can_go_live: committed
1176 && state.gate.as_ref().is_some_and(|(report, _)| report.passed())
1177 && state.live.is_none()
1178 && state.pending.is_none(),
1179 waiting: match &state.pending {
1180 Some(pending) => Some(self.approval_view(pending, actor).await?),
1181 None => None,
1182 },
1183 live: state.live.map(|(seq, at)| {
1184 format!("Live since {} · release {seq}, signed", at.format("%-d %b %H:%M"))
1185 }),
1186 };
1187
1188 let run = match (state.live, charter.as_ref().and_then(|c| c.committed.as_ref())) {
1189 (Some((_, at)), Some(_)) => {
1190 let committed = self.inner.charter.lock().await.committed.clone();
1191 committed.map(|version| {
1192 let plan = RunPlan::new(&version.charter, at);
1193 RunView {
1194 first_review: plan.first_review,
1195 propose_until: plan.propose_until,
1196 phases: plan.phases.to_vec(),
1197 promotions: plan
1198 .promotions
1199 .iter()
1200 .map(|(job, level)| {
1201 Line::new(
1202 crate::jobs::job(job).map_or(job.as_str(), |spec| spec.title),
1203 words::level(*level),
1204 )
1205 })
1206 .collect(),
1207 }
1208 })
1209 }
1210 _ => None,
1211 };
1212
1213 Ok(OnboardingView {
1214 site_name: name,
1215 stages,
1216 current: current.map_or_else(|| "done".to_string(), |stage| stage.as_str().to_string()),
1217 start,
1218 discovery,
1219 protect,
1220 interview,
1221 charter,
1222 design,
1223 gate,
1224 connections,
1225 deploy,
1226 run,
1227 })
1228 }
1229
1230 async fn confirmed_keys(&self) -> Result<BTreeSet<String>> {
1232 let Some((facts, scope)) = &self.inner.facts else { return Ok(BTreeSet::new()) };
1233 Ok(facts
1234 .list(FactFilter::recall(scope))
1235 .await?
1236 .into_iter()
1237 .filter(|fact| !fact.provenance.source_ids.is_empty())
1238 .filter(|fact| fact.status == FactStatus::Known)
1239 .filter_map(|fact| {
1240 fact.text.split_once(':').map(|(key, _)| key.to_lowercase().replace(' ', ""))
1241 })
1242 .collect())
1243 }
1244
1245 async fn discovery_view(&self, state: &State) -> Result<DiscoveryView> {
1246 let mut facts = Vec::new();
1247 if let Some((store, scope)) = &self.inner.facts {
1248 for fact in store.list(FactFilter::user(&scope.app, &scope.user)).await? {
1249 if fact.provenance.source_ids.is_empty() || !scope.admits(&fact.scope) {
1250 continue;
1251 }
1252 let (status, open) = match fact.status {
1253 FactStatus::Assumed => (Pill::new("A guess", Tone::Waiting), true),
1254 FactStatus::Known => (Pill::new("You said this", Tone::Good), false),
1256 _ => continue,
1257 };
1258 facts.push(FactView {
1259 id: fact.id.clone(),
1260 text: fact_words(&fact.text),
1261 source: fact.provenance.source_ids.first().cloned(),
1262 status,
1263 open,
1264 });
1265 }
1266 facts.sort_by(|a, b| a.text.cmp(&b.text));
1268 }
1269 let proposal = state.found.as_ref().and_then(|found| found.proposal.clone());
1270 let mut kinds: Vec<SiteKind> = Vec::new();
1271 if let Some(proposal) = &proposal {
1272 kinds.push(proposal.kind);
1273 kinds.extend(proposal.alternatives.iter().copied());
1274 }
1275 for kind in words::KINDS {
1276 if !kinds.contains(&kind) {
1277 kinds.push(kind);
1278 }
1279 }
1280 let kind = KindView {
1281 proposed: proposal.as_ref().map(|p| words::kind_id(p.kind).to_string()),
1282 reasons: proposal.as_ref().map(|p| p.reasons.clone()).unwrap_or_default(),
1283 confirmed: state.kind.map(|kind| words::kind_id(kind).to_string()),
1284 options: kinds
1285 .into_iter()
1286 .map(|kind| FieldOption {
1287 value: words::kind_id(kind).into(),
1288 label: template(kind).title.into(),
1289 })
1290 .collect(),
1291 };
1292 let mut decisions = Vec::new();
1293 if let Some(found) = &state.found {
1294 for card in &found.cards {
1295 match card {
1296 OwnerCard::Quarantined { entry } => {
1297 let id = format!("quarantine:{}", entry.content_id);
1298 let releasable = entry.findings.iter().all(|f| f.kind.releasable());
1299 let mut options = vec![FieldOption {
1300 value: "keep_out".into(),
1301 label: "Keep it out of the site".into(),
1302 }];
1303 if releasable {
1304 options.push(FieldOption {
1305 value: "release".into(),
1306 label: "It is mine: publish it".into(),
1307 });
1308 }
1309 decisions.push(DecisionView {
1310 title: entry
1311 .path
1312 .clone()
1313 .or_else(|| entry.item.clone())
1314 .unwrap_or_else(|| entry.content_id.to_string()),
1315 detail: entry
1316 .findings
1317 .iter()
1318 .map(|f| finding_words(f.kind))
1319 .collect::<Vec<_>>()
1320 .join("; "),
1321 evidence: entry
1322 .findings
1323 .iter()
1324 .flat_map(|f| f.evidence.iter())
1325 .take(3)
1326 .map(|e| match &e.url {
1327 Some(url) => format!("{} — {url}", e.detail),
1328 None => e.detail.clone(),
1329 })
1330 .collect(),
1331 options,
1332 default: Some("keep_out".into()),
1333 chosen: state.decisions.get(&id).cloned(),
1334 id,
1335 });
1336 }
1337 OwnerCard::Feature { decision } => {
1338 let id = format!("feature:{}", decision.id);
1339 decisions.push(DecisionView {
1340 title: decision.question.clone(),
1341 detail: format!(
1342 "Found on {} page{}",
1343 decision.evidence.len(),
1344 plural(decision.evidence.len())
1345 ),
1346 evidence: Vec::new(),
1347 options: decision
1348 .options
1349 .iter()
1350 .map(|o| FieldOption {
1351 value: o.id.clone(),
1352 label: o.label.clone(),
1353 })
1354 .collect(),
1355 default: Some(decision.default.clone()),
1356 chosen: state.decisions.get(&id).cloned(),
1357 id,
1358 });
1359 }
1360 OwnerCard::ConfirmKind { .. }
1361 | OwnerCard::Freeze { .. }
1362 | OwnerCard::Design { .. } => {}
1363 }
1364 }
1365 }
1366 if let Some(quotes) = &self.inner.quotes {
1369 for (index, review) in quotes.list().await.into_iter().enumerate() {
1370 let Some(author) = review.author.clone().filter(|a| !a.trim().is_empty()) else {
1371 continue;
1372 };
1373 let id = format!("review:{index}");
1374 let excerpt: String = review.text.chars().take(160).collect();
1375 decisions.push(DecisionView {
1376 title: format!("Quote {author}'s review on the site?"),
1377 detail: format!(
1378 "\"{excerpt}\" — a page quotes it with {author}'s name only if you say yes"
1379 ),
1380 evidence: review.source.clone().into_iter().collect(),
1381 options: vec![
1382 FieldOption {
1383 value: "quote".into(),
1384 label: "Yes, quote it with their name".into(),
1385 },
1386 FieldOption {
1387 value: "do_not_quote".into(),
1388 label: "Do not quote it".into(),
1389 },
1390 ],
1391 default: Some("do_not_quote".into()),
1392 chosen: state.decisions.get(&id).cloned(),
1393 id,
1394 });
1395 }
1396 }
1397 Ok(DiscoveryView {
1398 ran: state.found.is_some(),
1399 source: state.found.as_ref().and_then(|f| f.source.clone()),
1400 found: state
1401 .found
1402 .as_ref()
1403 .map(|found| {
1404 [
1405 ("Facts to check", found.facts),
1406 ("Pages", found.pages),
1407 ("Posts, products and other items", found.items),
1408 ]
1409 .into_iter()
1410 .filter(|(_, count)| *count > 0)
1411 .map(|(label, count)| Line::new(label, count.to_string()))
1412 .collect()
1413 })
1414 .unwrap_or_default(),
1415 facts,
1416 kind,
1417 decisions,
1418 })
1419 }
1420
1421 pub async fn onboarding_command(
1430 &self,
1431 person: &str,
1432 token: Option<&str>,
1433 command: OnboardingCommand,
1434 ) -> Result<OnboardingOutcome> {
1435 let result = self.onboarding_command_unsaved(person, token, command).await;
1436 if result.is_ok() {
1437 self.persist().await;
1438 }
1439 result
1440 }
1441
1442 async fn onboarding_command_unsaved(
1443 &self,
1444 person: &str,
1445 token: Option<&str>,
1446 command: OnboardingCommand,
1447 ) -> Result<OnboardingOutcome> {
1448 let actor = match &command {
1452 OnboardingCommand::Approve { .. } => {
1453 if !self.setup_view().await.paired {
1454 return Err(self.admit(person, None).await.err().unwrap_or_else(|| {
1455 forbidden("website.setup.unpaired", "the site has not been claimed")
1456 }));
1457 }
1458 person.to_string()
1459 }
1460 _ => self.admit(person, token).await?,
1461 };
1462 let mut next = None;
1463 let mut note = None;
1464 match command {
1465 OnboardingCommand::Start { from, url, profiles, name, phone } => {
1466 self.require(&actor, &[Role::Owner], "Starting onboarding").await?;
1467 note = self.start(&actor, from, url, profiles, name, phone).await?;
1468 }
1469 OnboardingCommand::Fact { id, answer, text } => {
1470 self.require(&actor, &[Role::Owner], "Confirming a fact").await?;
1471 self.answer_fact(&actor, &id, answer, text.as_deref()).await?;
1472 let mut state = self.inner.onboarding.lock().await;
1473 self.refresh_preview(&mut state).await?;
1474 }
1475 OnboardingCommand::Kind { kind } => {
1476 self.require(&actor, &[Role::Owner], "Confirming the kind of site").await?;
1477 let kind =
1478 words::KINDS.into_iter().find(|k| words::kind_id(*k) == kind).ok_or_else(
1479 || invalid("website.onboarding.kind", format!("no kind '{kind}'")),
1480 )?;
1481 let mut state = self.inner.onboarding.lock().await;
1482 if state.started.is_none() {
1483 return Err(invalid("website.onboarding.order", "start first"));
1484 }
1485 if state.done.contains(&Stage::Interview) {
1486 return Err(invalid(
1487 "website.onboarding.order",
1488 "the charter is drafted for this kind; a new kind is a charter change",
1489 ));
1490 }
1491 state.kind = Some(kind);
1492 self.complete(&mut state, Stage::Discover, None).await;
1493 if !state.found.as_ref().is_some_and(|found| found.legacy) {
1494 self.complete(&mut state, Stage::Protect, None).await;
1495 }
1496 if let Some(ladder) = &self.inner.ladder
1497 && let Err(error) =
1498 crate::jobs::register_onboarding(ladder, self.inner.site.id).await
1499 {
1500 tracing::warn!(error = %error, "the onboarding job could not be registered");
1501 }
1502 self.refresh_preview(&mut state).await?;
1503 }
1504 OnboardingCommand::Protect { freeze } => {
1505 self.require(&actor, &[Role::Owner], "Deciding the freeze").await?;
1506 let mut state = self.inner.onboarding.lock().await;
1507 if !state.found.as_ref().is_some_and(|found| found.legacy) {
1508 return Err(invalid(
1509 "website.onboarding.order",
1510 "there is no legacy site to freeze",
1511 ));
1512 }
1513 state.protect = Some(freeze);
1514 if state.kind.is_some() {
1515 self.complete(&mut state, Stage::Protect, None).await;
1516 }
1517 note = Some(if freeze {
1518 "The Steward freezes the old site: a signed copy goes live and the old server leaves the public path.".into()
1519 } else {
1520 "The old site stays as it is until you launch.".into()
1521 });
1522 }
1523 OnboardingCommand::Decide { card, choice } => {
1524 self.require(&actor, &[Role::Owner], "Deciding what the old site's parts become")
1525 .await?;
1526 let mut state = self.inner.onboarding.lock().await;
1527 let view = self.discovery_view(&state).await?;
1528 let decision = view.decisions.iter().find(|d| d.id == card).ok_or_else(|| {
1529 not_found("website.onboarding.card", format!("no card '{card}'"))
1530 })?;
1531 if !decision.options.iter().any(|o| o.value == choice) {
1532 return Err(invalid(
1533 "website.onboarding.choice",
1534 format!("'{choice}' is not a choice of this card"),
1535 ));
1536 }
1537 if let (Some(quotes), Some(index)) = (
1538 &self.inner.quotes,
1539 card.strip_prefix("review:").and_then(|n| n.parse::<usize>().ok()),
1540 ) {
1541 let decision = format!("quote-review-{index}-{actor}");
1542 quotes.approve(index, (choice == "quote").then_some(decision.as_str())).await?;
1543 }
1544 state.decisions.insert(card, choice);
1545 }
1546 OnboardingCommand::Answer { form, values } => {
1547 self.require(&actor, &[Role::Owner], "Answering the interview").await?;
1548 self.answer(&actor, &form, values).await?;
1549 }
1550 OnboardingCommand::FinishInterview => {
1551 self.require(&actor, &[Role::Owner], "Finishing the interview").await?;
1552 self.finish_interview().await?;
1553 }
1554 OnboardingCommand::Charter { command } => {
1555 if let Some(version) = self.charter_command(&actor, command).await? {
1556 let mut state = self.inner.onboarding.lock().await;
1557 self.complete(&mut state, Stage::Charter, None).await;
1558 note = Some(format!(
1559 "Charter version {} is signed and in force.",
1560 version.version()
1561 ));
1562 }
1563 }
1564 OnboardingCommand::Design { design } => {
1565 self.require(&actor, &[Role::Owner], "Choosing the design").await?;
1566 note = Some(self.choose_design(&design).await?);
1567 }
1568 OnboardingCommand::RunGate => {
1569 self.require(&actor, &[Role::Owner], "Running the launch check").await?;
1570 self.run_gate().await?;
1571 }
1572 OnboardingCommand::Connect { connection } => {
1573 self.require(&actor, &[Role::Owner], "Connecting a service").await?;
1574 let connector =
1575 self.inner.connectors.iter().find(|c| c.id() == connection).ok_or_else(
1576 || {
1577 not_found(
1578 "website.onboarding.connection",
1579 format!("no connection '{connection}'"),
1580 )
1581 },
1582 )?;
1583 next = Some(connector.start(&actor).await?);
1584 self.inner.onboarding.lock().await.skipped.remove(&connection);
1585 }
1586 OnboardingCommand::Skip { connection } => {
1587 self.require(&actor, &[Role::Owner], "Leaving a connection for later").await?;
1588 self.inner.onboarding.lock().await.skipped.insert(connection);
1589 }
1590 OnboardingCommand::GoLive => {
1591 self.require(&actor, &[Role::Owner], "Going live").await?;
1592 note = Some(self.go_live().await?);
1593 }
1594 OnboardingCommand::Approve { role } => {
1595 let mut state = self.inner.onboarding.lock().await;
1596 let mut pending = state.pending.take().ok_or_else(|| {
1597 not_found("website.onboarding.no_launch", "no launch waits for approval")
1598 })?;
1599 match self.approve_release(&mut pending, &actor, &role).await {
1600 Ok(Some(step)) => note = Some(self.launched(&mut state, step).await),
1601 Ok(None) => {
1602 state.pending = Some(pending);
1603 note = Some(
1604 "Your approval is recorded; the launch waits for the other roles."
1605 .into(),
1606 );
1607 }
1608 Err(error) => {
1609 state.pending = Some(pending);
1610 return Err(error);
1611 }
1612 }
1613 }
1614 }
1615 Ok(OnboardingOutcome { view: self.build_onboarding_view(&actor).await?, next, note })
1616 }
1617
1618 async fn start(
1619 &self,
1620 actor: &str,
1621 from: StartFrom,
1622 url: Option<String>,
1623 profiles: Vec<String>,
1624 name: Option<String>,
1625 phone: Option<String>,
1626 ) -> Result<Option<String>> {
1627 let mut state = self.inner.onboarding.lock().await;
1628 if state.started.is_some() {
1629 return Err(invalid("website.onboarding.started", "onboarding has started already"));
1630 }
1631 let start = match from {
1632 StartFrom::Site => StartingPoint::ExistingSite {
1633 url: url.map(|u| u.trim().to_string()).filter(|u| !u.is_empty()).ok_or_else(
1634 || invalid("website.onboarding.url", "enter your site's address"),
1635 )?,
1636 },
1637 StartFrom::Presence => {
1638 let profiles: Vec<String> = profiles
1639 .into_iter()
1640 .map(|p| p.trim().to_string())
1641 .filter(|p| !p.is_empty())
1642 .collect();
1643 if profiles.is_empty() {
1644 return Err(invalid(
1645 "website.onboarding.profiles",
1646 "add at least one profile or listing",
1647 ));
1648 }
1649 StartingPoint::Presence { profiles }
1650 }
1651 StartFrom::Nothing => StartingPoint::Nothing,
1652 };
1653 let phone = phone.map(|p| p.trim().to_string()).filter(|p| !p.is_empty());
1654 if let Some(phone) = &phone
1655 && !phone.chars().all(|c| c.is_ascii_digit() || " +-()".contains(c))
1656 {
1657 return Err(invalid(
1658 "website.onboarding.phone",
1659 "a phone number has digits, spaces and + only",
1660 ));
1661 }
1662 let name = name.map(|n| n.trim().to_string()).filter(|n| !n.is_empty());
1663 let mut note = None;
1664 if !matches!(start, StartingPoint::Nothing) {
1665 let (context, source) = self
1666 .inner
1667 .discovery
1668 .clone()
1669 .ok_or_else(|| unavailable("Discovery of an existing site or presence"))?;
1670 let language = self
1671 .inner
1672 .languages
1673 .first()
1674 .cloned()
1675 .unwrap_or_else(|| LanguageTag::parse("en").expect("a valid tag"));
1676 let mut discovery = Discovery::new(start.clone(), language)?;
1677 if let Some(source) = source {
1678 discovery = discovery.with_source(source);
1679 }
1680 let discovered = discovery.run(&context).await?;
1681 let (store, scope) =
1682 self.inner.facts.clone().ok_or_else(|| unavailable("The site's fact store"))?;
1683 let recorded =
1684 record_facts(discovered.facts(), store.as_ref(), &scope, DESK_SESSION).await?;
1685 let inventory = discovered.inventory.as_ref();
1686 if let (Some(quotes), Some(inventory)) = (&self.inner.quotes, inventory) {
1688 quotes.add_discovered(&inventory.reviews).await?;
1689 }
1690 note = Some(format!(
1691 "Found {} fact{} to check. Each is a guess until you confirm it.",
1692 recorded.len(),
1693 plural(recorded.len())
1694 ));
1695 state.found = Some(Found {
1696 source: inventory.map(|i| source_words(i.source, i.origin.as_deref())),
1697 facts: recorded.len(),
1698 pages: inventory.map_or(0, |i| i.urls.len()),
1699 items: inventory.map_or(0, |i| i.items.len()),
1700 legacy: discovered.legacy_runtime,
1701 proposal: discovered.kind.clone(),
1702 cards: discovered.cards(),
1703 });
1704 if name.is_none()
1705 && let Some(found_name) = inventory.and_then(|i| i.site_name.clone())
1706 {
1707 state.name = Some(found_name);
1708 }
1709 } else {
1710 state.found = None;
1711 }
1712 if name.is_some() {
1713 state.name = name;
1714 }
1715 let progress =
1716 OnboardingProgress::start(self.inner.site.clone(), &start, self.inner.audit.clone())
1717 .await;
1718 state.progress = Some(Arc::new(progress));
1719 state.started = Some(Started { start, phone });
1720 self.complete(&mut state, Stage::Start, None).await;
1721 tracing::info!(website.site = %self.inner.site.id, actor, "website.onboarding.started");
1722 Ok(note)
1723 }
1724
1725 async fn answer_fact(
1726 &self,
1727 actor: &str,
1728 id: &str,
1729 answer: FactAnswer,
1730 text: Option<&str>,
1731 ) -> Result<()> {
1732 let (store, scope) =
1733 self.inner.facts.clone().ok_or_else(|| unavailable("The site's fact store"))?;
1734 let fact = store
1735 .get(id)
1736 .await?
1737 .filter(|fact| scope.admits(&fact.scope) && !fact.provenance.source_ids.is_empty())
1738 .ok_or_else(|| {
1739 not_found("website.onboarding.fact", format!("no discovered fact '{id}'"))
1740 })?;
1741 if fact.status != FactStatus::Assumed {
1742 return Err(invalid("website.onboarding.fact", "this fact is answered already"));
1743 }
1744 let by = SubjectRef::human(actor);
1745 let (text, source) = match answer {
1748 FactAnswer::Forget => return store.set_status(id, FactStatus::Forgotten, &by).await,
1749 FactAnswer::Right => (fact_words(&fact.text), FactSource::UserConfirmed),
1750 FactAnswer::Fix => {
1751 let text = text.map(str::trim).filter(|t| !t.is_empty()).ok_or_else(|| {
1752 invalid("website.onboarding.fact", "write what is right instead")
1753 })?;
1754 (redact_fact_text(text, FACT_TEXT_MAX_CHARS)?, FactSource::UserStated)
1755 }
1756 };
1757 if text == fact.text {
1758 return store.set_status(id, FactStatus::Known, &by).await;
1759 }
1760 let digest = fact_digest(&text);
1763 let same = store.list(FactFilter::user(&scope.app, &scope.user)).await?.into_iter().find(
1764 |other| {
1765 other.id != fact.id
1766 && other.status.is_live()
1767 && other.scope == fact.scope
1768 && other.digest == digest
1769 },
1770 );
1771 if let Some(other) = same {
1772 store.set_status(&other.id, FactStatus::Known, &by).await?;
1773 return store.set_status(id, FactStatus::Superseded { by: other.id }, &by).await;
1774 }
1775 let mut provenance = Provenance::new(source, DESK_SESSION, self.next_id("fact"));
1776 provenance.quote = Some(text.clone());
1777 provenance.source_ids = fact.provenance.source_ids.clone();
1778 let known = MemoryFact::new(scope.clone(), fact.kind, text, FactStatus::Known, provenance);
1779 store.set_status(id, FactStatus::Superseded { by: known.id.clone() }, &by).await?;
1781 store.put(known).await.map(drop)
1782 }
1783
1784 async fn answer(&self, actor: &str, form_id: &str, values: FormValues) -> Result<()> {
1785 let mut state = self.inner.onboarding.lock().await;
1786 let kind = state.kind.ok_or_else(|| {
1787 invalid("website.onboarding.order", "confirm what kind of site this is first")
1788 })?;
1789 if state.done.contains(&Stage::Interview) {
1790 return Err(invalid(
1791 "website.onboarding.order",
1792 "the interview is done; change the charter's cards instead",
1793 ));
1794 }
1795 let name = state.name.clone().unwrap_or_else(|| self.inner.name.clone());
1796 let form =
1797 forms(kind, &name).into_iter().find(|form| form.id == form_id).ok_or_else(|| {
1798 not_found("website.onboarding.form", format!("no question '{form_id}'"))
1799 })?;
1800 let mut clean = FormValues::new();
1801 for field in &form.fields {
1802 let value = values.get(&field.id).map(|v| v.trim().to_string()).unwrap_or_default();
1803 if field.required && value.is_empty() {
1804 return Err(invalid("website.ui.missing", format!("{} is needed", field.label)));
1805 }
1806 if value.is_empty() {
1807 continue;
1808 }
1809 match field.kind {
1810 FieldKind::Email if !value.contains('@') || value.contains(' ') => {
1811 return Err(invalid(
1812 "website.onboarding.email",
1813 format!("{} is not an email address", value),
1814 ));
1815 }
1816 FieldKind::Choice if !field.options.iter().any(|o| o.value == value) => {
1817 return Err(invalid(
1818 "website.onboarding.choice",
1819 format!("choose one of the options for {}", field.label),
1820 ));
1821 }
1822 _ => {}
1823 }
1824 redact_fact_text(&value, FACT_TEXT_MAX_CHARS * 4)?;
1826 clean.insert(field.id.clone(), value);
1827 }
1828 if let Some((store, scope)) = self.inner.facts.clone() {
1829 let by = SubjectRef::human(actor);
1830 for old in state.answer_facts.remove(form_id).unwrap_or_default() {
1831 store.set_status(&old, FactStatus::Forgotten, &by).await?;
1832 }
1833 let mut ids = Vec::new();
1834 for text in answer_facts(form_id, &clean, &name) {
1835 let text = redact_fact_text(&text, FACT_TEXT_MAX_CHARS)?;
1836 let mut provenance =
1837 Provenance::new(FactSource::UserStated, DESK_SESSION, self.next_id("answer"));
1838 provenance.quote = Some(text.clone());
1839 let stored = store
1840 .put(MemoryFact::new(
1841 scope.clone(),
1842 FactKind::ProjectFact,
1843 text,
1844 FactStatus::Known,
1845 provenance,
1846 ))
1847 .await?;
1848 ids.push(stored.id);
1849 }
1850 state.answer_facts.insert(form_id.to_string(), ids);
1851 }
1852 state.answers.insert(form_id.to_string(), clean);
1853 self.refresh_preview(&mut state).await
1854 }
1855
1856 async fn finish_interview(&self) -> Result<()> {
1857 let covered = self.confirmed_keys().await?;
1858 let mut state = self.inner.onboarding.lock().await;
1859 let kind = state.kind.ok_or_else(|| {
1860 invalid("website.onboarding.order", "confirm what kind of site this is first")
1861 })?;
1862 if state.done.contains(&Stage::Interview) {
1863 return Ok(());
1864 }
1865 let name = state.name.clone().unwrap_or_else(|| self.inner.name.clone());
1866 for form in forms(kind, &name) {
1867 let required = form.fields.iter().any(|f| f.required);
1868 let covered =
1869 !form.covered_by.is_empty() && form.covered_by.iter().all(|k| covered.contains(*k));
1870 if required && !covered && !state.answers.contains_key(form.id) {
1871 return Err(invalid(
1872 "website.onboarding.unanswered",
1873 format!("answer \"{}\" first", form.question),
1874 ));
1875 }
1876 }
1877 let template = template(kind);
1878 let team = SiteTeam::new(self.inner.site.clone(), &template);
1879 let inputs = self.inputs(&state, &name);
1880 let mut charter =
1881 crate::onboarding::draft_charter(&template, &team, &inputs, self.inner.audit.as_ref())
1882 .await;
1883 if let Some(never) = state.answers.get("never").and_then(|v| optional(v, "never")) {
1884 for line in never.lines().map(str::trim).filter(|l| !l.is_empty()) {
1885 charter
1886 .red_lines
1887 .push(RedLine { kind: RedLineKind::Claim, text: line.to_string() });
1888 }
1889 }
1890 self.inner.charter.lock().await.draft = Some(charter);
1891 self.complete(&mut state, Stage::Interview, None).await;
1892 Ok(())
1893 }
1894
1895 async fn choose_design(&self, design: &str) -> Result<String> {
1896 let committed = self.inner.charter.lock().await.committed.clone().ok_or_else(|| {
1897 invalid(
1898 "website.onboarding.order",
1899 "sign the charter first: every page serves one of its goals",
1900 )
1901 })?;
1902 let mut state = self.inner.onboarding.lock().await;
1903 let choice = if design == "keep_current" {
1904 if !matches!(
1905 state.started.as_ref().map(|s| &s.start),
1906 Some(StartingPoint::ExistingSite { .. })
1907 ) {
1908 return Err(invalid(
1909 "website.onboarding.design",
1910 "there is no current design to keep",
1911 ));
1912 }
1913 DesignChoice::KeepCurrent
1914 } else {
1915 DesignChoice::NewTheme(
1916 design.parse::<ThemeId>().map_err(|e| invalid("website.onboarding.design", e))?,
1917 )
1918 };
1919 if state.live.is_some() {
1920 return Err(invalid(
1921 "website.onboarding.order",
1922 "the site is live; a new design is a release",
1923 ));
1924 }
1925 if matches!(
1926 state.started.as_ref().map(|s| &s.start),
1927 Some(StartingPoint::ExistingSite { .. })
1928 ) {
1929 crate::audit::record(
1931 self.inner.audit.as_ref(),
1932 "site.migration.decided",
1933 adk_core::audit_log::AuditActor::default(),
1934 serde_json::json!({
1935 "site": self.inner.site.id,
1936 "migration": adk_site::migrate::parity::design_choice_fields(&choice.parity()),
1937 }),
1938 )
1939 .await;
1940 }
1941 if let Some(assembly) = &self.inner.assembly {
1942 let theme = match choice {
1943 DesignChoice::KeepCurrent => None,
1944 DesignChoice::NewTheme(theme) => Some(theme),
1945 };
1946 *self.inner.runtime.write().await = assembly.runtime(theme);
1947 }
1948 let runtime = self.runtime().await;
1949 let name = state.name.clone().unwrap_or_else(|| self.inner.name.clone());
1950 let charter = &committed.charter;
1951 let known = match &self.inner.facts {
1952 Some((facts, scope)) => known_facts(facts.as_ref(), scope).await?,
1953 None => Vec::new(),
1954 };
1955 let plan = SitePlan::new(charter, &name);
1956 let staged = stage_release_one(
1957 &runtime,
1958 plan.items(charter, &known, &self.inner.jurisdictions),
1959 &self.steward(),
1960 )
1961 .await?;
1962 let held: Vec<String> = staged.held.iter().map(|id| id.0.clone()).collect();
1963 let summary = if held.is_empty() {
1964 format!(
1965 "{} pages built from {} confirmed fact{}.",
1966 staged.written.len(),
1967 known.len(),
1968 plural(known.len())
1969 )
1970 } else {
1971 format!(
1972 "{} pages built; {} held: {}",
1973 staged.written.len(),
1974 held.len(),
1975 staged.gate.summary()
1976 )
1977 };
1978 state.design = Some(choice);
1979 state.gate = None;
1980 state.built = Some(Built { held: held.clone(), summary: summary.clone() });
1981 if held.is_empty() {
1982 self.complete(&mut state, Stage::Build, None).await;
1983 }
1984 Ok(summary)
1985 }
1986
1987 async fn home_draft(&self) -> Result<adk_site::pipeline::Draft> {
1988 let runtime = self.runtime().await;
1989 let language = self.inner.languages.first().map_or("en", LanguageTag::as_str).to_string();
1990 let id = ContentId(format!(
1991 "{}/home/{language}",
1992 adk_site::content::kind_directory(awp_types::ContentKind::Page)
1993 ));
1994 let home = runtime.store().get(&id).await.map_err(site)?.ok_or_else(|| {
1995 invalid(
1996 "website.onboarding.order",
1997 "release 1 has no home page yet; choose a design first",
1998 )
1999 })?;
2000 let change = Change {
2001 items: vec![home],
2002 media: Vec::new(),
2003 entry: EntryPoint::SiteAgent { agent: self.steward() },
2004 proposer: self.steward(),
2005 job: crate::jobs::ONBOARDING.to_string(),
2006 action_class: "publish".into(),
2007 };
2008 runtime.pipeline().draft(change).await.map_err(site)
2009 }
2010
2011 async fn run_gate(&self) -> Result<()> {
2012 let mut state = self.inner.onboarding.lock().await;
2013 if state.built.is_none() {
2014 return Err(invalid(
2015 "website.onboarding.order",
2016 "choose a design first: release 1 is built from it",
2017 ));
2018 }
2019 let runtime = self.runtime().await;
2020 let report = runtime.run_launch_gate().await?;
2021 let draft = self.home_draft().await?;
2022 let preview = runtime.pipeline().preview(&draft).await.map_err(site)?;
2023 let name = state.name.clone().unwrap_or_else(|| self.inner.name.clone());
2024 let titles: BTreeMap<String, String> = self
2025 .inner
2026 .charter
2027 .lock()
2028 .await
2029 .committed
2030 .as_ref()
2031 .map(|version| {
2032 SitePlan::new(&version.charter, &name)
2033 .pages
2034 .into_iter()
2035 .map(|page| (page.slug, page.title))
2036 .collect()
2037 })
2038 .unwrap_or_default();
2039 let mut pages = Vec::new();
2040 for diff in preview.diff.iter().take(PREVIEW_PAGES_MAX) {
2041 let twin =
2042 diff.path.trim_start_matches('/').trim_end_matches(".html").to_string() + ".md";
2043 let markdown = tokio::fs::read_to_string(preview.staged.root.join(&twin))
2044 .await
2045 .ok()
2046 .map(|text| text.chars().take(PAGE_MARKDOWN_MAX).collect());
2047 let slug = slug_of(&diff.path);
2048 pages.push(PageView {
2049 title: match diff.path.as_str() {
2050 "/404.html" => "Page not found".to_string(),
2051 "/410.html" => "Page withdrawn".to_string(),
2052 path => titles.get(&slug).cloned().unwrap_or_else(|| path.to_string()),
2053 },
2054 path: diff.path.clone(),
2055 change: words::page_change(diff.change),
2056 markdown,
2057 });
2058 }
2059 pages.sort_by_key(|page| (page.path != "/index.html", page.path.clone()));
2060 let _ = tokio::fs::remove_dir_all(&preview.staged.root).await;
2061 let passed = report.passed();
2062 state.gate = Some((report, pages));
2063 if passed {
2064 self.complete(&mut state, Stage::LaunchGate, None).await;
2065 }
2066 Ok(())
2067 }
2068
2069 async fn go_live(&self) -> Result<String> {
2070 let mut state = self.inner.onboarding.lock().await;
2071 if !state.gate.as_ref().is_some_and(|(report, _)| report.passed()) {
2072 return Err(invalid("website.onboarding.order", "the launch check has to pass first"));
2073 }
2074 if state.live.is_some() || state.pending.is_some() {
2075 return Err(invalid("website.onboarding.order", "the launch is under way already"));
2076 }
2077 let draft = self.home_draft().await?;
2078 let step = self.release(draft, None).await?;
2079 Ok(self.launched(&mut state, step).await)
2080 }
2081
2082 async fn launched(&self, state: &mut State, step: ReleaseStep) -> String {
2084 match step {
2085 ReleaseStep::Live { seq } => {
2086 let at = self.now();
2087 state.live = Some((seq, at));
2088 if let Some(status) = &self.inner.status {
2089 let record = crate::incident::StatusRecord {
2090 state: awp_types::SiteState::Operational,
2091 since: at,
2092 reason: "launched".into(),
2093 release_seq: Some(seq),
2094 };
2095 if let Err(error) = status.set(self.inner.site.id, record).await {
2096 tracing::warn!(error = %error, "the site's status could not be set at launch");
2097 }
2098 }
2099 self.complete(state, Stage::ConnectAndDeploy, Some(seq)).await;
2100 self.complete(state, Stage::Run, Some(seq)).await;
2101 format!("The site is live: release {seq} is signed and published.")
2102 }
2103 ReleaseStep::Pending(next) => {
2104 state.pending = Some(*next);
2105 "The launch waits for every role of the publication chain.".into()
2106 }
2107 ReleaseStep::Held(summary) => format!("The launch is held: {summary}"),
2108 ReleaseStep::Frozen => {
2109 "The launch is approved, but the site is frozen: go live again once the freeze \
2110 lifts."
2111 .into()
2112 }
2113 ReleaseStep::Rejected { by, reason } => format!("{by} refused the launch: {reason}"),
2114 ReleaseStep::Scheduled { at } => format!("The launch is scheduled for {at}"),
2115 }
2116 }
2117}
2118
2119fn fact_words(text: &str) -> String {
2121 let Some((key, value)) = text.split_once(':') else { return text.to_string() };
2122 let key = key.trim();
2123 if key.is_empty() || key.contains(' ') {
2124 return text.to_string();
2125 }
2126 let label = match key {
2127 "type" | "@type" => "Kind of place".to_string(),
2128 other => {
2129 let mut words = String::new();
2130 for (index, c) in other.trim_start_matches('@').chars().enumerate() {
2131 if index == 0 {
2132 words.extend(c.to_uppercase());
2133 } else if c.is_uppercase() {
2134 words.push(' ');
2135 words.extend(c.to_lowercase());
2136 } else if c == '_' || c == '-' {
2137 words.push(' ');
2138 } else {
2139 words.push(c);
2140 }
2141 }
2142 words
2143 }
2144 };
2145 format!("{label}:{value}")
2146}
2147
2148fn plural(n: usize) -> &'static str {
2149 if n == 1 { "" } else { "s" }
2150}
2151
2152fn connection_kind(kind: ConnectionKind) -> &'static str {
2153 match kind {
2154 ConnectionKind::Domain => "Domain",
2155 ConnectionKind::Email => "Email",
2156 ConnectionKind::OwnerChannel => "Your channels",
2157 ConnectionKind::Analytics => "Analytics",
2158 ConnectionKind::Payment => "Payments",
2159 }
2160}
2161
2162fn connect_method(method: ConnectMethod) -> &'static str {
2163 match method {
2164 ConnectMethod::OAuth => "Through the service's own sign-in",
2165 ConnectMethod::Broker => "Through your credential broker",
2166 ConnectMethod::Pairing => "With a pairing code",
2167 }
2168}
2169
2170fn finding_words(kind: adk_site::migrate::detect::FindingKind) -> &'static str {
2171 use adk_site::migrate::detect::FindingKind;
2172 match kind {
2173 FindingKind::HiddenLinks => "Links hidden from visitors",
2174 FindingKind::SpamLinks => "Spam links",
2175 FindingKind::Cloaking => "Different content for search engines than for people",
2176 FindingKind::Executable => "A program uploaded as a file; it is never published",
2177 FindingKind::MimeMismatch => "A file that is not what its name says",
2178 FindingKind::ObfuscatedScript => "A disguised script",
2179 _ => "Something suspicious",
2180 }
2181}
2182
2183#[cfg(test)]
2184mod tests {
2185 use super::*;
2186
2187 #[test]
2190 fn alarms_offer_every_chat_platform() {
2191 let options = channel_options();
2192 for (id, label) in [("slack", "Slack"), ("discord", "Discord"), ("matrix", "Matrix")] {
2193 assert!(options.contains(&(id.to_string(), label.to_string())), "{id}");
2194 }
2195 for (id, _) in &options {
2196 assert!(!matches!(Channel::from(id.as_str()), Channel::Other(_)), "{id}");
2197 }
2198 }
2199
2200 #[test]
2201 fn discovered_keys_read_as_words() {
2202 assert_eq!(
2203 fact_words("openingHours: Mo-Sa 07:00-18:00"),
2204 "Opening hours: Mo-Sa 07:00-18:00"
2205 );
2206 assert_eq!(fact_words("type: LocalBusiness"), "Kind of place: LocalBusiness");
2207 assert_eq!(fact_words("Juniper Bakery: bread"), "Juniper Bakery: bread");
2208 }
2209
2210 #[test]
2211 fn page_slugs_come_from_their_files() {
2212 assert_eq!(slug_of("/index.html"), "home");
2213 assert_eq!(slug_of("/about/index.html"), "about");
2214 assert_eq!(slug_of("/sw/contact/index.html"), "contact");
2215 }
2216
2217 #[test]
2218 fn answers_state_facts_in_the_owners_words() {
2219 let values = FormValues::from([
2220 ("email".to_string(), "hello@juniper.example".to_string()),
2221 ("phone".to_string(), "+254 700 000 000".to_string()),
2222 ]);
2223 assert_eq!(answer_facts("contact", &values, "Juniper"), ["Telephone: +254 700 000 000"]);
2224 assert!(answer_facts("alarms", &values, "Juniper").is_empty(), "channels are not claims");
2225 }
2226
2227 #[test]
2228 fn hours_are_asked_only_of_places_people_visit() {
2229 let ids = |kind| forms(kind, "Site").into_iter().map(|f| f.id).collect::<Vec<_>>();
2230 assert!(ids(SiteKind::Business).contains(&"hours"));
2231 assert!(!ids(SiteKind::Personal).contains(&"hours"));
2232 }
2233}