Skip to main content

gemini_adk_fluent_rs/
conversation.rs

1//! The conversation compiler (Phase 1 MVP).
2//!
3//! Authors describe a voice experience in terms of **stages** that *say* things,
4//! *collect* slots, *commit* tools behind confirmation, and advance via *next*
5//! transitions. A [`Conversation`] builder produces a serializable
6//! [`ConversationSpec`] (the single source of truth), and [`Conversation::compile`]
7//! lowers it to the governed [`CompiledFlow`] IR — so the high level is sugar over
8//! the low level, never a parallel runtime (see
9//! `docs/plans/2026-06-06-conversation-compiler-rfc.md`).
10//!
11//! ```no_run
12//! # use gemini_adk_fluent_rs::prelude::*;
13//! # use gemini_adk_fluent_rs::conversation::Conversation;
14//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
15//! let convo = Conversation::new("booking")
16//!     .stage("collect")
17//!         .instruction("Help the user book a table.")
18//!         .collect(["party_size", "slot"])
19//!         .next("check", Guard::captured(["party_size", "slot"]))
20//!     .stage("check")
21//!         .ground("Party of {party_size} at {slot}.")
22//!         .next("confirm", Guard::is_true("availability_ok"))
23//!     .stage("confirm")
24//!         .commit("book", Guard::is_true("user_confirmed"))
25//!         .next("done", Guard::called_ok("book"))
26//!     .stage("done").terminal()
27//!     .require(["done"])
28//!     .compile()?;
29//! let mut monitor = convo.monitor(Enforcement::Enforce);
30//! # let _ = &mut monitor; Ok(())
31//! # }
32//! ```
33//!
34//! ### Lowering semantics (MVP)
35//!
36//! - A stage lowers to a Flow [`Step`](gemini_adk_rs::flow). `say` → posture,
37//!   `ground` → grounding template, `allow` → tool whitelist.
38//! - `commit(tool, when)` gates a confirm-before-act tool (`tool` is auto-allowed
39//!   in the stage).
40//! - `next(to, when)` adds a forward edge: `to` depends on this stage (`after`)
41//!   and its activation gate is `when`. Multiple incoming edges are an **AND-join**
42//!   (all predecessors must complete) — richer topologies are Phase 3.
43//! - A non-terminal stage's completion is, in priority order: an explicit
44//!   `done`, else `captured(collect)` when it collects slots, else the disjunction
45//!   of its `next` conditions.
46
47use serde::{Deserialize, Serialize};
48use serde_json::Value;
49use std::collections::{BTreeMap, BTreeSet};
50use std::future::Future;
51use std::pin::Pin;
52use std::sync::Arc;
53use std::time::Duration;
54
55use gemini_adk_rs::extract::Extract;
56use gemini_adk_rs::flow::{CompiledFlow, Enforcement, Flow, FlowErrors, FlowMonitor, Guard, Pred};
57use gemini_adk_rs::frame::{Frame, FrameSpec};
58
59/// A boxed async fetcher: bind args (a JSON object) → resolved value.
60type SlotFetch =
61    Arc<dyn Fn(Value) -> Pin<Box<dyn Future<Output = Result<Value, String>> + Send>> + Send + Sync>;
62
63/// A registry of named async resolvers, bound to a [`ConversationSpec`]'s
64/// declared resolver slots at load time via
65/// [`Conversation::from_spec_with_resolvers`].
66///
67/// This is what makes a JSON spec a complete deployable unit: the spec carries
68/// the *declarations* (slot, resolver name, args, ttl) and the registry supplies
69/// the *implementations*.
70///
71/// ```no_run
72/// # use gemini_adk_fluent_rs::conversation::{Conversation, ConversationSpec, ResolverRegistry};
73/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
74/// # let spec = ConversationSpec::default();
75/// let registry = ResolverRegistry::new()
76///     .with("availability", |args| async move {
77///         let _ = args;
78///         Ok(serde_json::json!({ "open": true }))
79///     });
80/// let convo = Conversation::from_spec_with_resolvers(spec, &registry)?;
81/// # let _ = convo; Ok(())
82/// # }
83/// ```
84#[derive(Clone, Default)]
85pub struct ResolverRegistry {
86    fetchers: BTreeMap<String, SlotFetch>,
87}
88
89impl ResolverRegistry {
90    /// An empty registry.
91    pub fn new() -> Self {
92        Self::default()
93    }
94
95    /// Register an async resolver under `name` (builder style).
96    pub fn with<F, Fut>(mut self, name: impl Into<String>, fetch: F) -> Self
97    where
98        F: Fn(Value) -> Fut + Send + Sync + 'static,
99        Fut: Future<Output = Result<Value, String>> + Send + 'static,
100    {
101        self.add(name, fetch);
102        self
103    }
104
105    /// Register an async resolver under `name`.
106    pub fn add<F, Fut>(&mut self, name: impl Into<String>, fetch: F)
107    where
108        F: Fn(Value) -> Fut + Send + Sync + 'static,
109        Fut: Future<Output = Result<Value, String>> + Send + 'static,
110    {
111        let fetch = Arc::new(fetch);
112        self.fetchers.insert(
113            name.into(),
114            Arc::new(move |v| {
115                let fetch = fetch.clone();
116                Box::pin(async move { fetch(v).await })
117            }),
118        );
119    }
120
121    /// Whether a resolver named `name` is registered.
122    pub fn contains(&self, name: &str) -> bool {
123        self.fetchers.contains_key(name)
124    }
125
126    /// A registry that stubs every resolver declared anywhere in `spec` (stages
127    /// and overlays) with a no-op returning JSON `null`.
128    ///
129    /// For **structural validation and deterministic simulation**, the resolver
130    /// *implementations* are irrelevant — a resolver is an external fetch, so in
131    /// a model-free test its output is supplied via a scenario `set` step (like
132    /// a tool result via `tool_ok`), and the stub is never actually invoked when
133    /// the slot is pre-set. Real implementations bind at deploy time via
134    /// [`Conversation::from_spec_with_resolvers`].
135    pub fn stubbing(spec: &ConversationSpec) -> Self {
136        let mut reg = Self::new();
137        let stages = spec
138            .stages
139            .iter()
140            .chain(spec.overlays.iter().flat_map(|o| o.stages.iter()));
141        for stage in stages {
142            for r in &stage.resolve {
143                let name = r.resolver_name().to_string();
144                if !reg.contains(&name) {
145                    reg.add(name, |_args| async { Ok(serde_json::Value::Null) });
146                }
147            }
148        }
149        reg
150    }
151
152    fn get(&self, name: &str) -> Option<SlotFetch> {
153        self.fetchers.get(name).cloned()
154    }
155}
156
157/// A resolver binding attached to a stage by [`Conversation::resolve_slot`]. The
158/// closure lives only in the builder (it is not serializable); the serializable
159/// [`ConversationSpec`] is unaffected.
160#[derive(Clone)]
161struct StageResolver {
162    stage: String,
163    name: String,
164    args: Vec<String>,
165    ttl: Option<Duration>,
166    fetch: SlotFetch,
167}
168
169/// A serializable declaration that a slot is filled by a *named* async resolver.
170///
171/// The resolver's implementation (the async fetch) is bound at load time from a
172/// [`ResolverRegistry`] — so a `ConversationSpec` carrying these is a complete,
173/// JSON-deployable unit once paired with a registry. This is the data half of
174/// [`Conversation::resolve_slot`]; the closure half lives only in the builder.
175#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
176pub struct ResolveSpec {
177    /// The slot (state key) the resolver fills. Added to the stage's `collect`.
178    pub slot: String,
179    /// The registered resolver name to bind (defaults to `slot` if omitted).
180    #[serde(default, skip_serializing_if = "Option::is_none")]
181    pub resolver: Option<String>,
182    /// State keys passed to the resolver as a JSON object argument.
183    #[serde(default, skip_serializing_if = "Vec::is_empty")]
184    pub args: Vec<String>,
185    /// Optional memoization TTL in seconds.
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub ttl_secs: Option<u64>,
188}
189
190impl ResolveSpec {
191    /// The resolver name to look up in the registry (the explicit `resolver`, or
192    /// the slot name as a default).
193    fn resolver_name(&self) -> &str {
194        self.resolver.as_deref().unwrap_or(&self.slot)
195    }
196}
197
198/// A transition: advance to `to` when `when` holds.
199#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
200pub struct TransitionSpec {
201    /// Target stage id.
202    pub to: String,
203    /// The (serializable) guard that fires this transition.
204    pub when: Guard,
205}
206
207/// A confirm-before-act tool, gated by `when`.
208#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
209pub struct CommitSpec {
210    /// The committing tool (e.g. `book`, `charge_card`).
211    pub tool: String,
212    /// The guard that must hold before the tool is admitted.
213    pub when: Guard,
214}
215
216/// One authored conversation stage.
217#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
218pub struct StageSpec {
219    /// Stage id, unique across the main flow and every overlay.
220    pub id: String,
221    /// Instruction projected as steering while the stage is active. Serialized
222    /// as `say` for compatibility; `instruction` is accepted on input.
223    #[serde(
224        default,
225        alias = "instruction",
226        skip_serializing_if = "Option::is_none"
227    )]
228    pub say: Option<String>,
229    /// Grounding template projected while active (`{key}` interpolation).
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub ground: Option<String>,
232    /// Slots to collect; drives the default completion (`captured`).
233    #[serde(default, skip_serializing_if = "Vec::is_empty")]
234    pub collect: Vec<String>,
235    /// The frame whose slots this stage collects, if set via `collect_frame`. Its
236    /// recognizer-bearing slots lower to an extractor that fills the slots.
237    #[serde(default, skip_serializing_if = "Option::is_none")]
238    pub frame: Option<FrameSpec>,
239    /// Tools available while this stage is active.
240    #[serde(default, skip_serializing_if = "Vec::is_empty")]
241    pub allow: Vec<String>,
242    /// Explicit completion guard (overrides the `collect`/`next` default).
243    #[serde(default, skip_serializing_if = "Option::is_none")]
244    pub done: Option<Guard>,
245    /// A confirm-before-act tool committed in this stage.
246    #[serde(default, skip_serializing_if = "Option::is_none")]
247    pub commit: Option<CommitSpec>,
248    /// Forward transitions out of this stage.
249    #[serde(default, skip_serializing_if = "Vec::is_empty")]
250    pub next: Vec<TransitionSpec>,
251    /// Explicit dependency stage ids (in addition to `next`-derived edges).
252    #[serde(default, skip_serializing_if = "Vec::is_empty")]
253    pub after: Vec<String>,
254    /// Whether this is a terminal stage.
255    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
256    pub terminal: bool,
257    /// Repair policy for this stage (reprompt/escalate on stalling).
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub repair: Option<RepairPolicy>,
260    /// Voice pacing while this stage is active: reprompt on silence, filler
261    /// cues for slow tools, holding the floor, endpointing, context delivery.
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub timing: Option<VoiceTiming>,
264    /// Text the model must say word for word in this stage (strict canned
265    /// mode). The stage completes only once the output transcript matches it;
266    /// see [`gemini_adk_rs::flow::verbatim`]. The model holds the floor
267    /// unless `timing` says otherwise.
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub verbatim: Option<String>,
270    /// Named-resolver slot declarations. Bound to implementations at load via a
271    /// [`ResolverRegistry`]; the data lives in the spec so it round-trips JSON.
272    #[serde(default, skip_serializing_if = "Vec::is_empty")]
273    pub resolve: Vec<ResolveSpec>,
274}
275
276// The digression/repair vocabulary is owned by the runtime: the authoring layer
277// lowers into it and never reimplements it. Re-exported here so existing
278// `conversation::{Resume, RepairPolicy, FlowStack}` paths keep working.
279pub use gemini_adk_rs::flow::{FlowStack, RepairPolicy, Resume, VoiceTiming};
280use gemini_adk_rs::flow::{Overlay, correction_flag, escalate_flag, verbatim_flag};
281
282/// A digression (overlay): a named sub-flow that suspends the main flow when its
283/// `trigger` holds, runs to completion, then resumes per `resume`.
284#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
285pub struct OverlaySpec {
286    /// Overlay name, unique across the conversation. The safety-handoff policy
287    /// generates an overlay named `safety`.
288    pub name: String,
289    /// The guard that activates this overlay (e.g. an `intent:*` flag).
290    pub trigger: Guard,
291    /// The overlay's own stages.
292    #[serde(default)]
293    pub stages: Vec<StageSpec>,
294    /// Stages required for the overlay to be considered complete.
295    #[serde(default, skip_serializing_if = "Vec::is_empty")]
296    pub require: Vec<String>,
297    /// What the main flow does once the overlay completes.
298    #[serde(default)]
299    pub resume: Resume,
300}
301
302/// The serializable authoring spec — the single source of truth from which the
303/// typed builder, YAML, and (later) codegen all derive.
304#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
305pub struct ConversationSpec {
306    /// Conversation name.
307    pub name: String,
308    /// The authored stages.
309    #[serde(default)]
310    pub stages: Vec<StageSpec>,
311    /// Stages that must be done for the conversation to be complete.
312    #[serde(default, skip_serializing_if = "Vec::is_empty")]
313    pub require: Vec<String>,
314    /// Digressions/overlays that can suspend and resume the main flow.
315    #[serde(default, skip_serializing_if = "Vec::is_empty")]
316    pub overlays: Vec<OverlaySpec>,
317    /// Cross-cutting policy aspects (safety/redaction/commit governance).
318    #[serde(default, skip_serializing_if = "Vec::is_empty")]
319    pub policies: Vec<crate::policy::Policy>,
320}
321
322/// Error compiling a [`ConversationSpec`] into a [`CompiledConversation`].
323#[derive(Debug)]
324pub enum ConversationError {
325    /// The spec has no stages.
326    Empty,
327    /// An authoring-level error (e.g. a transition to an unknown stage).
328    Spec(String),
329    /// The lowered flow failed referential/acyclicity validation.
330    Flow(Vec<String>),
331    /// The lowered flow failed to compile (unreachable steps, unguarded commit…).
332    Compile(FlowErrors),
333}
334
335impl std::fmt::Display for ConversationError {
336    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
337        match self {
338            ConversationError::Empty => write!(f, "conversation has no stages"),
339            ConversationError::Spec(m) => write!(f, "conversation spec error: {m}"),
340            ConversationError::Flow(errs) => {
341                write!(f, "lowered flow is invalid: {}", errs.join("; "))
342            }
343            ConversationError::Compile(e) => write!(f, "lowered flow failed to compile: {e}"),
344        }
345    }
346}
347
348impl std::error::Error for ConversationError {}
349
350/// The JSON Schema for a [`ConversationSpec`], as a pretty-printed string.
351///
352/// This is the machine-readable authoring contract: a web form, an IDE, or an
353/// LLM/skill drafting a spec targets this schema. Generated from the same
354/// `#[derive(JsonSchema)]` types the runtime compiles, so it cannot drift.
355pub fn conversation_spec_schema() -> String {
356    let schema = schemars::schema_for!(ConversationSpec);
357    serde_json::to_string_pretty(&schema).expect("schema serialization is infallible")
358}
359
360impl serde::Serialize for ConversationError {
361    /// A machine-readable diagnostic so authoring tools (web/CLI/skills) can
362    /// render structured errors. Shape:
363    /// `{ "kind": "compile", "errors": [ { "kind": "unreachable_step", ... } ] }`.
364    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
365        use serde::ser::SerializeMap;
366        let mut m = s.serialize_map(None)?;
367        m.serialize_entry("message", &self.to_string())?;
368        match self {
369            ConversationError::Empty => {
370                m.serialize_entry("kind", "empty")?;
371            }
372            ConversationError::Spec(msg) => {
373                m.serialize_entry("kind", "spec")?;
374                m.serialize_entry("detail", msg)?;
375            }
376            ConversationError::Flow(errs) => {
377                m.serialize_entry("kind", "flow")?;
378                m.serialize_entry("errors", errs)?;
379            }
380            ConversationError::Compile(e) => {
381                m.serialize_entry("kind", "compile")?;
382                m.serialize_entry("errors", &e.0)?;
383            }
384        }
385        m.end()
386    }
387}
388
389/// A compiled digression: its trigger, lowered flow, extractors, and resume policy.
390#[derive(Clone)]
391pub struct CompiledOverlay {
392    /// Overlay name.
393    pub name: String,
394    /// Guard that activates the overlay.
395    pub trigger: Guard,
396    /// The overlay's lowered governance flow.
397    pub flow: CompiledFlow,
398    /// Extractors that fill the overlay's frame slots.
399    pub extractors: Vec<Extract>,
400    /// What the main flow does once this overlay completes.
401    pub resume: Resume,
402}
403
404impl CompiledOverlay {
405    /// The runtime [`Overlay`] this digression installs: trigger, governed flow
406    /// and resume policy. Extractors are registered separately (see
407    /// [`CompiledConversation::all_extractors`]).
408    pub fn to_runtime(&self) -> Overlay {
409        Overlay::new(
410            self.name.clone(),
411            self.trigger.clone(),
412            self.flow.clone(),
413            self.resume,
414        )
415    }
416}
417
418/// A compiled conversation: the validated main [`CompiledFlow`], the extractors
419/// that fill its frames' slots, any digressions, and the source spec.
420#[derive(Clone)]
421pub struct CompiledConversation {
422    flow: CompiledFlow,
423    extractors: Vec<Extract>,
424    overlays: Vec<CompiledOverlay>,
425    repair: BTreeMap<String, RepairPolicy>,
426    timing: BTreeMap<String, VoiceTiming>,
427    corrections: BTreeMap<String, Vec<String>>,
428    verbatim: BTreeMap<String, String>,
429    policies: Vec<crate::policy::Policy>,
430    spec: ConversationSpec,
431}
432
433// Manual: the lowered `Extract`s hold recognizer/resolver closures (not `Debug`),
434// so they are summarized by count.
435impl std::fmt::Debug for CompiledConversation {
436    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
437        f.debug_struct("CompiledConversation")
438            .field("flow", &self.flow)
439            .field("extractors", &self.extractors.len())
440            .field("overlays", &self.overlays.len())
441            .field("policies", &self.policies)
442            .field("spec", &self.spec)
443            .finish()
444    }
445}
446
447impl CompiledConversation {
448    /// The governed flow IR this conversation lowered to.
449    pub fn flow(&self) -> &CompiledFlow {
450        &self.flow
451    }
452    /// The extractors lowered from `collect_frame` stages — register these on the
453    /// live session so each turn fills the frames' slots from the transcript.
454    pub fn extractors(&self) -> &[Extract] {
455        &self.extractors
456    }
457    /// The compiled digressions/overlays.
458    pub fn overlays(&self) -> &[CompiledOverlay] {
459        &self.overlays
460    }
461    /// The cross-cutting policy aspects attached to this conversation.
462    pub fn policies(&self) -> &[crate::policy::Policy] {
463        &self.policies
464    }
465    /// The set of state keys marked for redaction by `Policy::redact`.
466    pub fn redacted_fields(&self) -> BTreeSet<String> {
467        self.policies
468            .iter()
469            .flat_map(|p| p.redacted_keys().iter().cloned())
470            .collect()
471    }
472    /// Every extractor (main + overlays) — what [`Live::converse`](crate::live::Live)
473    /// registers so slots fill whether the main flow or a digression is active.
474    pub fn all_extractors(&self) -> Vec<Extract> {
475        let mut all = self.extractors.clone();
476        for ov in &self.overlays {
477            all.extend(ov.extractors.iter().cloned());
478        }
479        all
480    }
481    /// Build the runtime [`FlowStack`] — the main flow plus its digressions and
482    /// repair policies, with push-on-trigger / resume-on-completion.
483    ///
484    /// This is the artifact every execution path drives: the simulator
485    /// ([`Sim`](crate::simulation::Sim)) and a live session
486    /// ([`Live::converse`](crate::live::Live::converse)) both install exactly
487    /// this stack, so what a definition does is the same in each.
488    pub fn stack(&self, mode: Enforcement) -> FlowStack {
489        FlowStack::new(self.flow.clone(), mode)
490            .with_overlays(self.overlays.iter().map(CompiledOverlay::to_runtime))
491            .with_repairs(self.repair.clone())
492            .with_timings(self.timing.clone())
493            .with_corrections(self.corrections.clone())
494            .with_verbatims(self.verbatim.clone())
495    }
496    /// The per-stage repair policies the runtime applies to the main flow.
497    pub fn repair_policies(&self) -> &BTreeMap<String, RepairPolicy> {
498        &self.repair
499    }
500    /// The stages that must say their text word for word, keyed by stage id.
501    pub fn verbatim_policies(&self) -> &BTreeMap<String, String> {
502        &self.verbatim
503    }
504    /// The slots whose correction re-opens later stages, each with the state
505    /// keys the correction clears (see
506    /// [`FlowStack::with_correction`](gemini_adk_rs::flow::FlowStack::with_correction)).
507    pub fn correction_policies(&self) -> &BTreeMap<String, Vec<String>> {
508        &self.corrections
509    }
510    /// The per-stage voice timing, main flow and digressions, keyed by
511    /// stage id.
512    pub fn timing_policies(&self) -> &BTreeMap<String, VoiceTiming> {
513        &self.timing
514    }
515    /// The authoring spec it was compiled from.
516    pub fn spec(&self) -> &ConversationSpec {
517        &self.spec
518    }
519    /// Render the lowered flow as a Mermaid diagram.
520    pub fn to_mermaid(&self) -> String {
521        self.flow.to_mermaid()
522    }
523    /// Build a [`FlowMonitor`] over the lowered flow.
524    pub fn monitor(&self, mode: Enforcement) -> FlowMonitor {
525        FlowMonitor::compiled(self.flow.clone(), mode)
526    }
527}
528
529/// Fluent builder that produces a [`ConversationSpec`]; sugar over the spec.
530///
531/// (Not `Debug`: [`resolve_slot`](Conversation::resolve_slot) bindings hold async
532/// closures. The serializable [`ConversationSpec`] is `Debug` via [`spec`](Conversation::spec).)
533#[derive(Clone, Default)]
534pub struct Conversation {
535    spec: ConversationSpec,
536    resolvers: Vec<StageResolver>,
537    /// When `Some(i)`, stage setters target `spec.overlays[i]` instead of the main
538    /// flow (between `.overlay(..)` and `.end_overlay()`).
539    current_overlay: Option<usize>,
540    /// Builder misuse found while chaining, reported by [`compile`](Self::compile).
541    issues: Vec<String>,
542}
543
544impl Conversation {
545    /// Start a new conversation.
546    pub fn new(name: impl Into<String>) -> Self {
547        Self {
548            spec: ConversationSpec {
549                name: name.into(),
550                ..Default::default()
551            },
552            resolvers: Vec::new(),
553            current_overlay: None,
554            issues: Vec::new(),
555        }
556    }
557
558    /// Begin authoring a new stage; subsequent setters apply to it. Routes to the
559    /// active overlay when between `.overlay(..)` and `.end_overlay()`.
560    pub fn stage(mut self, id: impl Into<String>) -> Self {
561        let stage = StageSpec {
562            id: id.into(),
563            ..Default::default()
564        };
565        match self.current_overlay {
566            Some(i) => self.spec.overlays[i].stages.push(stage),
567            None => self.spec.stages.push(stage),
568        }
569        self
570    }
571
572    /// Begin authoring a digression/overlay; subsequent `.stage(..)` calls (until
573    /// `.end_overlay()`) populate it. Set its activation guard with `.trigger(..)`
574    /// (an overlay with no trigger never fires — fail-closed).
575    pub fn overlay(mut self, name: impl Into<String>) -> Self {
576        self.spec.overlays.push(OverlaySpec {
577            name: name.into(),
578            // Fail-closed default: never triggers until `.trigger(..)` is set.
579            trigger: Guard::is_true("__overlay_never_triggers__"),
580            stages: Vec::new(),
581            require: Vec::new(),
582            resume: Resume::Previous,
583        });
584        self.current_overlay = Some(self.spec.overlays.len() - 1);
585        self
586    }
587
588    /// Set the activation guard of the overlay currently being authored.
589    pub fn trigger(mut self, guard: Guard) -> Self {
590        if let Some(i) = self.current_overlay {
591            self.spec.overlays[i].trigger = guard;
592        }
593        self
594    }
595
596    /// Set the resume policy of the overlay currently being authored.
597    pub fn resume(mut self, resume: Resume) -> Self {
598        if let Some(i) = self.current_overlay {
599            self.spec.overlays[i].resume = resume;
600        }
601        self
602    }
603
604    /// End overlay authoring; subsequent `.stage(..)` calls target the main
605    /// flow again. (Not a sub-builder exit — the `Conversation` is the same
606    /// value throughout — so it is named for what it does.)
607    pub fn end_overlay(mut self) -> Self {
608        self.current_overlay = None;
609        self
610    }
611
612    /// Append a pre-built [`StageSpec`] (e.g. from a [`Motif`](crate::motifs::Motif)).
613    /// Routes to the active overlay when authoring one, else the main flow.
614    /// Subsequent stage setters (`next`, `say`, …) apply to it.
615    pub fn add_stage(mut self, stage: StageSpec) -> Self {
616        match self.current_overlay {
617            Some(i) => self.spec.overlays[i].stages.push(stage),
618            None => self.spec.stages.push(stage),
619        }
620        self
621    }
622
623    /// Append a pre-built [`OverlaySpec`] (e.g. a `Motif::faq_digression`). Leaves
624    /// overlay-authoring mode (the overlay is already complete).
625    pub fn add_overlay(mut self, overlay: OverlaySpec) -> Self {
626        self.spec.overlays.push(overlay);
627        self.current_overlay = None;
628        self
629    }
630
631    /// Attach a cross-cutting [`Policy`](crate::policy::Policy) aspect.
632    pub fn policy(mut self, policy: impl Into<crate::policy::Policy>) -> Self {
633        self.spec.policies.push(policy.into());
634        self
635    }
636
637    /// Apply `configure` to the stage most recently declared with
638    /// [`stage`](Self::stage). With no stage declared there is nothing to
639    /// configure: the misuse is recorded and [`compile`](Self::compile) reports it.
640    fn configure_stage(&mut self, setter: &str, configure: impl FnOnce(&mut StageSpec)) {
641        let stages = match self.current_overlay {
642            Some(i) => &mut self.spec.overlays[i].stages,
643            None => &mut self.spec.stages,
644        };
645        match stages.last_mut() {
646            Some(stage) => configure(stage),
647            None => self.issues.push(format!(
648                "`.{setter}(..)` was called before `.stage(..)`: there is no stage to configure"
649            )),
650        }
651    }
652
653    /// Set the stage's instruction: guidance projected to the model while the
654    /// stage is active. It steers what the model says; it is not verbatim
655    /// speech and carries no guarantee of exact wording.
656    pub fn instruction(mut self, text: impl Into<String>) -> Self {
657        self.configure_stage("instruction", |stage| stage.say = Some(text.into()));
658        self
659    }
660
661    /// Alias of [`instruction`](Self::instruction). The name suggests exact
662    /// speech, which this never was; prefer `instruction` in new code.
663    pub fn say(self, text: impl Into<String>) -> Self {
664        self.instruction(text)
665    }
666
667    /// Set the stage's grounding template.
668    pub fn ground(mut self, template: impl Into<String>) -> Self {
669        self.configure_stage("ground", |stage| stage.ground = Some(template.into()));
670        self
671    }
672
673    /// Collect the given slots in this stage (drives default completion).
674    pub fn collect<I, S>(mut self, fields: I) -> Self
675    where
676        I: IntoIterator<Item = S>,
677        S: Into<String>,
678    {
679        self.configure_stage("collect", |stage| {
680            stage.collect = fields.into_iter().map(Into::into).collect();
681        });
682        self
683    }
684
685    /// Collect the slots of a typed [`gemini_adk_rs::frame::Frame`] in this
686    /// stage. The frame's slot state-keys drive the `captured` completion; its
687    /// metadata (prompts/confirm/pii) is available via `F::frame()` for
688    /// confirmation and repair.
689    pub fn collect_frame<F: Frame>(mut self) -> Self {
690        let spec = F::frame();
691        self.configure_stage("collect_frame", |stage| {
692            stage.collect = spec.slot_keys();
693            stage.frame = Some(spec);
694        });
695        self
696    }
697
698    /// Allow the given tools while this stage is active.
699    ///
700    /// Calls to other governed tools are refused. Under
701    /// [`SteeringMode::ContextUpdate`](gemini_adk_rs::live::SteeringMode::ContextUpdate)
702    /// the model is also offered only the admitted tools while the stage is
703    /// active.
704    pub fn allow<I, S>(mut self, tools: I) -> Self
705    where
706        I: IntoIterator<Item = S>,
707        S: Into<String>,
708    {
709        self.configure_stage("allow", |stage| {
710            stage.allow = tools.into_iter().map(Into::into).collect();
711        });
712        self
713    }
714
715    /// Set an explicit completion guard for this stage: the stage counts as
716    /// complete when `guard` holds (default: all `collect`ed slots captured).
717    pub fn complete_when(mut self, guard: Guard) -> Self {
718        self.configure_stage("complete_when", |stage| stage.done = Some(guard));
719        self
720    }
721
722    /// Commit a confirm-before-act tool in this stage, gated by `when`.
723    pub fn commit(mut self, tool: impl Into<String>, when: Guard) -> Self {
724        self.configure_stage("commit", |stage| {
725            stage.commit = Some(CommitSpec {
726                tool: tool.into(),
727                when,
728            });
729        });
730        self
731    }
732
733    /// Add a forward transition to `to` when `when` holds.
734    pub fn next(mut self, to: impl Into<String>, when: Guard) -> Self {
735        self.configure_stage("next", |stage| {
736            stage.next.push(TransitionSpec {
737                to: to.into(),
738                when,
739            });
740        });
741        self
742    }
743
744    /// Fill a slot in the current stage from an **async resolver** — a tool call,
745    /// HTTP fetch, MCP request, or agent. `args` names the `State` keys bound into
746    /// the JSON object passed to `fetch`; the returned value fills `name`. With a
747    /// `ttl`, results are memoized by `(field, canonical args)`.
748    ///
749    /// The slot is added to the stage's `collect`, so its `captured` completion
750    /// waits for the resolution. The closure lives only in the builder; the
751    /// serializable spec is unaffected.
752    pub fn resolve_slot<I, S, F, Fut>(
753        mut self,
754        name: impl Into<String>,
755        args: I,
756        ttl: Option<Duration>,
757        fetch: F,
758    ) -> Self
759    where
760        I: IntoIterator<Item = S>,
761        S: Into<String>,
762        F: Fn(Value) -> Fut + Send + Sync + 'static,
763        Fut: Future<Output = Result<Value, String>> + Send + 'static,
764    {
765        let name = name.into();
766        let args: Vec<String> = args.into_iter().map(Into::into).collect();
767        let mut stage_id = None;
768        self.configure_stage("resolve_slot", |stage| {
769            stage_id = Some(stage.id.clone());
770            if !stage.collect.contains(&name) {
771                stage.collect.push(name.clone());
772            }
773            // Record the serializable declaration too, so `into_spec()` carries the
774            // resolver and the spec can later be re-bound from a `ResolverRegistry`.
775            stage.resolve.push(ResolveSpec {
776                slot: name.clone(),
777                resolver: None,
778                args: args.clone(),
779                ttl_secs: ttl.map(|d| d.as_secs()),
780            });
781        });
782        // No stage to bind the resolver to: the misuse is already recorded.
783        let Some(stage) = stage_id else {
784            return self;
785        };
786        let fetch = Arc::new(fetch);
787        self.resolvers.push(StageResolver {
788            stage,
789            name,
790            args,
791            ttl,
792            fetch: Arc::new(move |v| {
793                let fetch = fetch.clone();
794                Box::pin(async move { fetch(v).await })
795            }),
796        });
797        self
798    }
799
800    /// Add an explicit dependency on another stage.
801    pub fn after(mut self, dep: impl Into<String>) -> Self {
802        self.configure_stage("after", |stage| stage.after.push(dep.into()));
803        self
804    }
805
806    /// Mark the current stage terminal.
807    pub fn terminal(mut self) -> Self {
808        self.configure_stage("terminal", |stage| stage.terminal = true);
809        self
810    }
811
812    /// Attach a [`RepairPolicy`] to the current stage.
813    pub fn repair(mut self, policy: RepairPolicy) -> Self {
814        self.configure_stage("repair", |stage| stage.repair = Some(policy));
815        self
816    }
817
818    /// Require the current stage to say `text` word for word (strict canned
819    /// mode): it completes only once the model's output transcript matches.
820    /// The model holds the floor while it reads, unless the stage sets
821    /// [`timing`](Self::timing). Needs output transcription on the session.
822    pub fn verbatim(mut self, text: impl Into<String>) -> Self {
823        self.configure_stage("verbatim", |stage| stage.verbatim = Some(text.into()));
824        self
825    }
826
827    /// Set the current stage's voice pacing; see [`VoiceTiming`].
828    ///
829    /// ```
830    /// # use gemini_adk_fluent_rs::prelude::*;
831    /// use std::time::Duration;
832    /// Conversation::new("disclosure")
833    ///     .stage("read_terms")
834    ///     .say("Read the terms word for word.")
835    ///     .timing(VoiceTiming::new().uninterruptible())
836    ///     .stage("confirm")
837    ///     .collect(["agreed"])
838    ///     .timing(VoiceTiming::new().reprompt_after(Duration::from_secs(6)));
839    /// ```
840    pub fn timing(mut self, timing: VoiceTiming) -> Self {
841        self.configure_stage("timing", |stage| stage.timing = Some(timing));
842        self
843    }
844
845    /// Require these stages for completion (lowers to a Flow `require`). Targets
846    /// the active overlay when authoring one, else the main flow.
847    pub fn require<I, S>(mut self, steps: I) -> Self
848    where
849        I: IntoIterator<Item = S>,
850        S: Into<String>,
851    {
852        let req: Vec<String> = steps.into_iter().map(Into::into).collect();
853        match self.current_overlay {
854            Some(i) => self.spec.overlays[i].require = req,
855            None => self.spec.require = req,
856        }
857        self
858    }
859
860    /// The spec built so far. A setter called before any `.stage(..)` is
861    /// recorded as a misuse that [`compile`](Self::compile) and
862    /// [`try_into_spec`](Self::try_into_spec) report; this view does not.
863    pub fn spec(&self) -> &ConversationSpec {
864        &self.spec
865    }
866
867    /// Consume into the underlying spec, discarding any recorded builder
868    /// misuse. Use [`try_into_spec`](Self::try_into_spec) to have it
869    /// reported instead.
870    pub fn into_spec(self) -> ConversationSpec {
871        self.spec
872    }
873
874    /// Consume into the underlying spec, or the builder misuse `compile`
875    /// would report (a setter called before any `.stage(..)`).
876    pub fn try_into_spec(self) -> Result<ConversationSpec, ConversationError> {
877        if !self.issues.is_empty() {
878            return Err(ConversationError::Spec(self.issues.join("; ")));
879        }
880        Ok(self.spec)
881    }
882
883    /// Compile from a [`ConversationSpec`] (e.g. parsed from JSON/YAML).
884    ///
885    /// If the spec declares any named-resolver slots (`stage.resolve`), this
886    /// errors — those slots would be collected but never filled. Use
887    /// [`Conversation::from_spec_with_resolvers`] to bind them.
888    pub fn from_spec(spec: ConversationSpec) -> Result<CompiledConversation, ConversationError> {
889        Self::from_spec_with_resolvers(spec, &ResolverRegistry::new())
890    }
891
892    /// Compile a [`ConversationSpec`] with its declared resolvers **stubbed**
893    /// (each returns JSON `null`) — for structural validation, model-free
894    /// simulation, and CI, where resolver outputs are supplied by scenario
895    /// `set` steps rather than live fetches.
896    ///
897    /// Use this (not [`from_spec`](Self::from_spec)) when compiling a spec from
898    /// untrusted JSON for testing/authoring; use
899    /// [`from_spec_with_resolvers`](Self::from_spec_with_resolvers) at deploy
900    /// time to bind real implementations.
901    pub fn from_spec_stubbing_resolvers(
902        spec: ConversationSpec,
903    ) -> Result<CompiledConversation, ConversationError> {
904        let registry = ResolverRegistry::stubbing(&spec);
905        Self::from_spec_with_resolvers(spec, &registry)
906    }
907
908    /// Compile a [`ConversationSpec`] and bind its declared named-resolver slots
909    /// from `registry`. This makes a JSON spec + a resolver registry a complete
910    /// deployable unit.
911    ///
912    /// Errors if the spec references a resolver name absent from `registry`.
913    pub fn from_spec_with_resolvers(
914        spec: ConversationSpec,
915        registry: &ResolverRegistry,
916    ) -> Result<CompiledConversation, ConversationError> {
917        let mut resolvers = Vec::new();
918        let stages = spec
919            .stages
920            .iter()
921            .chain(spec.overlays.iter().flat_map(|o| o.stages.iter()));
922        for stage in stages {
923            for r in &stage.resolve {
924                let fetch = registry.get(r.resolver_name()).ok_or_else(|| {
925                    ConversationError::Spec(format!(
926                        "stage '{}' slot '{}' needs resolver '{}', which is not in the registry",
927                        stage.id,
928                        r.slot,
929                        r.resolver_name()
930                    ))
931                })?;
932                resolvers.push(StageResolver {
933                    stage: stage.id.clone(),
934                    name: r.slot.clone(),
935                    args: r.args.clone(),
936                    ttl: r.ttl_secs.map(Duration::from_secs),
937                    fetch,
938                });
939            }
940        }
941        compile_spec(spec, resolvers)
942    }
943
944    /// Lower and validate into a [`CompiledConversation`].
945    ///
946    /// Fails with [`ConversationError::Spec`] if a stage setter (`instruction`,
947    /// `next`, `terminal`, ...) was chained before any `.stage(..)`.
948    pub fn compile(self) -> Result<CompiledConversation, ConversationError> {
949        if !self.issues.is_empty() {
950            return Err(ConversationError::Spec(self.issues.join("; ")));
951        }
952        compile_spec(self.spec, self.resolvers)
953    }
954}
955
956impl crate::live::Live {
957    /// Drive a [`Live`](crate::live::Live) session from a compiled conversation:
958    /// **govern** with its lowered flow, **install** its digressions and repair
959    /// policies on the session's [`FlowStack`], and **register** the extractors
960    /// that fill its frames' slots each turn. The one-liner entrypoint for "run
961    /// this conversation": the session drives the same stack
962    /// [`CompiledConversation::stack`] builds for the simulator.
963    ///
964    /// ```no_run
965    /// # use gemini_adk_fluent_rs::prelude::*;
966    /// # use gemini_adk_fluent_rs::conversation::Conversation;
967    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
968    /// let convo = Conversation::new("booking")
969    ///     .stage("done").terminal()
970    ///     .require(["done"])
971    ///     .compile()?;
972    /// let handle = Live::builder()
973    ///     .converse(&convo)
974    ///     .connect_from_env()
975    ///     .await?;
976    /// # let _ = handle; Ok(())
977    /// # }
978    /// ```
979    pub fn converse(self, convo: &CompiledConversation) -> Self {
980        self.govern_compiled(convo.flow().clone())
981            .install_conversation(convo)
982    }
983
984    /// Like [`converse`](Self::converse) but attaches the flow in **observe** mode
985    /// (nothing blocked; deviations recorded) while still registering extractors.
986    pub fn converse_observe(self, convo: &CompiledConversation) -> Self {
987        self.observe_compiled(convo.flow().clone())
988            .install_conversation(convo)
989    }
990
991    /// Everything a compiled conversation declares beyond its main flow: the
992    /// digressions and repair policies (installed on the session's
993    /// [`FlowStack`]) and the extractors (main + overlays). The main flow was
994    /// attached by the caller in the chosen enforcement mode.
995    fn install_conversation(mut self, convo: &CompiledConversation) -> Self {
996        self.digressions = convo
997            .overlays()
998            .iter()
999            .map(CompiledOverlay::to_runtime)
1000            .collect();
1001        self.repair_policies = convo.repair_policies().clone();
1002        // A timing set on the builder with `stage_timing` wins over the
1003        // conversation's, whichever was called first.
1004        for (step, timing) in convo.timing_policies() {
1005            self.stage_timings
1006                .entry(step.clone())
1007                .or_insert_with(|| timing.clone());
1008        }
1009        self.corrections = convo.correction_policies().clone();
1010        self.verbatims = convo.verbatim_policies().clone();
1011        // A safety hand-off is already lowered into the digressions above;
1012        // redaction and commit governance are enforced at connect. Policies
1013        // added with `Live::policy` are kept alongside.
1014        let mut policies: Vec<_> = convo
1015            .policies()
1016            .iter()
1017            .filter(|p| !matches!(p, crate::policy::Policy::SafetyHandoff { .. }))
1018            .cloned()
1019            .collect();
1020        policies.append(&mut self.policies);
1021        self.policies = policies;
1022        for extract in convo.all_extractors() {
1023            self = self.extract_record(extract);
1024        }
1025        self
1026    }
1027}
1028
1029fn is_always(g: &Guard) -> bool {
1030    matches!(g, Guard::Spec(Pred::Always))
1031}
1032
1033/// Combine guards into a single disjunction, collapsing trivial cases.
1034fn any_of(guards: Vec<Guard>) -> Option<Guard> {
1035    if guards.is_empty() {
1036        return None;
1037    }
1038    if guards.iter().any(is_always) {
1039        return Some(Guard::always());
1040    }
1041    if guards.len() == 1 {
1042        return guards.into_iter().next();
1043    }
1044    Some(Guard::any(guards))
1045}
1046
1047/// Lower a set of stages (the main flow or an overlay) into a [`CompiledFlow`],
1048/// with conversation-level referential checks.
1049/// The stages an overlay without an explicit `require` must finish: its
1050/// terminal stages, else the stages no other stage follows.
1051fn overlay_ends(stages: &[StageSpec]) -> Vec<String> {
1052    let terminal: Vec<String> = stages
1053        .iter()
1054        .filter(|s| s.terminal)
1055        .map(|s| s.id.clone())
1056        .collect();
1057    if !terminal.is_empty() {
1058        return terminal;
1059    }
1060    let followed = |id: &str| stages.iter().any(|s| s.after.iter().any(|a| a == id));
1061    stages
1062        .iter()
1063        .filter(|s| s.next.is_empty() && !followed(&s.id))
1064        .map(|s| s.id.clone())
1065        .collect()
1066}
1067
1068fn lower_flow(stages: &[StageSpec], require: &[String]) -> Result<CompiledFlow, ConversationError> {
1069    if stages.is_empty() {
1070        return Err(ConversationError::Empty);
1071    }
1072    let ids: BTreeSet<&str> = stages.iter().map(|s| s.id.as_str()).collect();
1073    for s in stages {
1074        for t in &s.next {
1075            if !ids.contains(t.to.as_str()) {
1076                return Err(ConversationError::Spec(format!(
1077                    "stage '{}' transitions to unknown stage '{}'",
1078                    s.id, t.to
1079                )));
1080            }
1081        }
1082        for d in &s.after {
1083            if !ids.contains(d.as_str()) {
1084                return Err(ConversationError::Spec(format!(
1085                    "stage '{}' depends on unknown stage '{}'",
1086                    s.id, d
1087                )));
1088            }
1089        }
1090        if let Some(target) = s.repair.as_ref().and_then(|r| r.escalate_to.as_ref())
1091            && !ids.contains(target.as_str())
1092        {
1093            return Err(ConversationError::Spec(format!(
1094                "stage '{}' escalates to unknown stage '{}'",
1095                s.id, target
1096            )));
1097        }
1098    }
1099    for r in require {
1100        if !ids.contains(r.as_str()) {
1101            return Err(ConversationError::Spec(format!(
1102                "require references unknown stage '{r}'"
1103            )));
1104        }
1105    }
1106
1107    // Incoming edges: target -> [(source, when)].
1108    let mut incoming: BTreeMap<&str, Vec<(&str, Guard)>> = BTreeMap::new();
1109    for s in stages {
1110        for t in &s.next {
1111            incoming
1112                .entry(t.to.as_str())
1113                .or_default()
1114                .push((s.id.as_str(), t.when.clone()));
1115        }
1116        // Repair escalation is an extra edge gated on the escalate signal.
1117        if let Some(target) = s.repair.as_ref().and_then(|r| r.escalate_to.as_ref()) {
1118            incoming
1119                .entry(target.as_str())
1120                .or_default()
1121                .push((s.id.as_str(), Guard::is_true(escalate_flag(&s.id))));
1122        }
1123    }
1124
1125    let mut fb = Flow::new();
1126    for s in stages {
1127        fb = fb.step(&s.id);
1128
1129        let mut deps: BTreeSet<&str> = s.after.iter().map(String::as_str).collect();
1130        if let Some(inc) = incoming.get(s.id.as_str()) {
1131            for (src, _) in inc {
1132                deps.insert(src);
1133            }
1134        }
1135        for d in deps {
1136            fb = fb.after(d);
1137        }
1138
1139        if let Some(inc) = incoming.get(s.id.as_str())
1140            && let Some(gate) = any_of(inc.iter().map(|(_, w)| w.clone()).collect())
1141        {
1142            fb = fb.gate(gate);
1143        }
1144
1145        if let Some(posture) = stage_posture(s) {
1146            fb = fb.posture(posture);
1147        }
1148        if let Some(ground) = &s.ground {
1149            fb = fb.ground(ground.clone());
1150        }
1151
1152        let mut allow: Vec<String> = s.allow.clone();
1153        if let Some(c) = &s.commit
1154            && !allow.contains(&c.tool)
1155        {
1156            allow.push(c.tool.clone());
1157        }
1158        if !allow.is_empty() {
1159            fb = fb.allow(allow);
1160        }
1161        if let Some(c) = &s.commit {
1162            fb = fb.commit(&c.tool, c.when.clone());
1163        }
1164
1165        if s.terminal {
1166            fb = fb.terminal();
1167        } else {
1168            let done = stage_completion(s).ok_or_else(|| {
1169                ConversationError::Spec(format!(
1170                    "non-terminal stage '{}' has no completion (add collect, next, or done)",
1171                    s.id
1172                ))
1173            })?;
1174            fb = fb.done(done);
1175        }
1176    }
1177
1178    // A corrected slot re-opens the stages downstream of it.
1179    for rule in reopen_rules(stages) {
1180        if let Some(when) = any_of(
1181            rule.slots
1182                .iter()
1183                .map(|slot| Guard::is_true(correction_flag(slot)))
1184                .collect(),
1185        ) {
1186            fb = fb.reset(rule.steps).when(when);
1187        }
1188    }
1189
1190    if !require.is_empty() {
1191        fb = fb.require(require.to_vec());
1192    }
1193
1194    let flow = fb.build().map_err(|e| ConversationError::Flow(e.issues))?;
1195    flow.compile().map_err(ConversationError::Compile)
1196}
1197
1198/// The extractors lowered from a stage list's `collect_frame` frames.
1199fn frame_extractors(stages: &[StageSpec]) -> Vec<Extract> {
1200    stages
1201        .iter()
1202        .filter_map(|s| s.frame.as_ref().and_then(FrameSpec::to_extract))
1203        .collect()
1204}
1205
1206fn compile_spec(
1207    mut spec: ConversationSpec,
1208    resolvers: Vec<StageResolver>,
1209) -> Result<CompiledConversation, ConversationError> {
1210    let authored_overlay_count = spec.overlays.len();
1211    // Apply cross-cutting policies. SafetyHandoff lowers to a `safety` digression
1212    // (terminate on intent); Redact/Commit are carried for the runtime.
1213    for policy in spec.policies.clone() {
1214        if let crate::policy::Policy::SafetyHandoff { intents } = policy
1215            && let Some(trigger) = any_of(
1216                intents
1217                    .iter()
1218                    .map(|i| Guard::is_true(format!("intent:{i}")))
1219                    .collect(),
1220            )
1221        {
1222            spec.overlays.push(OverlaySpec {
1223                name: "safety".into(),
1224                trigger,
1225                stages: vec![StageSpec {
1226                    id: "safety_handoff".into(),
1227                    say: Some("Safety concern detected — hand off to a human now.".into()),
1228                    terminal: true,
1229                    ..Default::default()
1230                }],
1231                require: Vec::new(),
1232                resume: Resume::Terminate,
1233            });
1234        }
1235    }
1236
1237    // Stage ids also key resolver routing, timing, verbatim policies, and the
1238    // Studio graph. Their identity spans the whole conversation, not one layer.
1239    let mut overlay_names = BTreeSet::new();
1240    for overlay in &spec.overlays {
1241        if !overlay_names.insert(overlay.name.as_str()) {
1242            return Err(ConversationError::Spec(format!(
1243                "duplicate overlay name '{}'",
1244                overlay.name
1245            )));
1246        }
1247    }
1248    let mut stage_layers = BTreeMap::new();
1249    let layers = std::iter::once(("main flow".to_string(), spec.stages.as_slice())).chain(
1250        spec.overlays.iter().map(|overlay| {
1251            (
1252                format!("overlay '{}'", overlay.name),
1253                overlay.stages.as_slice(),
1254            )
1255        }),
1256    );
1257    for (layer, stages) in layers {
1258        for stage in stages {
1259            if let Some(previous) = stage_layers.insert(stage.id.as_str(), layer.clone()) {
1260                return Err(ConversationError::Spec(format!(
1261                    "duplicate stage ids: '{}' appears in {previous} and {layer}",
1262                    stage.id
1263                )));
1264            }
1265        }
1266    }
1267
1268    // A declared resolver slot behaves like a collected slot: the stage's
1269    // implicit `captured` completion must wait for the resolution. The builder
1270    // path (`resolve_slot`) adds it eagerly; specs parsed from JSON get the
1271    // same normalization here, before lowering.
1272    for stage in spec
1273        .stages
1274        .iter_mut()
1275        .chain(spec.overlays.iter_mut().flat_map(|o| o.stages.iter_mut()))
1276    {
1277        for slot in stage
1278            .resolve
1279            .iter()
1280            .map(|r| r.slot.clone())
1281            .collect::<Vec<_>>()
1282        {
1283            if !stage.collect.contains(&slot) {
1284                stage.collect.push(slot);
1285            }
1286        }
1287    }
1288
1289    // Main flow.
1290    let flow = lower_flow(&spec.stages, &spec.require)?;
1291
1292    // Resolver bindings must reference a known, uniquely owned stage — main
1293    // or overlay, as validated above.
1294    let ids: BTreeSet<&str> = spec.stages.iter().map(|s| s.id.as_str()).collect();
1295    let mut overlay_of: BTreeMap<&str, usize> = BTreeMap::new();
1296    for (i, ov) in spec.overlays.iter().enumerate() {
1297        for s in &ov.stages {
1298            overlay_of.insert(s.id.as_str(), i);
1299        }
1300    }
1301    for r in &resolvers {
1302        if !ids.contains(r.stage.as_str()) && !overlay_of.contains_key(r.stage.as_str()) {
1303            return Err(ConversationError::Spec(format!(
1304                "resolver for slot '{}' references unknown stage '{}'",
1305                r.name, r.stage
1306            )));
1307        }
1308    }
1309
1310    // Group resolver bindings per stage, routed to the main flow or the owning
1311    // overlay so overlay-declared resolvers actually fill their slots.
1312    let build_resolver_extractor = |stage: &str, binds: &[&StageResolver]| {
1313        let mut builder = Extract::record(format!("{}__{}_resolve", spec.name, stage));
1314        for r in binds {
1315            let fetch = r.fetch.clone();
1316            builder = builder.field_resolve(r.name.clone(), r.args.clone(), r.ttl, move |args| {
1317                let fetch = fetch.clone();
1318                async move { fetch(args).await }
1319            });
1320        }
1321        builder.build()
1322    };
1323    let mut by_stage: BTreeMap<&str, Vec<&StageResolver>> = BTreeMap::new();
1324    for r in &resolvers {
1325        by_stage.entry(r.stage.as_str()).or_default().push(r);
1326    }
1327    let mut overlay_extractors: BTreeMap<usize, Vec<Extract>> = BTreeMap::new();
1328
1329    // Main extractors: frame recognizers + resolver-slot bindings.
1330    let mut extractors = frame_extractors(&spec.stages);
1331    for (stage, binds) in &by_stage {
1332        let extractor = build_resolver_extractor(stage, binds);
1333        if ids.contains(stage) {
1334            extractors.push(extractor);
1335        } else if let Some(&i) = overlay_of.get(stage) {
1336            overlay_extractors.entry(i).or_default().push(extractor);
1337        }
1338    }
1339
1340    // Overlays: each lowers to its own validated flow + extractors. An overlay
1341    // with no explicit `require` is complete when its terminal stages are done,
1342    // or, with none marked terminal, its last stages (those nothing follows) —
1343    // so completion is meaningful (without it, `is_complete()` is trivially
1344    // true, and a handoff digression closed on the next turn whether or not its
1345    // transfer tool had run).
1346    let mut overlays = Vec::with_capacity(spec.overlays.len());
1347    for ov in &spec.overlays {
1348        let require = if ov.require.is_empty() {
1349            overlay_ends(&ov.stages)
1350        } else {
1351            ov.require.clone()
1352        };
1353        let ov_flow = lower_flow(&ov.stages, &require)?;
1354        let mut ov_extractors = frame_extractors(&ov.stages);
1355        if let Some(bound) = overlay_extractors.remove(&overlays.len()) {
1356            ov_extractors.extend(bound);
1357        }
1358        overlays.push(CompiledOverlay {
1359            name: ov.name.clone(),
1360            trigger: ov.trigger.clone(),
1361            flow: ov_flow,
1362            extractors: ov_extractors,
1363            resume: ov.resume,
1364        });
1365    }
1366
1367    // Per-stage repair policies for the runtime to apply.
1368    let repair = spec
1369        .stages
1370        .iter()
1371        .filter_map(|s| s.repair.clone().map(|p| (s.id.clone(), p)))
1372        .collect();
1373
1374    // Per-stage voice timing, main flow and digressions alike.
1375    let timing = spec
1376        .stages
1377        .iter()
1378        .chain(spec.overlays.iter().flat_map(|ov| ov.stages.iter()))
1379        .filter_map(|s| {
1380            let timing = s.timing.clone().or_else(|| {
1381                s.verbatim
1382                    .as_ref()
1383                    .map(|_| VoiceTiming::new().uninterruptible())
1384            });
1385            timing.map(|t| (s.id.clone(), t))
1386        })
1387        .collect();
1388
1389    // Verbatim stages, main flow and digressions alike.
1390    let verbatim = spec
1391        .stages
1392        .iter()
1393        .chain(spec.overlays.iter().flat_map(|ov| ov.stages.iter()))
1394        .filter_map(|s| s.verbatim.clone().map(|t| (s.id.clone(), t)))
1395        .collect();
1396
1397    // Slots whose correction re-opens downstream stages (lowered as resets
1398    // in the main flow above); the stack watches them.
1399    let mut corrections: BTreeMap<String, Vec<String>> = BTreeMap::new();
1400    for rule in reopen_rules(&spec.stages) {
1401        for slot in rule.slots {
1402            let clear = corrections.entry(slot).or_default();
1403            for key in &rule.clear {
1404                if !clear.contains(key) {
1405                    clear.push(key.clone());
1406                }
1407            }
1408        }
1409    }
1410
1411    let policies = spec.policies.clone();
1412    // Generated overlays belong to the compiled runtime. Keep the stored spec
1413    // re-compilable: its policies will generate these overlays again.
1414    spec.overlays.truncate(authored_overlay_count);
1415
1416    Ok(CompiledConversation {
1417        flow,
1418        extractors,
1419        overlays,
1420        repair,
1421        timing,
1422        corrections,
1423        verbatim,
1424        policies,
1425        spec,
1426    })
1427}
1428
1429/// The completion guard for a non-terminal stage, by priority:
1430/// explicit `done` → `captured(collect)` → disjunction of `next` conditions.
1431/// When repair escalation is configured, the stage may also complete by escalating
1432/// (so a stalled stage can hand off even though its normal completion never fired).
1433/// How a correction to each collected slot re-opens the conversation: the
1434/// stages downstream of the stage that collected it, and the state keys to
1435/// clear so those stages run again (their commit confirmations).
1436struct Reopen {
1437    slots: Vec<String>,
1438    steps: Vec<String>,
1439    clear: Vec<String>,
1440}
1441
1442/// For every stage that collects slots, the stages that depend on it
1443/// (through `after`, `next` or repair escalation, transitively) and would
1444/// have to run again if one of those slots were corrected.
1445fn reopen_rules(stages: &[StageSpec]) -> Vec<Reopen> {
1446    // Direct dependents: source -> stages that come after it.
1447    let mut dependents: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
1448    for s in stages {
1449        for d in &s.after {
1450            dependents
1451                .entry(d.as_str())
1452                .or_default()
1453                .insert(s.id.as_str());
1454        }
1455        for t in &s.next {
1456            dependents
1457                .entry(s.id.as_str())
1458                .or_default()
1459                .insert(t.to.as_str());
1460        }
1461        if let Some(target) = s.repair.as_ref().and_then(|r| r.escalate_to.as_ref()) {
1462            dependents
1463                .entry(s.id.as_str())
1464                .or_default()
1465                .insert(target.as_str());
1466        }
1467    }
1468    let collected: BTreeSet<&str> = stages
1469        .iter()
1470        .flat_map(|s| s.collect.iter().map(String::as_str))
1471        .collect();
1472    stages
1473        .iter()
1474        .filter(|s| !s.collect.is_empty())
1475        .filter_map(|s| {
1476            let mut downstream: BTreeSet<&str> = BTreeSet::new();
1477            let mut queue = vec![s.id.as_str()];
1478            while let Some(id) = queue.pop() {
1479                for next in dependents.get(id).into_iter().flatten() {
1480                    if *next != s.id && downstream.insert(next) {
1481                        queue.push(next);
1482                    }
1483                }
1484            }
1485            if downstream.is_empty() {
1486                return None;
1487            }
1488            let clear = stages
1489                .iter()
1490                .filter(|st| downstream.contains(st.id.as_str()))
1491                .filter_map(|st| st.commit.as_ref())
1492                .flat_map(|c| c.when.state_keys())
1493                .filter(|k| !collected.contains(k.as_str()))
1494                .collect::<BTreeSet<_>>()
1495                .into_iter()
1496                .collect();
1497            Some(Reopen {
1498                slots: s.collect.clone(),
1499                steps: downstream.into_iter().map(str::to_string).collect(),
1500                clear,
1501            })
1502        })
1503        .collect()
1504}
1505
1506/// The posture a stage projects: its `say`, plus the exact-reading
1507/// instruction of a verbatim stage.
1508fn stage_posture(s: &StageSpec) -> Option<String> {
1509    let read = s.verbatim.as_ref().map(|text| {
1510        format!(
1511            "Say the following exactly as written, word for word. Do not paraphrase, \
1512             add to or leave out any part of it:\n\n{text}"
1513        )
1514    });
1515    match (&s.say, read) {
1516        (Some(say), Some(read)) => Some(format!("{say}\n\n{read}")),
1517        (say, read) => say.clone().or(read),
1518    }
1519}
1520
1521fn stage_completion(s: &StageSpec) -> Option<Guard> {
1522    let base = stage_base_completion(s);
1523    // A verbatim stage also waits for its text to have been said.
1524    match (base, s.verbatim.is_some()) {
1525        (base, false) => base,
1526        (None, true) => Some(Guard::is_true(verbatim_flag(&s.id))),
1527        (Some(base), true) => Some(Guard::all(vec![base, Guard::is_true(verbatim_flag(&s.id))])),
1528    }
1529}
1530
1531fn stage_base_completion(s: &StageSpec) -> Option<Guard> {
1532    let base = if let Some(g) = &s.done {
1533        Some(g.clone())
1534    } else if !s.collect.is_empty() {
1535        Some(Guard::captured(s.collect.clone()))
1536    } else {
1537        any_of(s.next.iter().map(|t| t.when.clone()).collect())
1538    };
1539    if s.repair
1540        .as_ref()
1541        .and_then(|r| r.escalate_to.as_ref())
1542        .is_some()
1543    {
1544        let esc = Guard::is_true(escalate_flag(&s.id));
1545        return Some(match base {
1546            Some(b) => Guard::any(vec![b, esc]),
1547            None => esc,
1548        });
1549    }
1550    base
1551}
1552
1553#[cfg(test)]
1554mod tests {
1555    use super::*;
1556    use gemini_adk_rs::flow::Enforcement;
1557    use gemini_adk_rs::state::State;
1558
1559    #[test]
1560    fn stage_setters_before_the_first_stage_fail_at_compile() {
1561        let err = Conversation::new("misused")
1562            .instruction("hello")
1563            .terminal()
1564            .stage("only")
1565            .compile()
1566            .expect_err("setters chained before `.stage(..)` have no stage to configure");
1567        let ConversationError::Spec(message) = err else {
1568            panic!("expected a Spec error, got {err}");
1569        };
1570        assert!(message.contains("`.instruction(..)`"), "{message}");
1571        assert!(message.contains("`.terminal(..)`"), "{message}");
1572    }
1573
1574    #[test]
1575    fn try_into_spec_reports_the_misuse_into_spec_discards() {
1576        let misused = || {
1577            Conversation::new("misused")
1578                .instruction("hello")
1579                .stage("only")
1580        };
1581        let err = misused()
1582            .try_into_spec()
1583            .expect_err("a setter before `.stage(..)` is reported");
1584        assert!(matches!(err, ConversationError::Spec(_)), "{err}");
1585        // The lossy form keeps working for callers that chained correctly
1586        // and documents that it drops the record otherwise.
1587        assert_eq!(misused().into_spec().stages.len(), 1);
1588        assert!(
1589            Conversation::new("ok")
1590                .stage("only")
1591                .instruction("hello")
1592                .try_into_spec()
1593                .is_ok()
1594        );
1595    }
1596
1597    fn booking() -> CompiledConversation {
1598        Conversation::new("booking")
1599            .stage("collect")
1600            .instruction("Help the user book a table.")
1601            .collect(["party_size", "slot"])
1602            .next("check", Guard::captured(["party_size", "slot"]))
1603            .stage("check")
1604            .ground("Party of {party_size} at {slot}.")
1605            .next("confirm", Guard::is_true("availability_ok"))
1606            .stage("confirm")
1607            .commit("book", Guard::is_true("user_confirmed"))
1608            .next("done", Guard::called_ok("book"))
1609            .stage("done")
1610            .terminal()
1611            .require(["done"])
1612            .compile()
1613            .expect("booking compiles")
1614    }
1615
1616    #[test]
1617    fn compiles_to_a_governed_flow() {
1618        let convo = booking();
1619        // The commit tool is in the tool universe and gated.
1620        assert!(convo.flow().tool_surface().tools.contains("book"));
1621        assert_eq!(convo.flow().flow().steps.len(), 4);
1622    }
1623
1624    #[test]
1625    fn lowered_flow_enforces_stage_order_and_commit() {
1626        let convo = booking();
1627        let mut mon = convo.monitor(Enforcement::Enforce);
1628        let state = State::new();
1629
1630        // First stage active; book is blocked (not allowed here + not confirmed).
1631        let ex = mon.explain(&state);
1632        assert!(ex.active.contains(&"collect".to_string()));
1633        assert!(ex.blocked_tools.contains_key("book"));
1634
1635        // Collect the slots → collect completes, check activates.
1636        let _ = state.set("party_size", 4u8);
1637        let _ = state.set("slot", "tomorrow 7pm");
1638        mon.on_turn(&state);
1639        assert!(mon.explain(&state).active.contains(&"check".to_string()));
1640
1641        // Availability → confirm activates; book still needs confirmation.
1642        let _ = state.set("availability_ok", true);
1643        mon.on_turn(&state);
1644        assert!(mon.admits_tool("book", &state).is_err());
1645
1646        // Confirm → book admitted; calling it completes the conversation.
1647        let _ = state.set("user_confirmed", true);
1648        assert!(mon.admits_tool("book", &state).is_ok());
1649        mon.on_tool_ok("book", &state);
1650        mon.on_turn(&state);
1651        assert!(mon.is_complete());
1652    }
1653
1654    #[test]
1655    fn spec_round_trips_through_json() {
1656        let spec = booking().spec().clone();
1657        let json = serde_json::to_string(&spec).expect("serialize spec");
1658        let back: ConversationSpec = serde_json::from_str(&json).expect("deserialize spec");
1659        let recompiled = Conversation::from_spec(back).expect("recompile from spec");
1660        assert_eq!(recompiled.flow().flow().steps.len(), 4);
1661    }
1662
1663    #[tokio::test]
1664    async fn named_resolver_spec_round_trips_and_binds_from_registry() {
1665        // A spec declaring a named-resolver slot (data only, no closure).
1666        let json = r#"
1667        {
1668          "name": "booking",
1669          "stages": [
1670            { "id": "check",
1671              "resolve": [{ "slot": "availability", "resolver": "avail", "args": ["party_size"] }],
1672              "next": [{ "to": "done", "when": { "captured": ["availability"] } }] },
1673            { "id": "done", "terminal": true }
1674          ],
1675          "require": ["done"]
1676        }
1677        "#;
1678        let spec: ConversationSpec = serde_json::from_str(json).expect("parse");
1679        // Round-trips losslessly.
1680        let reser = serde_json::to_string(&spec).unwrap();
1681        let back: ConversationSpec = serde_json::from_str(&reser).unwrap();
1682        assert_eq!(back.stages[0].resolve[0].resolver_name(), "avail");
1683
1684        // Without a registry, an unbound resolver is a loud error (not a silently
1685        // unfillable slot).
1686        let err = Conversation::from_spec(back.clone()).expect_err("unbound resolver errors");
1687        assert!(matches!(err, ConversationError::Spec(m) if m.contains("avail")));
1688
1689        // With a registry, it compiles and the resolver extractor is wired.
1690        let registry = ResolverRegistry::new().with("avail", |_args| async move {
1691            Ok(serde_json::json!({ "open": true }))
1692        });
1693        let convo =
1694            Conversation::from_spec_with_resolvers(back, &registry).expect("binds and compiles");
1695        // The resolver lowered to an extractor that fills the `availability` slot.
1696        assert!(
1697            convo.extractors().iter().any(|e| e
1698                .field_state_keys()
1699                .iter()
1700                .any(|(_, k)| k == "availability")),
1701            "a resolver extractor filling 'availability' was compiled in"
1702        );
1703    }
1704
1705    #[tokio::test]
1706    async fn resolver_spec_is_validatable_and_simulatable_without_a_registry() {
1707        // The exact shape the CLI/Python/CI data-plane sees: a resolver slot
1708        // with no implementation available.
1709        let json = r#"{ "name": "r", "stages": [
1710            { "id": "check",
1711              "resolve": [{ "slot": "avail", "resolver": "lookup", "args": ["x"] }],
1712              "next": [{ "to": "done", "when": { "captured": ["avail"] } }] },
1713            { "id": "done", "terminal": true } ], "require": ["done"] }"#;
1714        let spec: ConversationSpec = serde_json::from_str(json).unwrap();
1715
1716        // Strict path (no registry) errors — as it should at deploy time.
1717        assert!(Conversation::from_spec(spec.clone()).is_err());
1718
1719        // Stubbing path compiles for structural validation + simulation.
1720        let convo = Conversation::from_spec_stubbing_resolvers(spec)
1721            .expect("stubbed resolvers compile for testing");
1722
1723        // A scenario supplies the resolver's output via `set` (the stub fetch is
1724        // never invoked when the slot is pre-set), and the flow completes.
1725        use crate::simulation::Sim;
1726        let mut sim = Sim::new(&convo, gemini_adk_rs::flow::Enforcement::Enforce);
1727        sim.set("avail", serde_json::json!({ "open": true }));
1728        sim.turn();
1729        assert!(sim.is_complete(), "resolver slot supplied by set completes");
1730    }
1731
1732    #[tokio::test]
1733    async fn overlay_resolver_binds_validates_and_fills_the_overlay() {
1734        // A resolver declared on an OVERLAY stage must be validated against the
1735        // registry and lowered into that overlay's extractors — not silently
1736        // ignored (which left the slot permanently unfilled at runtime).
1737        let json = r#"{ "name": "ov", "stages": [
1738            { "id": "main", "terminal": true } ],
1739          "require": ["main"],
1740          "overlays": [ { "name": "lookup", "trigger": { "is_true": "intent:lookup" },
1741            "stages": [
1742              { "id": "fetch", "resolve": [{ "slot": "balance", "resolver": "bal" }] },
1743              { "id": "ov_done", "terminal": true, "after": ["fetch"] } ] } ] }"#;
1744        let spec: ConversationSpec = serde_json::from_str(json).unwrap();
1745
1746        // Unbound overlay resolver is a loud error, same as a main-stage one.
1747        let err = Conversation::from_spec(spec.clone()).expect_err("unbound overlay resolver");
1748        assert!(matches!(err, ConversationError::Spec(m) if m.contains("bal")));
1749
1750        // Bound, it compiles and the extractor lands on the overlay.
1751        let registry =
1752            ResolverRegistry::new().with("bal", |_args| async move { Ok(serde_json::json!(42)) });
1753        let convo = Conversation::from_spec_with_resolvers(spec, &registry).expect("compiles");
1754        assert!(
1755            convo.overlays()[0]
1756                .extractors
1757                .iter()
1758                .any(|e| e.field_state_keys().iter().any(|(_, k)| k == "balance")),
1759            "the overlay carries the resolver extractor for 'balance'"
1760        );
1761    }
1762
1763    #[tokio::test]
1764    async fn resolver_slot_counts_toward_stage_completion_from_json() {
1765        // A resolver-only stage from JSON must gain the slot in `collect` (the
1766        // builder path adds it eagerly), so its implicit captured completion
1767        // exists and lowering succeeds instead of failing with "no completion".
1768        let json = r#"{ "name": "r2", "stages": [
1769            { "id": "check", "resolve": [{ "slot": "avail", "resolver": "lookup" }] },
1770            { "id": "done", "terminal": true, "after": ["check"] } ],
1771          "require": ["done"] }"#;
1772        let spec: ConversationSpec = serde_json::from_str(json).unwrap();
1773        let convo =
1774            Conversation::from_spec_stubbing_resolvers(spec).expect("resolver-only stage compiles");
1775        assert!(
1776            convo.spec().stages[0]
1777                .collect
1778                .contains(&"avail".to_string()),
1779            "declared resolver slot normalized into collect"
1780        );
1781    }
1782
1783    #[test]
1784    fn conversation_spec_schema_is_valid_json_with_expected_shape() {
1785        let schema_str = conversation_spec_schema();
1786        let schema: serde_json::Value =
1787            serde_json::from_str(&schema_str).expect("schema is valid JSON");
1788        // The root describes ConversationSpec; its `stages` property must exist
1789        // (proves the transitive JsonSchema derives wired through StageSpec).
1790        assert_eq!(schema["title"], "ConversationSpec");
1791        assert!(
1792            schema["properties"]["stages"].is_object(),
1793            "schema exposes the stages property: {schema}"
1794        );
1795        // The closed atom set (Pred, via Guard) must appear in $defs.
1796        assert!(
1797            schema["definitions"]["Pred"].is_object() || schema["$defs"]["Pred"].is_object(),
1798            "Pred atom schema is present"
1799        );
1800    }
1801
1802    #[test]
1803    fn conversation_error_serializes_machine_readable() {
1804        // An unguarded commit is rejected at compile with a Compile error.
1805        let err = Conversation::new("x")
1806            .stage("s")
1807            .commit("pay", Guard::always())
1808            .complete_when(Guard::called_ok("pay"))
1809            .next("done", Guard::called_ok("pay"))
1810            .stage("done")
1811            .terminal()
1812            .compile()
1813            .expect_err("unguarded commit must fail");
1814        let json = serde_json::to_value(&err).expect("error serializes");
1815        assert_eq!(json["kind"], "compile");
1816        assert!(json["message"].is_string());
1817        // The structured per-error list carries the tagged FlowError diagnostics.
1818        let errors = json["errors"].as_array().expect("errors array");
1819        assert!(
1820            errors.iter().any(|e| e["kind"] == "unguarded_commit_tool"),
1821            "structured FlowError kinds present: {json}"
1822        );
1823    }
1824
1825    #[test]
1826    fn collect_frame_uses_frame_slot_keys() {
1827        use gemini_adk_rs::frame::{Frame, FrameSpec, SlotSpec};
1828
1829        struct Booking;
1830        impl Frame for Booking {
1831            fn frame() -> FrameSpec {
1832                FrameSpec {
1833                    name: "booking".into(),
1834                    slots: vec![SlotSpec::new("party_size"), SlotSpec::new("slot")],
1835                }
1836            }
1837        }
1838
1839        let convo = Conversation::new("b")
1840            .stage("collect")
1841            .collect_frame::<Booking>()
1842            .next("done", Guard::captured(["party_size", "slot"]))
1843            .stage("done")
1844            .terminal()
1845            .compile()
1846            .expect("compiles");
1847
1848        // The collect stage completes on the frame's slots being captured.
1849        let mut mon = convo.monitor(Enforcement::Enforce);
1850        let state = State::new();
1851        assert!(mon.explain(&state).active.contains(&"collect".to_string()));
1852        let _ = state.set("party_size", 2u8);
1853        let _ = state.set("slot", "noon");
1854        mon.on_turn(&state);
1855        // Frame slots captured -> collect completes and the (terminal) done latches.
1856        assert!(mon.marking().done.contains("collect"));
1857        assert!(mon.marking().done.contains("done"));
1858    }
1859
1860    #[tokio::test]
1861    async fn collect_frame_extractor_fills_and_scores_slots() {
1862        use gemini_adk_rs::frame::{Frame, FrameSpec, SlotRecognizer, SlotSpec};
1863        use gemini_adk_rs::live::TranscriptTurn;
1864
1865        struct Order;
1866        impl Frame for Order {
1867            fn frame() -> FrameSpec {
1868                FrameSpec {
1869                    name: "order".into(),
1870                    slots: vec![SlotSpec {
1871                        recognizer: Some(SlotRecognizer::OneOf(vec![
1872                            "pizza".into(),
1873                            "salad".into(),
1874                        ])),
1875                        ..SlotSpec::new("item")
1876                    }],
1877                }
1878            }
1879        }
1880
1881        let convo = Conversation::new("o")
1882            .stage("collect")
1883            .collect_frame::<Order>()
1884            .next("done", Guard::captured(["item"]))
1885            .stage("done")
1886            .terminal()
1887            .compile()
1888            .expect("compiles");
1889
1890        // The frame lowered to exactly one extractor.
1891        assert_eq!(convo.extractors().len(), 1);
1892        let extractor = convo.extractors()[0].clone().into_extractor();
1893
1894        // Run it over a transcript turn against State — it fills the slot and
1895        // records confidence under `state_meta:` for evidence.
1896        let state = State::new();
1897        let window = vec![TranscriptTurn {
1898            turn_number: 0,
1899            user: "I'd like a large PIZZA".into(),
1900            model: String::new(),
1901            tool_calls: Vec::new(),
1902            timestamp: std::time::Instant::now(),
1903        }];
1904        let out = extractor.extract_with_state(&window, &state).await.unwrap();
1905        assert_eq!(out.get("item").and_then(|v| v.as_str()), Some("pizza"));
1906
1907        let ev = state.evidence("item");
1908        assert_eq!(ev.source.as_deref(), Some("extraction"));
1909        assert!(ev.confidence.unwrap() > 0.0);
1910    }
1911
1912    #[tokio::test]
1913    async fn validate_rejects_out_of_range_recognized_values() {
1914        use gemini_adk_rs::frame::{Frame, FrameSpec, SlotRecognizer, SlotSpec, SlotValidator};
1915        use gemini_adk_rs::live::TranscriptTurn;
1916
1917        struct Party;
1918        impl Frame for Party {
1919            fn frame() -> FrameSpec {
1920                FrameSpec {
1921                    name: "party".into(),
1922                    slots: vec![SlotSpec {
1923                        recognizer: Some(SlotRecognizer::Integer),
1924                        validate: Some(SlotValidator::Range {
1925                            min: Some(1.0),
1926                            max: Some(12.0),
1927                        }),
1928                        ..SlotSpec::new("party_size")
1929                    }],
1930                }
1931            }
1932        }
1933
1934        let convo = Conversation::new("p")
1935            .stage("collect")
1936            .collect_frame::<Party>()
1937            .next("done", Guard::captured(["party_size"]))
1938            .stage("done")
1939            .terminal()
1940            .compile()
1941            .expect("compiles");
1942        let extractor = convo.extractors()[0].clone().into_extractor();
1943
1944        let run = |text: &str| {
1945            let extractor = extractor.clone();
1946            let text = text.to_string();
1947            async move {
1948                let state = State::new();
1949                let window = vec![TranscriptTurn {
1950                    turn_number: 0,
1951                    user: text,
1952                    model: String::new(),
1953                    tool_calls: Vec::new(),
1954                    timestamp: std::time::Instant::now(),
1955                }];
1956                let out = extractor.extract_with_state(&window, &state).await.unwrap();
1957                out.get("party_size").cloned()
1958            }
1959        };
1960
1961        // In range -> filled; out of range -> rejected (no value promoted).
1962        assert_eq!(run("a table for 4").await, Some(serde_json::json!(4)));
1963        assert_eq!(run("a table for 40").await, None);
1964    }
1965
1966    #[tokio::test]
1967    async fn resolve_slot_fills_from_async_fetch() {
1968        use gemini_adk_rs::live::TranscriptTurn;
1969
1970        let convo = Conversation::new("c")
1971            .stage("check")
1972            .resolve_slot("availability", ["party_size"], None, |args| async move {
1973                // Echo an availability decision derived from the bound arg.
1974                let n = args
1975                    .get("party_size")
1976                    .and_then(serde_json::Value::as_i64)
1977                    .unwrap_or(0);
1978                Ok(serde_json::json!(n <= 8))
1979            })
1980            .next("done", Guard::is_set("availability"))
1981            .stage("done")
1982            .terminal()
1983            .compile()
1984            .expect("compiles");
1985
1986        // The resolver lowered to an extractor.
1987        assert_eq!(convo.extractors().len(), 1);
1988        let extractor = convo.extractors()[0].clone().into_extractor();
1989
1990        let state = State::new();
1991        let _ = state.set("party_size", 4i64);
1992        let window = vec![TranscriptTurn {
1993            turn_number: 0,
1994            user: "any".into(),
1995            model: String::new(),
1996            tool_calls: Vec::new(),
1997            timestamp: std::time::Instant::now(),
1998        }];
1999        let out = extractor.extract_with_state(&window, &state).await.unwrap();
2000        assert_eq!(out.get("availability"), Some(&serde_json::json!(true)));
2001    }
2002
2003    #[test]
2004    fn converse_registers_flow_and_extractors() {
2005        // Smoke test: the one-liner entrypoint wires onto a Live builder.
2006        use gemini_adk_rs::frame::{Frame, FrameSpec, SlotRecognizer, SlotSpec};
2007
2008        struct Order;
2009        impl Frame for Order {
2010            fn frame() -> FrameSpec {
2011                FrameSpec {
2012                    name: "order".into(),
2013                    slots: vec![SlotSpec {
2014                        recognizer: Some(SlotRecognizer::OneOf(vec!["pizza".into()])),
2015                        ..SlotSpec::new("item")
2016                    }],
2017                }
2018            }
2019        }
2020        let convo = Conversation::new("o")
2021            .stage("collect")
2022            .collect_frame::<Order>()
2023            .next("done", Guard::captured(["item"]))
2024            .stage("done")
2025            .terminal()
2026            .compile()
2027            .expect("compiles");
2028
2029        // Builds without panic; converse is the one-liner that govern()s + registers.
2030        let _live = crate::live::Live::builder().converse(&convo);
2031    }
2032
2033    #[test]
2034    fn overlay_suspends_main_then_resumes_previous() {
2035        // Main: a -> b. FAQ overlay triggered by intent:faq, single terminal stage,
2036        // resume Previous. While the overlay runs, the main marking is untouched.
2037        let convo = Conversation::new("support")
2038            .stage("a")
2039            .next("b", Guard::is_true("a_done"))
2040            .stage("b")
2041            .terminal()
2042            .overlay("faq")
2043            .trigger(Guard::is_true("intent:faq"))
2044            // A gated answer stage so the overlay does not complete in one turn.
2045            .stage("answer")
2046            .complete_when(Guard::is_true("faq_answered"))
2047            .next("faq_end", Guard::is_true("faq_answered"))
2048            .stage("faq_end")
2049            .terminal()
2050            .resume(Resume::Previous)
2051            .end_overlay()
2052            .compile()
2053            .expect("compiles");
2054
2055        assert_eq!(convo.overlays().len(), 1);
2056        let mut stack = convo.stack(Enforcement::Enforce);
2057        let state = State::new();
2058
2059        // Main is active on `a`.
2060        assert!(stack.explain(&state).active.contains(&"a".to_string()));
2061        assert!(stack.active_overlay().is_none());
2062
2063        // Intent fires -> digression suspends the main flow and stays active.
2064        let _ = state.set("intent:faq", true);
2065        stack.on_turn(&state);
2066        assert_eq!(stack.active_overlay(), Some("faq"));
2067
2068        // Answer the FAQ and clear the intent so the overlay completes. It is
2069        // still the projected layer for this closing turn.
2070        let _ = state.set("faq_answered", true);
2071        let _ = state.set("intent:faq", false);
2072        stack.on_turn(&state);
2073        assert_eq!(stack.active_overlay(), Some("faq"));
2074
2075        // Next boundary: main resumed exactly where it was, still on `a`.
2076        stack.on_turn(&state);
2077        assert!(stack.active_overlay().is_none());
2078        assert!(stack.explain(&state).active.contains(&"a".to_string()));
2079
2080        // Main continues normally afterward.
2081        let _ = state.set("a_done", true);
2082        stack.on_turn(&state);
2083        assert!(stack.current().marking().done.contains("a"));
2084    }
2085
2086    /// A handoff digression whose one stage waits for the transfer tool, with
2087    /// no `require` and no terminal stage (the shape `adk spec plan`'s
2088    /// `escalation` answer writes). In a live run the model offered the
2089    /// transfer instead of making it; the digression closed on the next turn
2090    /// and, resuming with `terminate`, ended the call untransferred.
2091    #[test]
2092    fn a_handoff_digression_waits_for_its_transfer() {
2093        let spec: ConversationSpec = serde_json::from_value(serde_json::json!({
2094            "name": "dental",
2095            "stages": [
2096                { "id": "book", "allow": ["book_cleaning"], "next": [{ "to": "done", "when": { "called_ok": "book_cleaning" } }] },
2097                { "id": "done", "terminal": true }
2098            ],
2099            "overlays": [{
2100                "name": "handoff",
2101                "trigger": { "is_true": "intent:urgent_care" },
2102                "stages": [{
2103                    "id": "transfer",
2104                    "allow": ["transfer_to_staff"],
2105                    "done": { "called_ok": "transfer_to_staff" }
2106                }],
2107                "resume": "terminate"
2108            }]
2109        }))
2110        .unwrap();
2111        let convo = Conversation::from_spec(spec).expect("compiles");
2112        let mut stack = convo.stack(Enforcement::Enforce);
2113        let state = State::new();
2114
2115        let _ = state.set("intent:urgent_care", true);
2116        stack.on_turn(&state);
2117        assert_eq!(stack.active_overlay(), Some("handoff"));
2118        // The model talks instead of transferring, for two turns.
2119        stack.on_turn(&state);
2120        stack.on_turn(&state);
2121        assert_eq!(stack.active_overlay(), Some("handoff"));
2122        assert!(
2123            !stack.is_terminated(),
2124            "the call is still waiting on the transfer"
2125        );
2126        assert!(stack.admits_tool("transfer_to_staff", &state).is_ok());
2127        assert!(stack.admits_tool("book_cleaning", &state).is_err());
2128
2129        stack.on_tool_ok("transfer_to_staff", &state);
2130        stack.on_turn(&state);
2131        stack.on_turn(&state);
2132        assert!(stack.is_terminated(), "terminated once the transfer ran");
2133    }
2134
2135    /// The artifact `converse()` installs on a live session is the same stack
2136    /// the simulator drives. Build both from one compiled conversation, advance
2137    /// them over the same state and turn sequence, and require identical
2138    /// governance at every turn: active steps, admitted/blocked tools, the
2139    /// active digression, and repair signals.
2140    #[test]
2141    fn live_and_simulator_drive_the_same_stack() {
2142        use crate::simulation::Sim;
2143
2144        let convo = Conversation::new("support")
2145            .stage("collect")
2146            .allow(["lookup"])
2147            .complete_when(Guard::is_true("info"))
2148            .next("done", Guard::is_true("info"))
2149            .repair(RepairPolicy::new(2, 3).escalate_to("handoff"))
2150            .stage("done")
2151            .terminal()
2152            .stage("handoff")
2153            .complete_when(Guard::is_true("handoff_complete"))
2154            .overlay("faq")
2155            .trigger(Guard::is_true("intent:faq"))
2156            .stage("answer")
2157            .allow(["search_faq"])
2158            .complete_when(Guard::is_true("faq_answered"))
2159            .next("faq_end", Guard::is_true("faq_answered"))
2160            .stage("faq_end")
2161            .terminal()
2162            .resume(Resume::Previous)
2163            .end_overlay()
2164            .compile()
2165            .expect("compiles");
2166
2167        // What a live session installs (the builder's view, no network).
2168        let live = crate::live::Live::builder().converse(&convo);
2169        assert_eq!(
2170            live.digressions()
2171                .iter()
2172                .map(gemini_adk_rs::flow::Overlay::name)
2173                .collect::<Vec<_>>(),
2174            ["faq"]
2175        );
2176        assert!(live.repair_policies().contains_key("collect"));
2177        let monitor = FlowMonitor::compiled(convo.flow().clone(), Enforcement::Enforce);
2178        let mut installed = crate::live::connect::assemble_stack(
2179            monitor,
2180            live.digressions().to_vec(),
2181            live.repair_policies().clone(),
2182            std::collections::BTreeMap::new(),
2183            std::collections::BTreeMap::new(),
2184            std::collections::BTreeMap::new(),
2185            &[],
2186        );
2187
2188        // What the simulator drives.
2189        let mut sim = Sim::new(&convo, Enforcement::Enforce);
2190        // Both stacks read the same facts.
2191        let state = sim.state().clone();
2192
2193        let script: [&[(&str, bool)]; 6] = [
2194            &[],
2195            &[("intent:faq", true)],
2196            &[("faq_answered", true), ("intent:faq", false)],
2197            &[],
2198            &[],
2199            &[],
2200        ];
2201        for facts in script {
2202            for (k, v) in facts {
2203                let _ = state.set(*k, *v);
2204            }
2205            sim.turn();
2206            installed.on_turn(&state);
2207            let a = sim.explain();
2208            let b = installed.explain(&state);
2209            assert_eq!(a.active, b.active);
2210            assert_eq!(a.allowed_tools, b.allowed_tools);
2211            assert_eq!(a.blocked_tools, b.blocked_tools);
2212            assert_eq!(sim.active_overlay(), installed.active_overlay());
2213            assert_eq!(sim.is_complete(), installed.is_complete());
2214        }
2215        // The script exercised a digression and a repair escalation.
2216        assert!(
2217            installed
2218                .explain(&state)
2219                .active
2220                .contains(&"handoff".to_string())
2221        );
2222        assert_eq!(state.get::<bool>("repair:collect:escalate"), Some(true));
2223    }
2224
2225    /// Replacing the governing flow discards the conversation's digressions:
2226    /// they only mean something relative to the main flow they suspend.
2227    #[test]
2228    fn regoverning_drops_installed_digressions() {
2229        let convo = Conversation::new("s")
2230            .stage("a")
2231            .terminal()
2232            .overlay("faq")
2233            .trigger(Guard::is_true("intent:faq"))
2234            .stage("x")
2235            .terminal()
2236            .end_overlay()
2237            .compile()
2238            .expect("compiles");
2239        let live = crate::live::Live::builder().converse(&convo);
2240        assert_eq!(live.digressions().len(), 1);
2241        let live = live.govern(Flow::new().step("only").terminal().build().expect("valid"));
2242        assert!(live.digressions().is_empty());
2243    }
2244
2245    #[test]
2246    fn overlay_spec_round_trips_through_json() {
2247        let spec = Conversation::new("s")
2248            .stage("main")
2249            .terminal()
2250            .overlay("cancel")
2251            .trigger(Guard::is_true("intent:cancel"))
2252            .stage("confirm")
2253            .terminal()
2254            .resume(Resume::Terminate)
2255            .end_overlay()
2256            .into_spec();
2257        let json = serde_json::to_string(&spec).unwrap();
2258        let back: ConversationSpec = serde_json::from_str(&json).unwrap();
2259        assert_eq!(back.overlays.len(), 1);
2260        assert_eq!(back.overlays[0].resume, Resume::Terminate);
2261        // Recompiles from the round-tripped spec.
2262        assert!(Conversation::from_spec(back).is_ok());
2263    }
2264
2265    #[tokio::test]
2266    async fn safety_policy_terminates_on_intent() {
2267        use crate::policy::Policy;
2268        use crate::simulation::Sim;
2269
2270        let convo = Conversation::new("support")
2271            .policy(Policy::safety_handoff(["self_harm", "abuse"]))
2272            .policy(Policy::redact(["card_number"]))
2273            .stage("triage")
2274            .next("resolve", Guard::is_true("triaged"))
2275            .stage("resolve")
2276            .terminal()
2277            .require(["resolve"])
2278            .compile()
2279            .expect("compiles");
2280
2281        // Redaction set is recorded for the runtime.
2282        assert!(convo.redacted_fields().contains("card_number"));
2283        // SafetyHandoff lowered to a `safety` digression.
2284        assert!(convo.overlays().iter().any(|o| o.name == "safety"));
2285
2286        let mut sim = Sim::new(&convo, Enforcement::Enforce);
2287        assert!(sim.active().contains(&"triage".to_string()));
2288        assert!(!sim.is_complete());
2289
2290        // A safety intent fires -> the `safety` digression drives this turn,
2291        // and its hand-off instruction is what the model is told.
2292        sim.set("intent:abuse", true);
2293        sim.turn();
2294        assert_eq!(sim.active_overlay(), Some("safety"));
2295        assert!(!sim.is_complete());
2296        assert!(
2297            sim.postures()
2298                .iter()
2299                .any(|p| p.contains("hand off to a human")),
2300            "{:?}",
2301            sim.postures()
2302        );
2303
2304        // Next boundary: the conversation has terminated.
2305        sim.turn();
2306        assert!(sim.is_complete());
2307        assert!(sim.active().is_empty());
2308    }
2309
2310    /// The user changes a detail after confirming: the confirmation is
2311    /// withdrawn and the commit is blocked until they confirm again.
2312    #[tokio::test]
2313    async fn a_corrected_slot_reopens_the_confirmation() {
2314        use crate::simulation::{Scenario, SimStep};
2315        use serde_json::json;
2316        let convo = Conversation::new("booking")
2317            .stage("collect")
2318            .collect(["party_size"])
2319            .stage("book")
2320            .after("collect")
2321            .commit("book_table", Guard::is_true("confirmed"))
2322            .complete_when(Guard::called_ok("book_table"))
2323            .stage("end")
2324            .after("book")
2325            .terminal()
2326            .compile()
2327            .unwrap();
2328        assert_eq!(
2329            convo.correction_policies()["party_size"],
2330            ["confirmed"],
2331            "a correction to party_size clears the booking confirmation"
2332        );
2333
2334        let set = |key: &str, value: serde_json::Value| SimStep::Set {
2335            key: key.into(),
2336            value,
2337        };
2338        let scenario = Scenario {
2339            name: "correction".into(),
2340            steps: vec![
2341                set("party_size", json!(4)),
2342                SimStep::Turn,
2343                SimStep::ExpectActive(vec!["book".into()]),
2344                set("confirmed", json!(true)),
2345                SimStep::Turn,
2346                SimStep::ExpectAllowed("book_table".into()),
2347                // "Actually, make it five."
2348                set("party_size", json!(5)),
2349                SimStep::Turn,
2350                SimStep::ExpectDenied("book_table".into()),
2351                SimStep::ExpectActive(vec!["book".into()]),
2352                set("confirmed", json!(true)),
2353                SimStep::Turn,
2354                SimStep::ExpectAllowed("book_table".into()),
2355                SimStep::ToolOk("book_table".into()),
2356                SimStep::ExpectComplete,
2357            ],
2358        };
2359        scenario.run(&convo, Enforcement::Enforce).await.unwrap();
2360    }
2361
2362    /// Repeated barge-ins escalate a stage to its hand-off.
2363    #[tokio::test]
2364    async fn repeated_barge_ins_escalate_to_the_handoff() {
2365        use crate::simulation::{Scenario, SimStep};
2366        let convo = Conversation::new("support")
2367            .stage("collect")
2368            .collect(["issue"])
2369            .repair(
2370                RepairPolicy::new(10, 10)
2371                    .escalate_after_interruptions(2)
2372                    .escalate_to("handoff"),
2373            )
2374            .stage("handoff")
2375            .terminal()
2376            .compile()
2377            .unwrap();
2378        let scenario = Scenario {
2379            name: "barge-ins".into(),
2380            steps: vec![
2381                SimStep::Turn,
2382                SimStep::ExpectActive(vec!["collect".into()]),
2383                SimStep::Interrupt,
2384                SimStep::Turn,
2385                SimStep::ExpectActive(vec!["collect".into()]),
2386                SimStep::Interrupt,
2387                SimStep::ExpectSlot {
2388                    key: escalate_flag("collect"),
2389                    value: serde_json::json!(true),
2390                },
2391                SimStep::Turn,
2392                // The terminal hand-off completes the conversation.
2393                SimStep::ExpectComplete,
2394            ],
2395        };
2396        scenario.run(&convo, Enforcement::Enforce).await.unwrap();
2397    }
2398
2399    #[test]
2400    fn stage_timing_round_trips_and_reaches_the_stack() {
2401        use std::time::Duration;
2402        let convo = Conversation::new("pacing")
2403            .stage("ask")
2404            .collect(["name"])
2405            .timing(VoiceTiming::new().reprompt_after(Duration::from_secs(6)))
2406            .add_stage(crate::motifs::Motif::disclosure("terms", "terms_ack"))
2407            .compile()
2408            .unwrap();
2409
2410        let json = serde_json::to_value(convo.spec()).unwrap();
2411        assert_eq!(json["stages"][0]["timing"]["reprompt_after_ms"], 6000);
2412        assert_eq!(json["stages"][1]["timing"]["interruptible"], false);
2413        let back: ConversationSpec = serde_json::from_value(json).unwrap();
2414        assert_eq!(
2415            back.stages[0].timing,
2416            Some(VoiceTiming::new().reprompt_after(Duration::from_secs(6)))
2417        );
2418
2419        assert!(convo.timing_policies()["terms"].holds_floor());
2420        let stack = convo.stack(Enforcement::Enforce);
2421        assert_eq!(stack.timing_policies().len(), 2);
2422    }
2423
2424    #[test]
2425    fn converse_keeps_timings_and_policies_set_on_the_builder() {
2426        use std::time::Duration;
2427        let convo = Conversation::new("pacing")
2428            .stage("ask")
2429            .collect(["name"])
2430            .timing(VoiceTiming::new().reprompt_after(Duration::from_secs(6)))
2431            .stage("done")
2432            .after("ask")
2433            .terminal()
2434            .policy(crate::policy::Policy::redact(["card"]))
2435            .compile()
2436            .unwrap();
2437        let mine = VoiceTiming::new().reprompt_after(Duration::from_secs(3));
2438
2439        // Before and after `converse`, the builder's own settings survive.
2440        for live in [
2441            crate::live::Live::builder()
2442                .stage_timing("ask", mine.clone())
2443                .policy(crate::policy::Policy::redact(["ssn"]))
2444                .converse(&convo),
2445            crate::live::Live::builder()
2446                .converse(&convo)
2447                .stage_timing("ask", mine.clone())
2448                .policy(crate::policy::Policy::redact(["ssn"])),
2449        ] {
2450            assert_eq!(live.stage_timings["ask"], mine);
2451            assert_eq!(live.policies.len(), 2, "{:?}", live.policies);
2452        }
2453    }
2454
2455    #[tokio::test]
2456    async fn repair_reprompts_then_escalates_to_handoff() {
2457        use crate::simulation::Sim;
2458
2459        // `collect` needs `info`; if the user stalls, reprompt after 2 turns and
2460        // escalate (route to `handoff`) after 3.
2461        let convo = Conversation::new("support")
2462            .stage("collect")
2463            .complete_when(Guard::is_true("info"))
2464            .next("done", Guard::is_true("info"))
2465            .repair(RepairPolicy::new(2, 3).escalate_to("handoff"))
2466            .stage("done")
2467            .terminal()
2468            // Non-terminal so it stays *active* (terminal stages latch instantly).
2469            .stage("handoff")
2470            .complete_when(Guard::is_true("handoff_complete"))
2471            .compile()
2472            .expect("compiles");
2473
2474        let mut sim = Sim::new(&convo, Enforcement::Enforce);
2475        assert!(sim.active().contains(&"collect".to_string()));
2476
2477        // User stalls. Turn 1 active: no signal yet.
2478        sim.turn();
2479        assert_eq!(sim.slot::<bool>("repair:collect:reprompt"), None);
2480        // Turn 2 active: reprompt raised.
2481        sim.turn();
2482        assert_eq!(sim.slot::<bool>("repair:collect:reprompt"), Some(true));
2483        assert!(sim.active().contains(&"collect".to_string()));
2484        // Turn 3 active: escalate raised -> stage completes via escalation -> handoff.
2485        sim.turn();
2486        assert_eq!(sim.slot::<bool>("repair:collect:escalate"), Some(true));
2487        assert!(sim.active().contains(&"handoff".to_string()));
2488        assert!(!sim.active().contains(&"collect".to_string()));
2489    }
2490
2491    #[tokio::test]
2492    async fn repair_signal_clears_when_stage_satisfied() {
2493        use crate::simulation::Sim;
2494
2495        let convo = Conversation::new("s")
2496            .stage("collect")
2497            .complete_when(Guard::is_true("info"))
2498            .next("done", Guard::is_true("info"))
2499            .repair(RepairPolicy::new(1, 9))
2500            .stage("done")
2501            .terminal()
2502            .require(["done"])
2503            .compile()
2504            .expect("compiles");
2505
2506        let mut sim = Sim::new(&convo, Enforcement::Enforce);
2507        sim.turn(); // active 1 turn -> reprompt (threshold 1)
2508        assert_eq!(sim.slot::<bool>("repair:collect:reprompt"), Some(true));
2509
2510        // User provides info -> collect completes this turn; the signal clears the
2511        // following turn (once the stage is observed no longer active).
2512        sim.set("info", true);
2513        sim.turn();
2514        sim.turn();
2515        assert_eq!(sim.slot::<bool>("repair:collect:reprompt"), Some(false));
2516        assert!(sim.is_complete());
2517    }
2518
2519    #[test]
2520    fn rejects_transition_to_unknown_stage() {
2521        let err = Conversation::new("x")
2522            .stage("a")
2523            .next("ghost", Guard::always())
2524            .stage("b")
2525            .terminal()
2526            .compile()
2527            .expect_err("unknown target must fail");
2528        assert!(matches!(err, ConversationError::Spec(_)));
2529    }
2530
2531    #[test]
2532    fn rejects_unguarded_commit_via_flow_compile() {
2533        // commit guarded by Always is an unguarded commit — Flow::compile rejects it.
2534        let err = Conversation::new("x")
2535            .stage("s")
2536            .commit("pay", Guard::always())
2537            .complete_when(Guard::called_ok("pay"))
2538            .next("done", Guard::called_ok("pay"))
2539            .stage("done")
2540            .terminal()
2541            .compile()
2542            .expect_err("unguarded commit must fail");
2543        assert!(matches!(err, ConversationError::Compile(_)));
2544    }
2545
2546    #[test]
2547    fn stage_ids_must_be_unique_across_main_and_overlays() {
2548        let error = Conversation::new("collision")
2549            .stage("shared")
2550            .terminal()
2551            .overlay("faq")
2552            .trigger(Guard::is_true("intent:faq"))
2553            .stage("shared")
2554            .terminal()
2555            .end_overlay()
2556            .compile()
2557            .expect_err("a stage cannot have two owners");
2558        assert!(matches!(error, ConversationError::Spec(message)
2559            if message.contains("duplicate stage ids")
2560                && message.contains("shared")
2561                && message.contains("main flow")
2562                && message.contains("overlay 'faq'")));
2563    }
2564
2565    #[test]
2566    fn stage_ids_must_be_unique_between_overlays() {
2567        let error = Conversation::new("collision")
2568            .stage("main")
2569            .terminal()
2570            .overlay("faq")
2571            .trigger(Guard::is_true("intent:faq"))
2572            .stage("shared")
2573            .terminal()
2574            .end_overlay()
2575            .overlay("clarify")
2576            .trigger(Guard::is_true("intent:clarify"))
2577            .stage("shared")
2578            .terminal()
2579            .end_overlay()
2580            .compile()
2581            .expect_err("overlays cannot share stage identity");
2582        assert!(matches!(error, ConversationError::Spec(message)
2583            if message.contains("shared")
2584                && message.contains("overlay 'faq'")
2585                && message.contains("overlay 'clarify'")));
2586    }
2587
2588    #[test]
2589    fn overlay_names_must_be_unique() {
2590        let error = Conversation::new("collision")
2591            .stage("main")
2592            .terminal()
2593            .overlay("faq")
2594            .trigger(Guard::is_true("intent:faq"))
2595            .stage("answer")
2596            .terminal()
2597            .end_overlay()
2598            .overlay("faq")
2599            .trigger(Guard::is_true("intent:other_faq"))
2600            .stage("other_answer")
2601            .terminal()
2602            .end_overlay()
2603            .compile()
2604            .expect_err("overlay names select active layers");
2605        assert!(matches!(error, ConversationError::Spec(message)
2606            if message == "duplicate overlay name 'faq'"));
2607    }
2608
2609    #[test]
2610    fn generated_safety_overlay_cannot_collide_with_authored_names_or_stages() {
2611        use crate::policy::Policy;
2612
2613        let error = Conversation::new("collision")
2614            .stage("main")
2615            .terminal()
2616            .overlay("safety")
2617            .trigger(Guard::is_true("intent:custom_safety"))
2618            .stage("custom_handoff")
2619            .terminal()
2620            .end_overlay()
2621            .policy(Policy::safety_handoff(["self_harm"]))
2622            .compile()
2623            .expect_err("generated safety overlay requires a unique name");
2624        assert!(matches!(error, ConversationError::Spec(message)
2625            if message == "duplicate overlay name 'safety'"));
2626
2627        let error = Conversation::new("collision")
2628            .stage("safety_handoff")
2629            .terminal()
2630            .policy(Policy::safety_handoff(["self_harm"]))
2631            .compile()
2632            .expect_err("generated safety stage requires a unique id");
2633        assert!(matches!(error, ConversationError::Spec(message)
2634            if message.contains("safety_handoff")
2635                && message.contains("main flow")
2636                && message.contains("overlay 'safety'")));
2637    }
2638
2639    #[test]
2640    fn duplicate_stage_ids_within_one_layer_remain_invalid() {
2641        let error = Conversation::new("collision")
2642            .stage("shared")
2643            .terminal()
2644            .stage("shared")
2645            .terminal()
2646            .compile()
2647            .expect_err("local duplicate stages remain invalid");
2648        assert!(matches!(error, ConversationError::Spec(message)
2649            if message.contains("duplicate stage ids")));
2650    }
2651
2652    #[test]
2653    fn compiled_safety_spec_can_be_serialized_and_compiled_again() {
2654        use crate::policy::Policy;
2655
2656        let compiled = Conversation::new("safety")
2657            .stage("main")
2658            .terminal()
2659            .policy(Policy::safety_handoff(["self_harm"]))
2660            .compile()
2661            .expect("compiles");
2662        assert_eq!(compiled.overlays().len(), 1);
2663        let value = serde_json::to_value(compiled.spec()).expect("serializes");
2664        let spec = serde_json::from_value(value).expect("parses");
2665        let recompiled = Conversation::from_spec(spec).expect("recompiles");
2666        assert_eq!(recompiled.overlays().len(), 1);
2667        assert_eq!(recompiled.overlays()[0].name, "safety");
2668    }
2669}