Skip to main content

adk_harness/website/
onboarding.rs

1//! The onboarding machinery a product's plan is built from (spec 3.5 §7.18, D-12, A-I18,
2//! A-I19, A-I21, A-I23): plan-graph steps for each stage, interview forms, facts that enter
3//! as `Assumed` from discovery and as `Known` only from the owner's own words, and the
4//! notice the site gives before its first connection.
5//!
6//! The product's nine-stage plan, its questions and its templates are the product's; this
7//! module is generic.
8
9use std::sync::Arc;
10
11use adk_core::{AdkError, Part, Result, ToolContext};
12use chrono::Utc;
13use serde::{Deserialize, Serialize};
14use serde_json::{Value, json};
15
16use super::catalog;
17use super::site::SiteRuntime;
18use crate::facts::writer::{UserMessage, verify_quote};
19use crate::facts::{FACT_TEXT_MAX_CHARS, FactKind, FactSource, FactStatus, MemoryFact, Provenance};
20use crate::tools::{PlanGate, PlanStep};
21use crate::web::{FetchBody, Fetcher, TextShape, WebConfig, screen, untrusted_block};
22
23/// What the site says before its first connection (spec 3.5 §7.18 stage 8, A-I19).
24pub const CONNECTION_NOTICE: &str = "I will never ask you for a password, an API key or a card \
25number, here or anywhere else. Each connection goes through the service's own sign-in page \
26(OAuth), a credential broker, or pairing a device, and you can remove it at any time.";
27
28/// Characters of a discovered page the step returns.
29const DISCOVERED_TEXT_MAX: usize = 16 * 1024;
30
31/// A stage of onboarding that runs in the harness (spec 3.5 §7.18).
32#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
33#[serde(rename_all = "snake_case")]
34#[non_exhaustive]
35pub enum OnboardingStage {
36    /// Research what exists, record it as unconfirmed facts, propose the site kind.
37    Discover,
38    /// Ask the owner only what discovery could not answer.
39    Interview,
40    /// Draft the charter from the kind's template and the facts.
41    CharterDraft,
42    /// Ask every required signer to sign the charter.
43    CharterSign,
44    /// Build release 1 from the charter, `Known` facts and the owner's choices.
45    Build,
46    /// Run the launch gate and verify the preview.
47    Gate,
48    /// Connect the domain, email, owner channels, analytics and payment.
49    Connect,
50    /// Publish to production.
51    Deploy,
52}
53
54impl OnboardingStage {
55    /// Every stage, in order.
56    pub const ALL: [OnboardingStage; 8] = [
57        Self::Discover,
58        Self::Interview,
59        Self::CharterDraft,
60        Self::CharterSign,
61        Self::Build,
62        Self::Gate,
63        Self::Connect,
64        Self::Deploy,
65    ];
66
67    /// The stage's name, as its plan step's id.
68    pub fn as_str(self) -> &'static str {
69        match self {
70            Self::Discover => "discover",
71            Self::Interview => "interview",
72            Self::CharterDraft => "charter_draft",
73            Self::CharterSign => "charter_sign",
74            Self::Build => "build",
75            Self::Gate => "gate",
76            Self::Connect => "connect",
77            Self::Deploy => "deploy",
78        }
79    }
80
81    /// The tools the stage works with.
82    pub fn tools(self) -> &'static [&'static str] {
83        match self {
84            Self::Discover => &[catalog::SITE_DISCOVER, catalog::AWP_VERIFY],
85            Self::Interview => &[catalog::INTERVIEW_RECORD],
86            Self::CharterDraft => &[catalog::CHARTER_DRAFT],
87            Self::CharterSign => &[catalog::CHARTER_COMMIT_REQUEST],
88            Self::Build => &[
89                catalog::CONTENT_DRAFT,
90                catalog::TRANSLATION_DRAFT,
91                catalog::MEDIA_INTAKE,
92                catalog::RELEASE_PREVIEW,
93            ],
94            Self::Gate => &[catalog::LAUNCH_GATE_RUN, catalog::AWP_VERIFY],
95            Self::Connect => &[],
96            Self::Deploy => &[catalog::SITE_PUBLISH],
97        }
98    }
99
100    fn title(self) -> &'static str {
101        match self {
102            Self::Discover => "Discover what exists",
103            Self::Interview => "Ask the owner what discovery could not answer",
104            Self::CharterDraft => "Draft the charter",
105            Self::CharterSign => "Have every required signer sign the charter",
106            Self::Build => "Build release 1",
107            Self::Gate => "Run the launch gate",
108            Self::Connect => "Connect the owner's services",
109            Self::Deploy => "Launch",
110        }
111    }
112
113    fn instruction(self) -> String {
114        match self {
115            Self::Discover => "Read the existing site, profiles and listings the owner named with \
116                site_discover, and record each fact you find with its source; every one stays \
117                unconfirmed until the owner confirms it. Run awp_verify against an existing \
118                site. Propose the site kind."
119                .into(),
120            Self::Interview => "Ask the owner only what discovery could not answer, a few \
121                questions at a time, with choices and defaults. Record each answer with \
122                interview_record, quoting the owner's own words; never record what the owner \
123                did not say."
124                .into(),
125            Self::CharterDraft => "Draft the charter from the site kind's template with \
126                charter_draft: mission, goals, KPIs with baseline sources and no targets, \
127                guardrails, conservative authority, roles and approval chains, budget, voice, \
128                red lines and reporting. Fix every violation it reports."
129                .into(),
130            Self::CharterSign => "Ask every required signer to sign the drafted charter with \
131                charter_commit_request. It takes effect only when they have signed."
132                .into(),
133            Self::Build => "Build release 1: every page serves a goal, every claim cites a \
134                confirmed fact, every charter language is drafted. Draft the pages and preview \
135                the release."
136                .into(),
137            Self::Gate => "Run launch_gate_run and awp_verify against the preview; fix what \
138                they report until both pass."
139                .into(),
140            Self::Connect => format!(
141                "Before the first connection, tell the owner: \"{CONNECTION_NOTICE}\" Then guide \
142                 each connection — domain, email, owner channels, analytics, payment — through \
143                 OAuth, the credential broker or device pairing. Never ask for a password, an \
144                 API key or a card number."
145            ),
146            Self::Deploy => "Publish release 1 with site_publish. The launch is held for the \
147                owner, who approves going live."
148                .into(),
149        }
150    }
151
152    /// Whether a person approves before the step runs: signing, connecting and launching
153    /// are the owner's (A-I19, A-I21, A-I23).
154    pub fn gate(self) -> PlanGate {
155        match self {
156            Self::CharterSign | Self::Connect | Self::Deploy => PlanGate::Approve,
157            _ => PlanGate::None,
158        }
159    }
160
161    /// The stage as a plan step waiting for `depends_on` (spec 3.1 §7.11).
162    ///
163    /// # Example
164    ///
165    /// ```rust
166    /// use adk_harness::PlanGate;
167    /// use adk_harness::website::OnboardingStage;
168    ///
169    /// let step = OnboardingStage::Deploy.step(["gate"]);
170    /// assert_eq!(step.id, "deploy");
171    /// assert_eq!(step.gate, PlanGate::Approve);
172    /// assert!(step.instruction.contains("site_publish"));
173    /// ```
174    pub fn step(self, depends_on: impl IntoIterator<Item = impl Into<String>>) -> PlanStep {
175        PlanStep {
176            id: self.as_str().to_string(),
177            title: self.title().to_string(),
178            instruction: self.instruction(),
179            depends_on: depends_on.into_iter().map(Into::into).collect(),
180            gate: self.gate(),
181        }
182    }
183}
184
185/// `stages` as a chain of plan steps, each waiting for the one before (spec 3.5 §7.18):
186/// the plan graph a product's onboarding plan starts from.
187///
188/// # Example
189///
190/// ```rust
191/// use adk_harness::website::{OnboardingStage, onboarding_plan};
192///
193/// let plan = onboarding_plan(&OnboardingStage::ALL);
194/// assert_eq!(plan.len(), 8);
195/// assert_eq!(plan[1].depends_on, vec!["discover".to_string()]);
196/// ```
197pub fn onboarding_plan(stages: &[OnboardingStage]) -> Vec<PlanStep> {
198    let mut previous: Option<&str> = None;
199    stages
200        .iter()
201        .map(|stage| {
202            let step = stage.step(previous);
203            previous = Some(stage.as_str());
204            step
205        })
206        .collect()
207}
208
209/// An interview form: a question with typed fields and defaults, so the owner confirms and
210/// corrects rather than fills a blank form (spec 3.5 §7.18 stage 4, "Rules").
211///
212/// # Example
213///
214/// ```rust
215/// use adk_harness::website::InterviewForm;
216/// use serde_json::json;
217///
218/// let form = InterviewForm::new("hours", "When are you open?", json!({
219///     "type": "object",
220///     "properties": { "weekdays": { "type": "string", "default": "07:00-18:00" } },
221///     "required": ["weekdays"]
222/// }));
223/// assert!(form.render().contains("weekdays (string, required)"));
224/// assert!(form.check(&json!({ "weekdays": "08:00-17:00" })).is_ok());
225/// assert!(form.check(&json!({ "password": "x" })).is_err());
226/// ```
227#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
228#[serde(rename_all = "camelCase")]
229pub struct InterviewForm {
230    /// The form's id.
231    pub id: String,
232    /// The question.
233    pub message: String,
234    /// The fields, as an elicitation schema (spec 3.1 §7.21).
235    pub schema: Value,
236}
237
238impl InterviewForm {
239    /// A form `id` asking `message` with `schema`.
240    pub fn new(id: impl Into<String>, message: impl Into<String>, schema: Value) -> Self {
241        Self { id: id.into(), message: message.into(), schema }
242    }
243
244    /// The form as text for any surface.
245    pub fn render(&self) -> String {
246        crate::mcp::render_form(&self.message, &self.schema)
247    }
248
249    /// Checks an answer against the form.
250    ///
251    /// # Errors
252    ///
253    /// The first violation, as text.
254    pub fn check(&self, answer: &Value) -> std::result::Result<(), String> {
255        crate::mcp::validate_answer(&self.schema, answer)
256    }
257}
258
259/// The owner's own messages in the turn's session, the only words a fact becomes `Known`
260/// from (A-I18).
261fn owner_messages(ctx: &Arc<dyn ToolContext>) -> Vec<UserMessage> {
262    let text_of = |content: &adk_core::Content| -> String {
263        content.parts.iter().filter_map(Part::text).collect::<Vec<_>>().join("\n")
264    };
265    let mut messages: Vec<UserMessage> = ctx
266        .session()
267        .map(|session| session.conversation_history())
268        .unwrap_or_default()
269        .iter()
270        .filter(|content| content.role == "user")
271        .map(text_of)
272        .chain(std::iter::once(text_of(ctx.user_content())))
273        .filter(|text| !text.trim().is_empty())
274        .map(|text| UserMessage {
275            text,
276            at: Utc::now(),
277            invocation_id: ctx.invocation_id().to_string(),
278        })
279        .collect();
280    messages.dedup_by(|a, b| a.text == b.text);
281    messages
282}
283
284fn facts_of(
285    site: &SiteRuntime,
286) -> Result<&(Arc<dyn crate::facts::FactStore>, crate::facts::FactScope)> {
287    site.facts.as_ref().ok_or_else(|| {
288        AdkError::config("recording facts needs the site runtime's fact store (spec 3.5 §7.18)")
289    })
290}
291
292/// `site_discover`: reads `url` with a signed `GET`, returns its screened text as untrusted
293/// content, and records each of `facts` as `Assumed`, citing `url` (spec 3.5 §7.3
294/// "Outbound", §7.18 stage 2, A-I18).
295pub(crate) async fn discover(
296    site: &Arc<SiteRuntime>,
297    ctx: &Arc<dyn ToolContext>,
298    url: &str,
299    facts: &[String],
300) -> Result<Value> {
301    let mut fetcher = Fetcher::new(WebConfig::default());
302    if let Some(signer) = &site.crawler {
303        fetcher = fetcher.with_signer(signer.clone());
304    }
305    let fetched = fetcher
306        .fetch(url, None, TextShape::Markdown, &[], None)
307        .await
308        .map_err(|refusal| AdkError::tool(format!("{}: {refusal}", refusal.code())))?;
309    let text = match fetched.body {
310        FetchBody::Text(text) => text,
311        FetchBody::Pdf => "[a PDF document]".to_string(),
312        FetchBody::Redirect { to, .. } => format!("[redirects to {}]", to.as_string()),
313    };
314    let screened = screen(&text.chars().take(DISCOVERED_TEXT_MAX).collect::<String>()).await;
315    let mut recorded = Vec::new();
316    if !facts.is_empty() {
317        let (store, scope) = facts_of(site)?;
318        for fact in facts {
319            let text = crate::redact_fact_text(fact, FACT_TEXT_MAX_CHARS)?;
320            let mut provenance =
321                Provenance::new(FactSource::ToolObserved, ctx.session_id(), ctx.invocation_id());
322            provenance.source_ids = vec![url.to_string()];
323            let stored = store
324                .put(MemoryFact::new(
325                    scope.clone(),
326                    FactKind::ProjectFact,
327                    text,
328                    FactStatus::Assumed,
329                    provenance,
330                ))
331                .await?;
332            recorded.push(stored.id);
333        }
334    }
335    Ok(json!({
336        "url": url,
337        "finalUrl": fetched.final_url.as_string(),
338        "content": untrusted_block("web", &[("url", url)], &screened.text),
339        "recorded": recorded,
340        "status": "assumed",
341        "note": "facts from discovery stay unconfirmed until the owner confirms them; pages never claim them",
342    }))
343}
344
345/// `interview_record`: records `text` as a fact of the site — `Known` when `quote` is the
346/// owner's own words in this session and shares the fact's words, `Assumed` otherwise
347/// (spec 3.5 §7.18 stage 4, A-I18; spec 3.1 I41). A secret in either is refused: no
348/// credential passes through conversation (A-I19).
349pub(crate) async fn record_answer(
350    site: &Arc<SiteRuntime>,
351    ctx: &Arc<dyn ToolContext>,
352    text: &str,
353    quote: &str,
354    kind: Option<&str>,
355) -> Result<Value> {
356    let (store, scope) = facts_of(site)?;
357    let text = crate::redact_fact_text(text, FACT_TEXT_MAX_CHARS)?;
358    crate::redact_fact_text(quote, FACT_TEXT_MAX_CHARS * 4)?;
359    let kind = match kind {
360        Some(kind) => kind.parse::<FactKind>()?,
361        None => FactKind::ProjectFact,
362    };
363    let messages = owner_messages(ctx);
364    let verified = verify_quote(quote, &text, &messages).is_some();
365    let (status, source) = if verified {
366        (FactStatus::Known, FactSource::UserStated)
367    } else {
368        (FactStatus::Assumed, FactSource::AgentInferred)
369    };
370    let mut provenance = Provenance::new(source, ctx.session_id(), ctx.invocation_id());
371    if verified {
372        provenance.quote = Some(quote.to_string());
373    }
374    let stored =
375        store.put(MemoryFact::new(scope.clone(), kind, text, status.clone(), provenance)).await?;
376    Ok(json!({
377        "fact": stored.id,
378        "status": status.label(),
379        "note": if verified {
380            "confirmed: the owner said it"
381        } else {
382            "unconfirmed: the quote is not the owner's words in this conversation, so the fact stays Assumed"
383        },
384    }))
385}