1use 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
23pub 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
28const DISCOVERED_TEXT_MAX: usize = 16 * 1024;
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
33#[serde(rename_all = "snake_case")]
34#[non_exhaustive]
35pub enum OnboardingStage {
36 Discover,
38 Interview,
40 CharterDraft,
42 CharterSign,
44 Build,
46 Gate,
48 Connect,
50 Deploy,
52}
53
54impl OnboardingStage {
55 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 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 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 pub fn gate(self) -> PlanGate {
155 match self {
156 Self::CharterSign | Self::Connect | Self::Deploy => PlanGate::Approve,
157 _ => PlanGate::None,
158 }
159 }
160
161 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
185pub 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
228#[serde(rename_all = "camelCase")]
229pub struct InterviewForm {
230 pub id: String,
232 pub message: String,
234 pub schema: Value,
236}
237
238impl InterviewForm {
239 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 pub fn render(&self) -> String {
246 crate::mcp::render_form(&self.message, &self.schema)
247 }
248
249 pub fn check(&self, answer: &Value) -> std::result::Result<(), String> {
255 crate::mcp::validate_answer(&self.schema, answer)
256 }
257}
258
259fn 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
292pub(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
345pub(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}