Skip to main content

gemini_adk_rs/flow/
stack.rs

1//! `FlowStack` — the runtime above the DAG: a main flow plus its digressions.
2//!
3//! A [`FlowMonitor`] governs one [`Flow`]. Real conversations
4//! leave the main task temporarily — a side question, a cancel, a hand-off —
5//! and expect to come back to it. A [`FlowStack`] holds the **main** monitor
6//! plus a set of [`Overlay`]s (digressions): when an overlay's trigger holds,
7//! the main flow is suspended untouched, the overlay's own monitor drives the
8//! session until it completes, and the main flow then continues per the
9//! overlay's [`Resume`] policy.
10//!
11//! This is the *only* governance object the Live control plane drives. A
12//! session governed by a bare flow is a stack with no overlays, so every
13//! execution path — the simulator, a live session, a replay — advances the same
14//! type with the same semantics. The authoring layer lowers a conversation into
15//! a stack; it does not implement one.
16//!
17//! Digressions nest: a digression can itself be interrupted by another (one
18//! not already on the active path), which drives until it completes and then
19//! resumes the one beneath it per its own [`Resume`] policy.
20
21use std::collections::{BTreeMap, BTreeSet};
22use std::sync::Arc;
23
24use serde::{Deserialize, Serialize};
25
26use super::timing::{VOICE_TIMING_KEY, VoiceTiming};
27use super::{
28    CompiledFlow, Enforcement, Flow, FlowExplanation, FlowMonitor, FlowSnapshot, Guard, Marking,
29    Step, StepAction,
30};
31use crate::state::State;
32
33/// The state key raised when a stage's repair policy escalates.
34pub fn escalate_flag(stage: &str) -> String {
35    format!("repair:{stage}:escalate")
36}
37
38/// The state key raised when a stage's repair policy asks for a reprompt.
39pub fn reprompt_flag(stage: &str) -> String {
40    format!("repair:{stage}:reprompt")
41}
42
43/// The state key raised for one turn when the user corrects `slot`: its
44/// value changed from one captured value to another. See
45/// [`FlowStack::with_correction`].
46pub fn correction_flag(slot: &str) -> String {
47    format!("correction:{slot}")
48}
49
50/// Written when the governed flow admits a tool call, before it runs:
51/// `{"tool": name, "id": call id}`. With [`TOOL_DENIED_KEY`] and
52/// [`TOOL_RESULT_KEY`] it puts every governance decision about a tool in the
53/// mutation journal, in order, which is what makes a recorded session
54/// replayable as a scenario.
55pub const TOOL_CALL_KEY: &str = "flow:tool_call";
56
57/// Written when the governed flow refuses a tool call:
58/// `{"tool": name, "id": call id, "reason": why}`.
59pub const TOOL_DENIED_KEY: &str = "flow:tool_denied";
60
61/// Written when an admitted tool call completes:
62/// `{"tool": name, "id": call id, "ok": succeeded}`.
63pub const TOOL_RESULT_KEY: &str = "flow:tool_result";
64
65/// The state key that names the active digression (`null` when the main flow
66/// is driving). Published by the control plane at every turn boundary.
67pub const OVERLAY_STATE_KEY: &str = "flow:overlay";
68
69/// The state key raised (`true`) once a [`Resume::Terminate`] digression has
70/// ended the conversation. Governance is inert from then on: no postures, no
71/// admitted tools. The runtime does not hang up by itself — the application
72/// decides how a call ends — so watch this key (or
73/// [`FlowStack::is_terminated`]) and close the session. Published by the
74/// control plane at every turn boundary.
75pub const TERMINATED_STATE_KEY: &str = "flow:terminated";
76
77/// How the main flow continues after a digression (overlay) completes.
78///
79/// `Restart` resets the main flow's *monitor* — its marking, fired `on_enter`
80/// actions and reset edges — against the session's existing `State`. It does
81/// not clear state, so slots the user already filled stay filled. It is a
82/// fresh pass over the same conversation, not a fresh business task.
83#[derive(
84    Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, schemars::JsonSchema,
85)]
86#[serde(rename_all = "snake_case")]
87pub enum Resume {
88    /// Resume the main flow exactly where it was suspended (history state).
89    #[default]
90    Previous,
91    /// Re-enter the main flow from its start (see the type docs for what that
92    /// does and does not reset). Repair signals and counters are cleared with
93    /// the marking: a fresh pass starts with no step already escalated.
94    Restart,
95    /// End the conversation (e.g. a cancel/handoff digression). From the next
96    /// turn boundary the stack governs nothing: see
97    /// [`FlowStack::is_terminated`] and [`TERMINATED_STATE_KEY`].
98    Terminate,
99}
100
101fn default_reprompt_after() -> u32 {
102    2
103}
104fn default_escalate_after() -> u32 {
105    4
106}
107
108/// A step's repair policy for the weird paths (silence, no-match, the user
109/// stalling). The stack sets `repair:{step}:reprompt` once the step has been
110/// active `reprompt_after` turns without completing, and `repair:{step}:escalate`
111/// after `escalate_after`. When `escalate_to` is set, the authoring layer lowers
112/// an extra edge gated on the escalate signal — a deterministic "give up and
113/// hand off".
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
115pub struct RepairPolicy {
116    /// Turns the step may be active before a reprompt signal is raised.
117    #[serde(default = "default_reprompt_after")]
118    pub reprompt_after: u32,
119    /// Turns the step may be active before an escalation signal is raised.
120    #[serde(default = "default_escalate_after")]
121    pub escalate_after: u32,
122    /// Step to route to on escalation (also completes the current step).
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    pub escalate_to: Option<String>,
125    /// Escalate once the user has barged in this many times while the step
126    /// is active (they keep cutting the model off: it is not working).
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub escalate_after_interruptions: Option<u32>,
129    /// Escalate once this many tool calls have failed or timed out while
130    /// the step is active.
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub escalate_after_tool_failures: Option<u32>,
133}
134
135impl Default for RepairPolicy {
136    fn default() -> Self {
137        Self {
138            reprompt_after: default_reprompt_after(),
139            escalate_after: default_escalate_after(),
140            escalate_to: None,
141            escalate_after_interruptions: None,
142            escalate_after_tool_failures: None,
143        }
144    }
145}
146
147impl RepairPolicy {
148    /// A policy with the given reprompt/escalate turn thresholds.
149    pub fn new(reprompt_after: u32, escalate_after: u32) -> Self {
150        Self {
151            reprompt_after,
152            escalate_after,
153            ..Self::default()
154        }
155    }
156
157    /// Route to `step` on escalation (also completes the current step).
158    pub fn escalate_to(mut self, step: impl Into<String>) -> Self {
159        self.escalate_to = Some(step.into());
160        self
161    }
162
163    /// Also escalate after `n` barge-ins while the step is active.
164    pub fn escalate_after_interruptions(mut self, n: u32) -> Self {
165        self.escalate_after_interruptions = Some(n);
166        self
167    }
168
169    /// Also escalate after `n` failed or timed-out tool calls while the step
170    /// is active.
171    pub fn escalate_after_tool_failures(mut self, n: u32) -> Self {
172        self.escalate_after_tool_failures = Some(n);
173        self
174    }
175}
176
177/// A digression the runtime can enter: its trigger, governed flow and resume
178/// policy. Built from a compiled flow so it carries proof of compilation.
179#[derive(Debug, Clone)]
180pub struct Overlay {
181    name: String,
182    trigger: Guard,
183    flow: Flow,
184    resume: Resume,
185}
186
187impl Overlay {
188    /// A digression over a compiled flow.
189    pub fn new(
190        name: impl Into<String>,
191        trigger: Guard,
192        flow: CompiledFlow,
193        resume: Resume,
194    ) -> Self {
195        Self {
196            name: name.into(),
197            trigger,
198            flow: flow.into_flow(),
199            resume,
200        }
201    }
202
203    /// The digression's name.
204    pub fn name(&self) -> &str {
205        &self.name
206    }
207    /// The guard that activates it, evaluated against the main flow's context.
208    pub fn trigger(&self) -> &Guard {
209        &self.trigger
210    }
211    /// The digression's governed flow.
212    pub fn flow(&self) -> &Flow {
213        &self.flow
214    }
215    /// Mutable access to the flow, for connect-time merges (ambient tools).
216    pub fn flow_mut(&mut self) -> &mut Flow {
217        &mut self.flow
218    }
219    /// What the main flow does once this digression completes.
220    pub fn resume(&self) -> Resume {
221        self.resume
222    }
223}
224
225/// A digression currently suspending the main flow.
226struct ActiveOverlay {
227    name: String,
228    monitor: FlowMonitor,
229    resume: Resume,
230}
231
232/// See [`FlowStack::decision_scope`].
233#[derive(Debug, Clone, Default, PartialEq, Eq)]
234pub struct DecisionScope {
235    /// Questions named by the driving layer's guards and the enterable
236    /// digressions' triggers.
237    pub questions: BTreeSet<String>,
238    /// State keys the active steps' guards and those triggers read.
239    pub reads: BTreeSet<String>,
240}
241
242/// A shared, lock-protected [`FlowStack`] — the form in which the Live
243/// control plane owns governance, so runtime surfaces (e.g.
244/// [`LiveHandle::explain`](crate::live::LiveHandle::explain)) can snapshot it
245/// concurrently. All methods are synchronous: lock briefly and never hold the
246/// guard across an `await`.
247pub type SharedFlowStack = Arc<parking_lot::Mutex<FlowStack>>;
248
249/// The main flow plus its digressions, with push-on-trigger and
250/// resume-on-completion.
251///
252/// While a digression is active, governance — tool admission, postures and
253/// grounds, `explain()` — delegates to the **active** layer, and the main
254/// flow's marking is untouched, so [`Resume::Previous`] resumes exactly where
255/// it left off. Driven by `State` and guards: model-free and deterministic.
256///
257/// A digression stays the active layer through the turn on which it
258/// completes, so that turn's projection carries its closing instruction (the
259/// terminal stage's posture — "hand off to a human now"), and its
260/// [`Resume`] policy applies at the *next* turn boundary. Without that, a
261/// digression that completes on its entry turn would never be seen at all.
262pub struct FlowStack {
263    main: FlowMonitor,
264    mode: Enforcement,
265    overlays: Vec<Overlay>,
266    /// The digressions suspending the main flow, outermost first. The last
267    /// one drives; each suspends the one beneath it.
268    active: Vec<ActiveOverlay>,
269    /// The digression that ended the conversation, once one has.
270    terminated: Option<String>,
271    /// Per-main-step repair policies.
272    repair: BTreeMap<String, RepairPolicy>,
273    /// Consecutive turns each main step has been active without completing.
274    active_turns: BTreeMap<String, u32>,
275    /// Per-step voice timing, keyed by step id in whichever layer is active.
276    timing: BTreeMap<String, VoiceTiming>,
277    /// Slots whose correction re-opens later stages, with the state keys to
278    /// clear when that happens (e.g. the confirmation of a commit stage).
279    corrections: BTreeMap<String, Vec<String>>,
280    /// The last value seen for each watched slot.
281    slot_values: BTreeMap<String, serde_json::Value>,
282    /// Text each step must have said word for word.
283    verbatim: BTreeMap<String, String>,
284    /// Barge-ins each main step has seen while active.
285    interruptions: BTreeMap<String, u32>,
286    /// Failed tool calls each main step has seen while active.
287    tool_failures: BTreeMap<String, u32>,
288}
289
290impl std::fmt::Debug for FlowStack {
291    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
292        f.debug_struct("FlowStack")
293            .field("mode", &self.mode)
294            .field("overlays", &self.overlays.len())
295            .field(
296                "active",
297                &self.active.iter().map(|a| &a.name).collect::<Vec<_>>(),
298            )
299            .field("terminated", &self.terminated)
300            .field("repair", &self.repair)
301            .field("timing", &self.timing)
302            .field("corrections", &self.corrections)
303            .finish()
304    }
305}
306
307impl FlowStack {
308    /// A stack over a compiled main flow with no digressions yet.
309    pub fn new(main: CompiledFlow, mode: Enforcement) -> Self {
310        Self::from_monitor(FlowMonitor::compiled(main, mode))
311    }
312
313    /// A stack whose main layer is an existing monitor (keeps its `on_enter`
314    /// actions and mode). This is how a bare governed flow becomes the one
315    /// governance object the control plane drives.
316    pub fn from_monitor(main: FlowMonitor) -> Self {
317        Self {
318            mode: main.mode(),
319            main,
320            overlays: Vec::new(),
321            active: Vec::new(),
322            terminated: None,
323            repair: BTreeMap::new(),
324            active_turns: BTreeMap::new(),
325            timing: BTreeMap::new(),
326            corrections: BTreeMap::new(),
327            verbatim: BTreeMap::new(),
328            slot_values: BTreeMap::new(),
329            interruptions: BTreeMap::new(),
330            tool_failures: BTreeMap::new(),
331        }
332    }
333
334    /// Add a digression.
335    pub fn with_overlay(mut self, overlay: Overlay) -> Self {
336        self.overlays.push(overlay);
337        self
338    }
339
340    /// Add several digressions, in trigger-priority order.
341    pub fn with_overlays(mut self, overlays: impl IntoIterator<Item = Overlay>) -> Self {
342        self.overlays.extend(overlays);
343        self
344    }
345
346    /// Admit installed service tools in the main flow and every digression.
347    /// Tool-specific constraints still apply. Call this after adding overlays
348    /// when constructing a stack, before it starts processing events.
349    pub fn with_ambient_tools(mut self, tools: impl IntoIterator<Item = String>) -> Self {
350        let tools: Vec<_> = tools.into_iter().collect();
351        let extend = |flow: &mut Flow| {
352            for name in &tools {
353                if !flow.ambient.contains(name) {
354                    flow.ambient.push(name.clone());
355                }
356            }
357        };
358        extend(&mut self.main.flow);
359        for overlay in &mut self.overlays {
360            extend(&mut overlay.flow);
361        }
362        for active in &mut self.active {
363            extend(&mut active.monitor.flow);
364        }
365        self
366    }
367
368    /// Attach a repair policy to a main-flow step.
369    pub fn with_repair(mut self, step: impl Into<String>, policy: RepairPolicy) -> Self {
370        self.repair.insert(step.into(), policy);
371        self
372    }
373
374    /// Attach repair policies keyed by main-flow step.
375    pub fn with_repairs(
376        mut self,
377        policies: impl IntoIterator<Item = (String, RepairPolicy)>,
378    ) -> Self {
379        self.repair.extend(policies);
380        self
381    }
382
383    /// Watch `slot` for corrections: when its value changes from one captured
384    /// value to another, [`correction_flag`]`(slot)` is raised for that turn
385    /// and `clear` keys are removed from state.
386    ///
387    /// Raising the flag does nothing by itself. The main flow reacts through
388    /// a [`Constraint::Reset`](super::Constraint::Reset) gated on it, which
389    /// un-latches the stages downstream of the slot so they run again with
390    /// the corrected value. A `Conversation` lowers exactly that for every
391    /// collected slot, clearing the confirmation of any commit stage it
392    /// re-opens.
393    pub fn with_correction(
394        mut self,
395        slot: impl Into<String>,
396        clear: impl IntoIterator<Item = String>,
397    ) -> Self {
398        self.corrections
399            .insert(slot.into(), clear.into_iter().collect());
400        self
401    }
402
403    /// Watch several slots; see [`with_correction`](Self::with_correction).
404    pub fn with_corrections(
405        mut self,
406        corrections: impl IntoIterator<Item = (String, Vec<String>)>,
407    ) -> Self {
408        self.corrections.extend(corrections);
409        self
410    }
411
412    /// The watched slots and the keys each correction clears.
413    pub fn correction_policies(&self) -> &BTreeMap<String, Vec<String>> {
414        &self.corrections
415    }
416
417    /// Require `step` to say `text` word for word; see
418    /// [`verbatim`](super::verbatim). The stack publishes the requirement
419    /// while the step is active. Its completion guard must also require
420    /// [`verbatim_flag`](super::verbatim_flag)`(step)`, which a
421    /// `Conversation` lowers for you.
422    pub fn with_verbatim(mut self, step: impl Into<String>, text: impl Into<String>) -> Self {
423        self.verbatim.insert(step.into(), text.into());
424        self
425    }
426
427    /// Verbatim requirements keyed by step.
428    pub fn with_verbatims(mut self, texts: impl IntoIterator<Item = (String, String)>) -> Self {
429        self.verbatim.extend(texts);
430        self
431    }
432
433    /// The verbatim requirements keyed by step.
434    pub fn verbatim_policies(&self) -> &BTreeMap<String, String> {
435        &self.verbatim
436    }
437
438    /// Attach voice timing to a step (main flow or digression).
439    pub fn with_timing(mut self, step: impl Into<String>, timing: VoiceTiming) -> Self {
440        self.timing.insert(step.into(), timing);
441        self
442    }
443
444    /// Attach voice timing keyed by step.
445    pub fn with_timings(
446        mut self,
447        timings: impl IntoIterator<Item = (String, VoiceTiming)>,
448    ) -> Self {
449        self.timing.extend(timings);
450        self
451    }
452
453    /// The voice timing keyed by step.
454    pub fn timing_policies(&self) -> &BTreeMap<String, VoiceTiming> {
455        &self.timing
456    }
457
458    /// The merged timing of the steps active right now in the driving layer
459    /// (empty when none of them has timing, or the conversation is over).
460    pub fn active_timing(&self, state: &State) -> VoiceTiming {
461        if self.timing.is_empty() || self.terminated.is_some() {
462            return VoiceTiming::default();
463        }
464        self.current()
465            .active_steps(state)
466            .iter()
467            .filter_map(|step| self.timing.get(&step.id))
468            .fold(VoiceTiming::default(), |acc, t| acc.merge(t))
469    }
470
471    /// Publish [`active_timing`](Self::active_timing) to
472    /// [`VOICE_TIMING_KEY`] in state, where the runtime's audio path, timers
473    /// and turn lifecycle read it. Writes only on change; removes the key
474    /// when no timing applies. The stack calls this itself after every turn
475    /// and tool call; call it once when installing the stack.
476    pub fn publish_timing(&self, state: &State) {
477        self.publish_verbatim(state);
478        if self.timing.is_empty() {
479            return;
480        }
481        let timing = self.active_timing(state);
482        let current = state.get::<VoiceTiming>(VOICE_TIMING_KEY);
483        if timing.is_empty() {
484            if current.is_some() {
485                state.remove(VOICE_TIMING_KEY);
486            }
487        } else if current.as_ref() != Some(&timing) {
488            let _ = state.set(VOICE_TIMING_KEY, &timing);
489        }
490    }
491
492    /// Publish the active step's verbatim requirement to
493    /// [`VERBATIM_KEY`](super::VERBATIM_KEY), or remove it when no active step
494    /// has one. Called with [`publish_timing`](Self::publish_timing).
495    fn publish_verbatim(&self, state: &State) {
496        if self.verbatim.is_empty() {
497            return;
498        }
499        let required = (self.terminated.is_none())
500            .then(|| {
501                self.current().active_steps(state).iter().find_map(|step| {
502                    self.verbatim
503                        .get(&step.id)
504                        .map(|text| super::VerbatimRequirement {
505                            step: step.id.clone(),
506                            text: text.clone(),
507                        })
508                })
509            })
510            .flatten();
511        let current = state.get::<super::VerbatimRequirement>(super::VERBATIM_KEY);
512        match required {
513            Some(req) if current.as_ref() != Some(&req) => {
514                let _ = state.set(super::VERBATIM_KEY, &req);
515            }
516            None if current.is_some() => {
517                state.remove(super::VERBATIM_KEY);
518            }
519            _ => {}
520        }
521    }
522
523    /// Wrap in a [`SharedFlowStack`] for shared ownership between the control
524    /// lane (which advances it) and runtime accessors (which snapshot it).
525    pub fn into_shared(self) -> SharedFlowStack {
526        Arc::new(parking_lot::Mutex::new(self))
527    }
528
529    /// The enforcement mode (shared by every layer).
530    pub fn mode(&self) -> Enforcement {
531        self.mode
532    }
533
534    /// The digressions this stack can enter, in trigger-priority order.
535    pub fn overlays(&self) -> &[Overlay] {
536        &self.overlays
537    }
538
539    /// Mutable access to the digressions, for connect-time merges.
540    pub fn overlays_mut(&mut self) -> &mut [Overlay] {
541        &mut self.overlays
542    }
543
544    /// The repair policies keyed by main-flow step.
545    pub fn repair_policies(&self) -> &BTreeMap<String, RepairPolicy> {
546        &self.repair
547    }
548
549    /// The main flow's monitor, whether or not it is currently driving.
550    pub fn main(&self) -> &FlowMonitor {
551        &self.main
552    }
553
554    /// The monitor currently driving — the active digression if any, else the
555    /// main flow.
556    pub fn current(&self) -> &FlowMonitor {
557        self.active.last().map_or(&self.main, |a| &a.monitor)
558    }
559
560    fn current_mut(&mut self) -> &mut FlowMonitor {
561        match self.active.last_mut() {
562            Some(a) => &mut a.monitor,
563            None => &mut self.main,
564        }
565    }
566
567    /// The name of the driving digression, if one is suspending the main flow.
568    pub fn active_overlay(&self) -> Option<&str> {
569        self.active.last().map(|a| a.name.as_str())
570    }
571
572    /// Every active digression, outermost first: a digression can itself be
573    /// interrupted by another, which then drives until it completes.
574    pub fn overlay_path(&self) -> Vec<&str> {
575        self.active.iter().map(|a| a.name.as_str()).collect()
576    }
577
578    /// Whether the conversation is finished (main complete, or a `Terminate`
579    /// digression ran).
580    pub fn is_complete(&self) -> bool {
581        self.terminated.is_some() || (self.active.is_empty() && self.main.is_complete())
582    }
583
584    /// Whether a `Terminate` digression ended the conversation. From then on
585    /// the stack governs nothing: no active steps or postures, every tool
586    /// denied. The runtime does not close the session by itself; the
587    /// application reads this (or [`TERMINATED_STATE_KEY`]) and hangs up.
588    pub fn is_terminated(&self) -> bool {
589        self.terminated.is_some()
590    }
591
592    /// Why a tool is denied once the conversation has ended.
593    fn termination_denial(&self) -> Option<String> {
594        self.terminated
595            .as_ref()
596            .map(|by| format!("the conversation has ended: digression `{by}` terminated it"))
597    }
598
599    /// Whether the active digression has run to completion and is being
600    /// projected for its closing turn.
601    fn active_is_closing(&self) -> bool {
602        self.active.last().is_some_and(|a| a.monitor.is_complete())
603    }
604
605    /// Index of the first overlay whose trigger holds against the main
606    /// context and that is not already on the active path (a digression
607    /// cannot interrupt itself).
608    fn triggered(&self, state: &State) -> Option<usize> {
609        self.overlays.iter().position(|ov| {
610            !self.active.iter().any(|a| a.name == ov.name) && self.main.eval(&ov.trigger, state)
611        })
612    }
613
614    /// Enter overlay `idx` on top of the active path, driving its first turn
615    /// so single-step overlays latch. If that completes it, it still stays
616    /// active for this turn's projection (see the type docs).
617    fn enter(&mut self, idx: usize, state: &State) {
618        let ov = &self.overlays[idx];
619        let mut monitor = FlowMonitor::new(ov.flow.clone(), self.mode);
620        monitor.on_turn(state);
621        self.active.push(ActiveOverlay {
622            name: ov.name.clone(),
623            monitor,
624            resume: ov.resume,
625        });
626    }
627
628    /// Raise the correction flag of every watched slot whose value changed
629    /// from one captured value to another since the last turn, clearing the
630    /// keys its rule names. A re-statement in different case, spacing or
631    /// punctuation is not a change (see
632    /// [`equivalent_values`](crate::state::equivalent_values)). The main
633    /// flow lowers the flags once it has advanced past them.
634    fn detect_corrections(&mut self, state: &State) {
635        if self.corrections.is_empty() {
636            return;
637        }
638        for (slot, clear) in &self.corrections {
639            let current = state.get_raw(slot);
640            let corrected = matches!(
641                (self.slot_values.get(slot), &current),
642                (Some(before), Some(now)) if !crate::state::equivalent_values(before, now)
643            );
644            if corrected {
645                let _ = state.set(correction_flag(slot), true);
646                for key in clear {
647                    state.remove(key);
648                }
649            }
650            match current {
651                Some(v) => {
652                    self.slot_values.insert(slot.clone(), v);
653                }
654                None => {
655                    self.slot_values.remove(slot);
656                }
657            }
658        }
659    }
660
661    /// Count a barge-in against every active main step and escalate those
662    /// whose policy's `escalate_after_interruptions` is reached. Called by
663    /// the control plane when the user interrupts the model.
664    pub fn on_interrupted(&mut self, state: &State) {
665        self.count_against_active(
666            state,
667            |p| p.escalate_after_interruptions,
668            |s| &mut s.interruptions,
669        );
670    }
671
672    /// Count a failed (or timed-out) tool call against every active main step
673    /// and escalate those whose policy's `escalate_after_tool_failures` is
674    /// reached.
675    pub fn on_tool_failed(&mut self, state: &State) {
676        self.count_against_active(
677            state,
678            |p| p.escalate_after_tool_failures,
679            |s| &mut s.tool_failures,
680        );
681    }
682
683    fn count_against_active(
684        &mut self,
685        state: &State,
686        threshold: impl Fn(&RepairPolicy) -> Option<u32>,
687        counters: impl Fn(&mut Self) -> &mut BTreeMap<String, u32>,
688    ) {
689        if self.terminated.is_some() || !self.active.is_empty() || self.repair.is_empty() {
690            return;
691        }
692        let steps: Vec<(String, u32)> = self
693            .main
694            .active_steps(state)
695            .iter()
696            .filter_map(|s| {
697                self.repair
698                    .get(&s.id)
699                    .and_then(&threshold)
700                    .map(|limit| (s.id.clone(), limit))
701            })
702            .collect();
703        for (step, limit) in steps {
704            let count = counters(self).entry(step.clone()).or_insert(0);
705            *count += 1;
706            if *count >= limit {
707                let _ = state.set(escalate_flag(&step), true);
708            }
709        }
710    }
711
712    /// Bump per-step active-turn counters for the main flow and raise repair
713    /// signals when thresholds are hit. Clears signals for steps that are no
714    /// longer active.
715    fn apply_repair(&mut self, state: &State, counted: bool) {
716        if self.repair.is_empty() {
717            return;
718        }
719        let active: BTreeSet<String> = self
720            .main
721            .active_steps(state)
722            .iter()
723            .map(|s| s.id.clone())
724            .collect();
725        let left: Vec<String> = self
726            .active_turns
727            .keys()
728            .filter(|k| !active.contains(*k))
729            .cloned()
730            .collect();
731        for step in left {
732            self.active_turns.remove(&step);
733            self.interruptions.remove(&step);
734            self.tool_failures.remove(&step);
735            let _ = state.set(reprompt_flag(&step), false);
736            // A step that completed *by escalating* must keep its escalate
737            // signal: the authoring layer lowers `escalate_to` into an edge
738            // gated on it, and gates are evaluated every turn, so clearing the
739            // flag here would drop the hand-off target out of the active set
740            // one turn after it was entered. Clear it only when the step left
741            // the active set without completing (its gate closed). Steps a
742            // `Constraint::Reset` un-latches are cleared in `advance_main`,
743            // before the re-latch can see the stale signal.
744            if !self.main.marking().done.contains(&step) {
745                let _ = state.set(escalate_flag(&step), false);
746            }
747        }
748        for step in &active {
749            let count = self.active_turns.entry(step.clone()).or_insert(0);
750            if counted {
751                *count += 1;
752            }
753            if let Some(rp) = self.repair.get(step) {
754                if *count >= rp.reprompt_after {
755                    let _ = state.set(reprompt_flag(step), true);
756                }
757                if *count >= rp.escalate_after {
758                    let _ = state.set(escalate_flag(step), true);
759                }
760            }
761        }
762    }
763
764    /// Forget everything the repair bookkeeping knows about `step`: its
765    /// active-turn count and both signals. Used when a step is un-latched (a
766    /// reset, or a restart of the whole main flow), because the lowered
767    /// `escalate_to` completion guard references the escalate signal and would
768    /// otherwise re-complete the step the moment it is re-latched.
769    fn clear_repair(&mut self, step: &str, state: &State) {
770        self.active_turns.remove(step);
771        self.interruptions.remove(step);
772        self.tool_failures.remove(step);
773        let _ = state.set(reprompt_flag(step), false);
774        let _ = state.set(escalate_flag(step), false);
775    }
776
777    /// Apply a closed digression's resume policy to the layer beneath it:
778    /// the next digression on the path, or the main flow.
779    fn apply_resume(&mut self, by: String, resume: Resume, state: &State) {
780        match resume {
781            // The suspended layer's marking was untouched — nothing to do.
782            Resume::Previous => {}
783            Resume::Restart => match self.active.last_mut() {
784                Some(beneath) => beneath.monitor.restart(),
785                None => {
786                    self.main.restart();
787                    // A fresh pass starts with no step already escalated.
788                    let steps: Vec<String> = self.repair.keys().cloned().collect();
789                    for step in steps {
790                        self.clear_repair(&step, state);
791                    }
792                }
793            },
794            Resume::Terminate => {
795                self.active.clear();
796                self.terminated = Some(by);
797            }
798        }
799    }
800
801    /// Advance the main flow one turn: resets first (shedding the repair
802    /// signals of any step they un-latch), then repair bookkeeping over the
803    /// pre-turn active set, then the re-latch.
804    fn advance_main(&mut self, state: &State, counted: bool) {
805        for step in self.main.begin_turn(state) {
806            self.clear_repair(&step, state);
807        }
808        // The main flow has now seen any correction raised since it last
809        // advanced (its reset edges fired above): lower the flags so the
810        // next correction is a fresh rising edge.
811        for slot in self.corrections.keys() {
812            let flag = correction_flag(slot);
813            if state.get::<bool>(&flag) == Some(true) {
814                let _ = state.set(&flag, false);
815            }
816        }
817        // Repair bookkeeping is based on the pre-turn active set so an
818        // escalation signal can take effect this turn.
819        self.apply_repair(state, counted);
820        self.main.relatch(state);
821    }
822
823    /// Advance one turn.
824    ///
825    /// A digression that completed on the previous turn has had its closing
826    /// turn projected; its resume policy applies now, and the turn then
827    /// proceeds as if the main flow had been driving all along (a new
828    /// digression may trigger, or the main flow advances). Otherwise: advance
829    /// the active digression, enter a triggered one (suspending the main
830    /// flow), or advance the main flow.
831    pub fn on_turn(&mut self, state: &State) {
832        self.on_turn_counted(state, true);
833    }
834
835    /// Advance one turn, saying whether it counts toward repair thresholds.
836    ///
837    /// A turn the caller had no part in, such as the greeting or the model
838    /// speaking a tool's result, is not a stall: with `counted` false the
839    /// flow advances as usual but no step's `reprompt_after` /
840    /// `escalate_after` count moves.
841    pub fn on_turn_counted(&mut self, state: &State, counted: bool) {
842        self.advance_turn(state, counted);
843        self.publish_timing(state);
844    }
845
846    fn advance_turn(&mut self, state: &State, counted: bool) {
847        if self.terminated.is_some() {
848            return;
849        }
850        // A correction can come while a digression drives; its flag stays
851        // raised until the main flow advances and sees it.
852        self.detect_corrections(state);
853        if let Some(closed) = self.active.pop_if(|a| a.monitor.is_complete()) {
854            self.apply_resume(closed.name, closed.resume, state);
855            if self.terminated.is_some() {
856                return;
857            }
858        }
859        // A triggered digression suspends whichever layer is driving, the
860        // main flow or another digression.
861        if let Some(idx) = self.triggered(state) {
862            self.enter(idx, state);
863            return;
864        }
865        match self.active.last_mut() {
866            Some(active) => active.monitor.on_turn(state),
867            None => self.advance_main(state, counted),
868        }
869    }
870
871    /// Record a successful tool call against the active layer. A no-op once the
872    /// conversation has been terminated: nothing is governing, so there is no
873    /// marking for the call to advance. (In `Enforce` the call is denied before
874    /// it runs; in `Observe` it runs but must not move a flow that has ended.)
875    ///
876    /// A tool can itself fire a reset (`reset(..).when(called_ok(..))`), so the
877    /// main layer sheds the repair signals of whatever that un-latches, exactly
878    /// as the main layer does at a turn boundary. Repair
879    /// is tracked for the main flow only, so a digression just delegates.
880    pub fn on_tool_ok(&mut self, tool: &str, state: &State) {
881        self.advance_tool_ok(tool, state);
882        self.publish_timing(state);
883    }
884
885    fn advance_tool_ok(&mut self, tool: &str, state: &State) {
886        if self.terminated.is_some() {
887            return;
888        }
889        match self.active.last_mut() {
890            Some(active) => active.monitor.on_tool_ok(tool, state),
891            None => {
892                for step in self.main.begin_tool_ok(tool, state) {
893                    self.clear_repair(&step, state);
894                }
895                // No `apply_repair` here: repair counters advance per turn, not
896                // per tool call.
897                self.main.relatch(state);
898            }
899        }
900    }
901
902    /// Observe a tool call for conformance against the active layer (see
903    /// [`FlowMonitor::observe_tool`]).
904    ///
905    /// After termination nothing is advanced, but in `Observe` the call is
906    /// still recorded as a deviation: a tool used after the conversation ended
907    /// is exactly what that mode exists to catch, and the monitor cannot see it
908    /// for itself because the denial is the stack's, not the flow's.
909    pub fn observe_tool(&mut self, tool: &str, ok: bool, state: &State) {
910        if let Some(denial) = self.termination_denial() {
911            if self.mode == Enforcement::Observe {
912                self.main.record_violation(tool, denial);
913            }
914            return;
915        }
916        // The conformance check is the *stack's*, not the active monitor's, and
917        // the call is recorded through `Self::on_tool_ok` so a tool-fired reset
918        // still sheds its repair signals.
919        if self.mode == Enforcement::Observe
920            && let Err(reason) = self.admits_tool(tool, state)
921        {
922            self.current_mut().record_violation(tool, reason);
923        }
924        if ok {
925            self.on_tool_ok(tool, state);
926        } else {
927            self.on_tool_failed(state);
928        }
929    }
930
931    /// Whether `tool` is admitted right now (delegates to the active layer).
932    /// Every tool is denied once the conversation has been terminated.
933    pub fn admits_tool(&self, tool: &str, state: &State) -> Result<(), String> {
934        if let Some(denial) = self.termination_denial() {
935            return Err(denial);
936        }
937        self.current().admits_tool(tool, state)
938    }
939
940    /// Whether the active layer would admit `tool` once its
941    /// `never(tool).until(..)` guards hold (see
942    /// [`FlowMonitor::offers_tool`]). Nothing is offered after termination.
943    pub fn offers_tool(&self, tool: &str, state: &State) -> bool {
944        self.termination_denial().is_none()
945            && (self.current().offers_tool(tool, state) || self.digression_offers(tool, state))
946    }
947
948    /// Whether a digression the caller's next words could open would admit
949    /// `tool` on entry: its trigger turns on a decision (see
950    /// [`Guard::possible`]) and a step it starts with allows the tool. Then
951    /// the model can call it in the turn the caller asks, and the gate enters
952    /// the digression first (see [`gate_scope`](Self::gate_scope)).
953    fn digression_offers(&self, tool: &str, state: &State) -> bool {
954        self.overlays.iter().any(|ov| {
955            !self.active.iter().any(|a| a.name == ov.name)
956                && self.main.possible(&ov.trigger, state).is_none()
957                && ov
958                    .flow
959                    .steps
960                    .iter()
961                    .filter(|s| s.after.is_empty())
962                    .any(|s| s.allow.iter().any(|a| a == tool))
963        })
964    }
965
966    /// The state keys read by the guards that refuse `tool` in the active
967    /// layer right now (see [`FlowMonitor::blocking_keys`]).
968    pub fn blocking_keys(&self, tool: &str, state: &State) -> std::collections::BTreeSet<String> {
969        if self.termination_denial().is_some() {
970            return std::collections::BTreeSet::new();
971        }
972        self.current().blocking_keys(tool, state)
973    }
974
975    /// Explain the active layer's control-plane state. After termination:
976    /// nothing active, nothing admitted, every tool blocked with the reason —
977    /// the conversation is over, so it is waiting for nothing. To ask instead
978    /// what it *never finished*, read [`main()`](Self::main): its marking and
979    /// `unmet_requirements()` are kept intact for exactly that audit.
980    pub fn explain(&self, state: &State) -> FlowExplanation {
981        let mut ex = self.current().explain(state);
982        if let Some(denial) = self.termination_denial() {
983            ex.active.clear();
984            ex.active_progress.clear();
985            ex.missing_requirements.clear();
986            for tool in std::mem::take(&mut ex.allowed_tools) {
987                ex.blocked_tools.insert(tool, denial.clone());
988            }
989            for reason in ex.blocked_tools.values_mut() {
990                *reason = denial.clone();
991            }
992        }
993        ex
994    }
995
996    /// Observe the current layer and whole-stack lifecycle together.
997    ///
998    /// Callers holding a shared stack lock get one consistent marking and
999    /// overlay path. Guard evaluation reads `State`, which may change
1000    /// independently; this is not a transaction across all session state.
1001    pub fn snapshot(&self, state: &State) -> FlowSnapshot {
1002        FlowSnapshot {
1003            explanation: self.explain(state),
1004            done: self.marking().done.iter().cloned().collect(),
1005            complete: self.is_complete(),
1006            overlay_path: self.overlay_path().into_iter().map(str::to_owned).collect(),
1007            terminated: self.is_terminated(),
1008        }
1009    }
1010
1011    /// What a decision model should be asked now: the questions named by the
1012    /// driving layer's guards and by the triggers of the digressions that can
1013    /// still be entered, and the state keys the driving layer could act on
1014    /// (for decisions that write a key). Empty after termination.
1015    pub fn decision_scope(&self, state: &State) -> DecisionScope {
1016        if self.is_terminated() {
1017            return DecisionScope::default();
1018        }
1019        let current = self.current();
1020        let mut questions = current.flow().decisions();
1021        let mut reads = current.reads_now(state);
1022        for ov in &self.overlays {
1023            if !self.active.iter().any(|a| a.name == ov.name) {
1024                questions.extend(ov.trigger.decisions());
1025                reads.extend(ov.trigger.state_keys());
1026            }
1027        }
1028        DecisionScope { questions, reads }
1029    }
1030
1031    /// What decides whether `tools` are admitted now: the questions in the
1032    /// driving layer's `never(tool).until(..)` guards on them (a stage's
1033    /// commit), in the way of the [frontier](FlowMonitor::frontier_steps)
1034    /// steps that allow one, and in the triggers of the digressions that
1035    /// would admit one of them, with the state keys those guards read. A call
1036    /// no decision governs gets an empty scope, so it is not held up by a
1037    /// decision round.
1038    pub fn gate_scope(&self, tools: &[String], state: &State) -> DecisionScope {
1039        if self.is_terminated() {
1040            return DecisionScope::default();
1041        }
1042        let mut scope = DecisionScope::default();
1043        for c in &self.current().flow().constraints {
1044            if let crate::flow::Constraint::NeverUntil { tool, until } = c
1045                && tools.contains(tool)
1046            {
1047                scope.questions.extend(until.decisions());
1048                scope.reads.extend(until.state_keys());
1049            }
1050        }
1051        for tool in tools {
1052            let frontier = self.current().frontier_questions(tool, state);
1053            scope.questions.extend(frontier.questions);
1054            scope.reads.extend(frontier.reads);
1055        }
1056        for ov in &self.overlays {
1057            if !self.active.iter().any(|a| a.name == ov.name)
1058                && tools.iter().any(|t| ov.flow.tool_universe().contains(t))
1059            {
1060                scope.questions.extend(ov.trigger.decisions());
1061                scope.reads.extend(ov.trigger.state_keys());
1062            }
1063        }
1064        scope
1065    }
1066
1067    /// Apply fresh decisions mid-turn: enter a digression whose trigger now
1068    /// holds, or re-evaluate the driving layer. Counts no turn and advances
1069    /// no repair policy, so it can run before a tool call is admitted: a
1070    /// caller who asks for a person and a model that transfers in the same
1071    /// turn then see the transfer counted inside the handoff digression.
1072    pub fn on_decisions(&mut self, state: &State) {
1073        if self.is_terminated() {
1074            return;
1075        }
1076        if let Some(idx) = self.triggered(state) {
1077            self.enter(idx, state);
1078        } else {
1079            self.relatch(state);
1080        }
1081        self.publish_timing(state);
1082    }
1083
1084    /// Re-evaluate the current layer after directly setting state.
1085    ///
1086    /// This does not count a turn, trigger or resume digressions, or advance
1087    /// repair policies. Use [`on_turn`](Self::on_turn) for a user turn.
1088    pub fn relatch(&mut self, state: &State) {
1089        if self.is_terminated() {
1090            return;
1091        }
1092        match self.active.last_mut() {
1093            Some(active) => active.monitor.relatch(state),
1094            None => {
1095                for step in self.main.apply_resets(state) {
1096                    self.clear_repair(&step, state);
1097                }
1098                self.main.relatch(state);
1099            }
1100        }
1101    }
1102
1103    /// The active layer's marking (the last driving layer's, after
1104    /// termination — kept for audit).
1105    pub fn marking(&self) -> &Marking {
1106        self.current().marking()
1107    }
1108
1109    /// Steps of the active layer that are eligible but not yet done. Empty
1110    /// after termination.
1111    pub fn active_steps(&self, state: &State) -> Vec<&Step> {
1112        if self.terminated.is_some() {
1113            return Vec::new();
1114        }
1115        self.current().active_steps(state)
1116    }
1117
1118    /// Postures to project this turn: the active layer's active steps', or —
1119    /// on the turn a digression completes — its closing steps' (see
1120    /// [`FlowMonitor::closing_postures`]). Empty after termination.
1121    pub fn active_postures(&self, state: &State) -> Vec<String> {
1122        if self.terminated.is_some() {
1123            return Vec::new();
1124        }
1125        if self.active_is_closing() {
1126            return self.current().closing_postures();
1127        }
1128        self.current().active_postures(state)
1129    }
1130
1131    /// Grounding lines to project this turn, chosen like
1132    /// [`active_postures`](Self::active_postures).
1133    pub fn active_grounds(&self, state: &State) -> Vec<String> {
1134        if self.terminated.is_some() {
1135            return Vec::new();
1136        }
1137        if self.active_is_closing() {
1138            return self.current().closing_grounds(state);
1139        }
1140        self.current().active_grounds(state)
1141    }
1142
1143    /// The active layer's unmet requirements. Empty after termination.
1144    pub fn unmet_requirements(&self) -> Vec<String> {
1145        if self.terminated.is_some() {
1146            return Vec::new();
1147        }
1148        self.current().unmet_requirements()
1149    }
1150
1151    /// Steps of the active layer that became active since the last call.
1152    pub fn take_newly_active(&mut self, state: &State) -> Vec<String> {
1153        if self.terminated.is_some() {
1154            return Vec::new();
1155        }
1156        self.current_mut().take_newly_active(state)
1157    }
1158
1159    /// The `on_enter` action registered for a step of the active layer.
1160    pub fn enter_action(&self, step: &str) -> Option<&StepAction> {
1161        if self.terminated.is_some() {
1162            return None;
1163        }
1164        self.current().enter_action(step)
1165    }
1166
1167    /// Replace a main-flow step's posture. Returns `true` when the step exists.
1168    pub fn set_posture(&mut self, step_id: &str, posture: Option<String>) -> bool {
1169        self.main.set_posture(step_id, posture)
1170    }
1171
1172    /// Replace a main-flow step's grounding template. Returns `true` when the
1173    /// step exists.
1174    pub fn set_ground(&mut self, step_id: &str, ground: Option<String>) -> bool {
1175        self.main.set_ground(step_id, ground)
1176    }
1177}
1178
1179#[cfg(test)]
1180mod tests {
1181    use super::*;
1182
1183    fn main_flow() -> CompiledFlow {
1184        Flow::new()
1185            .step("a")
1186            .done(Guard::is_true("a_done"))
1187            .step("b")
1188            .after("a")
1189            .terminal()
1190            .build()
1191            .expect("valid")
1192            .compile()
1193            .expect("compiles")
1194    }
1195
1196    fn faq_overlay() -> Overlay {
1197        let flow = Flow::new()
1198            .step("answer")
1199            .done(Guard::is_true("faq_answered"))
1200            .step("faq_end")
1201            .after("answer")
1202            .terminal()
1203            .require(["faq_end"])
1204            .build()
1205            .expect("valid")
1206            .compile()
1207            .expect("compiles");
1208        Overlay::new("faq", Guard::is_true("intent:faq"), flow, Resume::Previous)
1209    }
1210
1211    fn overlay(name: &str, trigger: &str, done_key: &str, resume: Resume) -> Overlay {
1212        let end = format!("{name}_end");
1213        let flow = Flow::new()
1214            .step(format!("{name}_step"))
1215            .done(Guard::is_true(done_key))
1216            .step(&end)
1217            .after(format!("{name}_step"))
1218            .terminal()
1219            .require([end.clone()])
1220            .build()
1221            .expect("valid")
1222            .compile()
1223            .expect("compiles");
1224        Overlay::new(name, Guard::is_true(trigger), flow, resume)
1225    }
1226
1227    #[test]
1228    fn snapshot_keeps_layer_progress_separate_from_stack_completion() {
1229        let state = State::new();
1230        let mut stack =
1231            FlowStack::new(main_flow(), Enforcement::Enforce).with_overlay(faq_overlay());
1232        let _ = state.set("a_done", true);
1233        stack.on_turn(&state);
1234        let _ = state.set("intent:faq", true);
1235        stack.on_turn(&state);
1236        let _ = state.set("faq_answered", true);
1237        stack.on_turn(&state);
1238
1239        let snapshot = stack.snapshot(&state);
1240        assert_eq!(snapshot.done, ["answer", "faq_end"]);
1241        assert_eq!(snapshot.overlay_path, ["faq"]);
1242        assert!(snapshot.explanation.missing_requirements.is_empty());
1243        assert!(!snapshot.complete, "a closing digression is still active");
1244        assert!(!snapshot.terminated);
1245        assert!(stack.main().marking().done.contains("a"));
1246
1247        let _ = state.set("intent:faq", false);
1248        stack.on_turn(&state);
1249        let snapshot = stack.snapshot(&state);
1250        assert_eq!(snapshot.done, ["a", "b"]);
1251        assert!(snapshot.overlay_path.is_empty());
1252        assert!(snapshot.complete);
1253    }
1254
1255    #[test]
1256    fn snapshot_reports_termination_without_inventing_main_progress() {
1257        let state = State::new();
1258        let mut stack = FlowStack::new(main_flow(), Enforcement::Enforce).with_overlay(overlay(
1259            "cancel",
1260            "cancel",
1261            "cancelled",
1262            Resume::Terminate,
1263        ));
1264        let _ = state.set("cancel", true);
1265        let _ = state.set("cancelled", true);
1266        stack.on_turn(&state);
1267        assert!(
1268            !stack.snapshot(&state).terminated,
1269            "closing turn comes first"
1270        );
1271        stack.on_turn(&state);
1272        let snapshot = stack.snapshot(&state);
1273        assert!(snapshot.terminated);
1274        assert!(snapshot.complete);
1275        assert!(snapshot.explanation.active.is_empty());
1276        assert!(snapshot.explanation.allowed_tools.is_empty());
1277        assert!(snapshot.done.is_empty(), "main task was never completed");
1278        let _ = state.set("a_done", true);
1279        stack.relatch(&state);
1280        assert!(stack.snapshot(&state).done.is_empty());
1281    }
1282
1283    #[test]
1284    fn a_digression_can_be_interrupted_by_another() {
1285        let state = State::new();
1286        let mut stack = FlowStack::new(main_flow(), Enforcement::Enforce)
1287            .with_overlay(overlay("faq", "intent:faq", "faq_done", Resume::Previous))
1288            .with_overlay(overlay(
1289                "clarify",
1290                "intent:clarify",
1291                "clarified",
1292                Resume::Previous,
1293            ));
1294
1295        let _ = state.set("intent:faq", true);
1296        stack.on_turn(&state);
1297        assert_eq!(stack.overlay_path(), ["faq"]);
1298
1299        // Mid-FAQ the user needs a clarification: it nests on top.
1300        let _ = state.set("intent:clarify", true);
1301        stack.on_turn(&state);
1302        assert_eq!(stack.overlay_path(), ["faq", "clarify"]);
1303        assert_eq!(stack.active_overlay(), Some("clarify"));
1304
1305        // The clarification completes (closing turn), then FAQ drives again.
1306        let _ = state.set("intent:clarify", false);
1307        let _ = state.set("clarified", true);
1308        stack.on_turn(&state);
1309        assert_eq!(stack.overlay_path(), ["faq", "clarify"], "closing turn");
1310        stack.on_turn(&state);
1311        assert_eq!(stack.overlay_path(), ["faq"]);
1312
1313        // FAQ completes; the main flow resumes where it was.
1314        let _ = state.set("intent:faq", false);
1315        let _ = state.set("faq_done", true);
1316        stack.on_turn(&state);
1317        stack.on_turn(&state);
1318        assert!(stack.overlay_path().is_empty());
1319        assert_eq!(stack.explain(&state).active, ["a"]);
1320    }
1321
1322    #[test]
1323    fn a_nested_terminate_ends_the_whole_conversation() {
1324        let state = State::new();
1325        let mut stack = FlowStack::new(main_flow(), Enforcement::Enforce)
1326            .with_overlay(overlay("faq", "intent:faq", "faq_done", Resume::Previous))
1327            .with_overlay(overlay(
1328                "cancel",
1329                "intent:cancel",
1330                "cancelled",
1331                Resume::Terminate,
1332            ));
1333        let _ = state.set("intent:faq", true);
1334        stack.on_turn(&state);
1335        let _ = state.set("intent:cancel", true);
1336        let _ = state.set("cancelled", true);
1337        stack.on_turn(&state);
1338        assert_eq!(stack.overlay_path(), ["faq", "cancel"]);
1339        stack.on_turn(&state);
1340        assert!(stack.is_terminated());
1341        assert!(stack.overlay_path().is_empty());
1342    }
1343
1344    #[test]
1345    fn a_digression_does_not_re_enter_itself() {
1346        let state = State::new();
1347        let mut stack = FlowStack::new(main_flow(), Enforcement::Enforce).with_overlay(overlay(
1348            "faq",
1349            "intent:faq",
1350            "faq_done",
1351            Resume::Previous,
1352        ));
1353        let _ = state.set("intent:faq", true);
1354        stack.on_turn(&state);
1355        stack.on_turn(&state);
1356        assert_eq!(
1357            stack.overlay_path(),
1358            ["faq"],
1359            "the trigger still holding does not stack it twice"
1360        );
1361    }
1362
1363    #[test]
1364    fn barge_ins_and_tool_failures_escalate_the_active_step() {
1365        let state = State::new();
1366        let mut stack = FlowStack::new(main_flow(), Enforcement::Enforce).with_repair(
1367            "a",
1368            RepairPolicy::new(10, 10)
1369                .escalate_after_interruptions(2)
1370                .escalate_after_tool_failures(3),
1371        );
1372        stack.on_turn(&state);
1373        stack.on_interrupted(&state);
1374        assert_eq!(state.get::<bool>(&escalate_flag("a")), None);
1375        stack.on_interrupted(&state);
1376        assert_eq!(state.get::<bool>(&escalate_flag("a")), Some(true));
1377
1378        let state = State::new();
1379        let mut stack = FlowStack::new(main_flow(), Enforcement::Enforce).with_repair(
1380            "a",
1381            RepairPolicy::new(10, 10).escalate_after_tool_failures(2),
1382        );
1383        stack.on_turn(&state);
1384        stack.observe_tool("lookup", false, &state);
1385        stack.observe_tool("lookup", false, &state);
1386        assert_eq!(state.get::<bool>(&escalate_flag("a")), Some(true));
1387    }
1388
1389    #[test]
1390    fn a_corrected_slot_raises_its_flag_once_and_clears_its_keys() {
1391        let state = State::new();
1392        let mut stack = FlowStack::new(main_flow(), Enforcement::Enforce)
1393            .with_correction("party_size", ["confirmed".to_string()]);
1394        let _ = state.set("party_size", 4);
1395        let _ = state.set("confirmed", true);
1396        stack.on_turn(&state);
1397        assert_eq!(
1398            state.get::<bool>(&correction_flag("party_size")),
1399            None,
1400            "first value is not a correction"
1401        );
1402
1403        let _ = state.set("party_size", 5);
1404        stack.detect_corrections(&state);
1405        assert_eq!(
1406            state.get::<bool>(&correction_flag("party_size")),
1407            Some(true)
1408        );
1409        assert_eq!(
1410            state.get::<bool>("confirmed"),
1411            None,
1412            "the confirmation is cleared"
1413        );
1414
1415        // The main flow advances past it: the flag drops for the next edge.
1416        stack.on_turn(&state);
1417        assert_eq!(
1418            state.get::<bool>(&correction_flag("party_size")),
1419            Some(false)
1420        );
1421    }
1422
1423    #[test]
1424    fn a_restated_slot_is_not_a_correction() {
1425        // An extractor re-reads the transcript each turn and may re-state a
1426        // value in different case or spacing; that must not clear the yes.
1427        let state = State::new();
1428        let mut stack = FlowStack::new(main_flow(), Enforcement::Enforce)
1429            .with_correction("slot", ["confirmed".to_string()]);
1430        let _ = state.set("slot", "tomorrow at 7 pm");
1431        stack.on_turn(&state);
1432        let _ = state.set("confirmed", true);
1433        let _ = state.set("slot", "Tomorrow at 7 PM.");
1434        stack.detect_corrections(&state);
1435        assert_eq!(state.get::<bool>(&correction_flag("slot")), None);
1436        assert_eq!(state.get::<bool>("confirmed"), Some(true));
1437
1438        let _ = state.set("slot", "tomorrow at 8 pm");
1439        stack.detect_corrections(&state);
1440        assert_eq!(state.get::<bool>(&correction_flag("slot")), Some(true));
1441        assert_eq!(state.get::<bool>("confirmed"), None);
1442    }
1443
1444    #[test]
1445    fn timing_follows_the_active_step_and_digression() {
1446        use std::time::Duration;
1447        let state = State::new();
1448        let a = VoiceTiming::new().reprompt_after(Duration::from_secs(6));
1449        let answer = VoiceTiming::new().uninterruptible();
1450        let mut stack = FlowStack::new(main_flow(), Enforcement::Enforce)
1451            .with_overlay(faq_overlay())
1452            .with_timing("a", a.clone())
1453            .with_timing("answer", answer.clone());
1454
1455        stack.publish_timing(&state);
1456        assert_eq!(state.get::<VoiceTiming>(VOICE_TIMING_KEY), Some(a.clone()));
1457
1458        // A digression takes over: its step's timing applies.
1459        let _ = state.set("intent:faq", true);
1460        stack.on_turn(&state);
1461        assert_eq!(state.get::<VoiceTiming>(VOICE_TIMING_KEY), Some(answer));
1462
1463        // Back in the main flow, past `a`: `b` has no timing, so none applies.
1464        let _ = state.set("intent:faq", false);
1465        let _ = state.set("faq_answered", true);
1466        stack.on_turn(&state);
1467        stack.on_turn(&state);
1468        assert_eq!(state.get::<VoiceTiming>(VOICE_TIMING_KEY), Some(a));
1469        let _ = state.set("a_done", true);
1470        stack.on_turn(&state);
1471        assert_eq!(state.get::<VoiceTiming>(VOICE_TIMING_KEY), None);
1472    }
1473
1474    #[test]
1475    fn bare_stack_behaves_like_its_monitor() {
1476        let state = State::new();
1477        let mut stack = FlowStack::new(main_flow(), Enforcement::Enforce);
1478        let mut mon = FlowMonitor::compiled(main_flow(), Enforcement::Enforce);
1479        for turn in 0..3 {
1480            if turn == 1 {
1481                let _ = state.set("a_done", true);
1482            }
1483            stack.on_turn(&state);
1484            mon.on_turn(&state);
1485            assert_eq!(stack.explain(&state).active, mon.explain(&state).active);
1486            assert_eq!(stack.marking().done, mon.marking().done);
1487        }
1488        assert!(stack.is_complete());
1489    }
1490
1491    #[test]
1492    fn overlay_suspends_main_then_resumes_previous() {
1493        let state = State::new();
1494        let mut stack =
1495            FlowStack::new(main_flow(), Enforcement::Enforce).with_overlay(faq_overlay());
1496
1497        assert!(stack.explain(&state).active.contains(&"a".to_string()));
1498        assert!(stack.active_overlay().is_none());
1499
1500        let _ = state.set("intent:faq", true);
1501        stack.on_turn(&state);
1502        assert_eq!(stack.active_overlay(), Some("faq"));
1503        assert!(stack.explain(&state).active.contains(&"answer".to_string()));
1504
1505        // The turn the digression completes it is still the projected layer
1506        // (its closing turn); the main flow is untouched underneath.
1507        let _ = state.set("faq_answered", true);
1508        let _ = state.set("intent:faq", false);
1509        stack.on_turn(&state);
1510        assert_eq!(stack.active_overlay(), Some("faq"));
1511        assert!(stack.explain(&state).active.is_empty());
1512        assert!(stack.main().marking().done.is_empty());
1513
1514        // Next boundary: resumed exactly where it was, and that same turn
1515        // advances the main flow.
1516        let _ = state.set("a_done", true);
1517        stack.on_turn(&state);
1518        assert!(stack.active_overlay().is_none());
1519        assert!(stack.main().marking().done.contains("a"));
1520        assert!(stack.explain(&state).active.is_empty());
1521        assert!(stack.is_complete());
1522    }
1523
1524    /// A digression that completes on its entry turn (the shape the safety
1525    /// hand-off policy lowers to: one terminal stage) must still be seen: it
1526    /// is the projected layer for that turn, its closing instruction is what
1527    /// the model is told, and the main flow's tools are not admitted.
1528    #[test]
1529    fn entry_complete_digression_is_projected_before_it_resumes() {
1530        let state = State::new();
1531        let main = Flow::new()
1532            .step("a")
1533            .allow(["main_tool"])
1534            .posture("MAIN")
1535            .done(Guard::is_true("a_done"))
1536            .step("b")
1537            .after("a")
1538            .terminal()
1539            .build()
1540            .expect("valid")
1541            .compile()
1542            .expect("compiles");
1543        // The digression governs its closing turn, so what it says about tools
1544        // is what holds: this one locks the main flow's tool outright.
1545        let handoff = Flow::new()
1546            .step("handoff")
1547            .posture("HAND OFF NOW")
1548            .terminal()
1549            .require(["handoff"])
1550            .never("main_tool")
1551            .until(Guard::is_true("human_joined"))
1552            .build()
1553            .expect("valid")
1554            .compile()
1555            .expect("compiles");
1556        let mut stack = FlowStack::new(main, Enforcement::Enforce).with_overlay(Overlay::new(
1557            "safety",
1558            Guard::is_true("intent:abuse"),
1559            handoff,
1560            Resume::Previous,
1561        ));
1562        assert_eq!(stack.active_postures(&state), ["MAIN"]);
1563
1564        let _ = state.set("intent:abuse", true);
1565        stack.on_turn(&state);
1566        assert_eq!(stack.active_overlay(), Some("safety"));
1567        assert_eq!(stack.active_postures(&state), ["HAND OFF NOW"]);
1568        // Complete, so nothing is *active* — but it is still the governing layer.
1569        assert!(stack.active_steps(&state).is_empty());
1570        assert!(stack.admits_tool("main_tool", &state).is_err());
1571        assert!(!stack.is_complete());
1572
1573        let _ = state.set("intent:abuse", false);
1574        stack.on_turn(&state);
1575        assert!(stack.active_overlay().is_none());
1576        assert_eq!(stack.active_postures(&state), ["MAIN"]);
1577        assert!(stack.admits_tool("main_tool", &state).is_ok());
1578    }
1579
1580    #[test]
1581    fn restart_resets_marking_but_not_state() {
1582        let state = State::new();
1583        let cancel = {
1584            let flow = Flow::new()
1585                .step("confirm")
1586                .done(Guard::is_true("confirmed"))
1587                .step("cancel_end")
1588                .after("confirm")
1589                .terminal()
1590                .require(["cancel_end"])
1591                .build()
1592                .expect("valid")
1593                .compile()
1594                .expect("compiles");
1595            Overlay::new(
1596                "cancel",
1597                Guard::is_true("intent:cancel"),
1598                flow,
1599                Resume::Restart,
1600            )
1601        };
1602        let mut stack = FlowStack::new(main_flow(), Enforcement::Enforce).with_overlay(cancel);
1603
1604        let _ = state.set("a_done", true);
1605        stack.on_turn(&state);
1606        assert!(stack.main().marking().done.contains("a"));
1607
1608        let _ = state.set("intent:cancel", true);
1609        stack.on_turn(&state);
1610        assert_eq!(stack.active_overlay(), Some("cancel"));
1611        let _ = state.set("confirmed", true);
1612        let _ = state.set("intent:cancel", false);
1613        stack.on_turn(&state); // closing turn
1614        assert_eq!(stack.active_overlay(), Some("cancel"));
1615        assert!(stack.main().marking().done.contains("a"));
1616
1617        // Next boundary: the monitor restarts and re-latches in the same turn.
1618        // State is untouched, so `a` completes again from the same facts.
1619        stack.on_turn(&state);
1620        assert!(stack.active_overlay().is_none());
1621        assert_eq!(state.get::<bool>("a_done"), Some(true));
1622        assert!(stack.main().marking().done.contains("a"));
1623        assert_eq!(stack.main().marking().turns, 1);
1624    }
1625
1626    /// A restart is a fresh pass: a step that had escalated must not start
1627    /// the new pass already escalated. The lowered completion guard references
1628    /// the escalate signal, so a stale signal would complete it on re-latch.
1629    #[test]
1630    fn restart_clears_repair_signals() {
1631        let state = State::new();
1632        let main = escalating_flow();
1633        let cancel = {
1634            let flow = Flow::new()
1635                .step("bye")
1636                .terminal()
1637                .require(["bye"])
1638                .build()
1639                .expect("valid")
1640                .compile()
1641                .expect("compiles");
1642            Overlay::new(
1643                "cancel",
1644                Guard::is_true("intent:cancel"),
1645                flow,
1646                Resume::Restart,
1647            )
1648        };
1649        let mut stack = FlowStack::new(main, Enforcement::Enforce)
1650            .with_overlay(cancel)
1651            .with_repair("collect", RepairPolicy::new(1, 2).escalate_to("handoff"));
1652        stack.on_turn(&state);
1653        stack.on_turn(&state); // escalated: collect done, handoff active
1654        assert_eq!(stack.explain(&state).active, ["handoff"]);
1655
1656        let _ = state.set("intent:cancel", true);
1657        stack.on_turn(&state); // enters and completes the digression
1658        let _ = state.set("intent:cancel", false);
1659        stack.on_turn(&state); // restart + re-latch
1660        assert!(stack.active_overlay().is_none());
1661        assert_eq!(stack.explain(&state).active, ["collect"]);
1662        assert_eq!(state.get::<bool>(&escalate_flag("collect")), Some(false));
1663        // And it can escalate again, from a fresh count.
1664        stack.on_turn(&state);
1665        assert_eq!(stack.explain(&state).active, ["handoff"]);
1666    }
1667
1668    /// A `Terminate` digression is projected for its closing turn (the model is
1669    /// told to say goodbye), and from the next boundary the stack governs
1670    /// nothing: no steps, no postures, every tool denied, further turns no-ops.
1671    #[test]
1672    fn terminate_ends_the_conversation() {
1673        let state = State::new();
1674        let main = Flow::new()
1675            .step("a")
1676            .allow(["main_tool"])
1677            .posture("MAIN")
1678            .done(Guard::is_true("a_done"))
1679            .step("b")
1680            .after("a")
1681            .terminal()
1682            .require(["b"])
1683            .build()
1684            .expect("valid")
1685            .compile()
1686            .expect("compiles");
1687        let bye = {
1688            let flow = Flow::new()
1689                .step("bye")
1690                .posture("SAY GOODBYE")
1691                .terminal()
1692                .require(["bye"])
1693                .build()
1694                .expect("valid")
1695                .compile()
1696                .expect("compiles");
1697            Overlay::new("bye", Guard::is_true("intent:bye"), flow, Resume::Terminate)
1698        };
1699        let mut stack = FlowStack::new(main, Enforcement::Enforce).with_overlay(bye);
1700        let _ = state.set("intent:bye", true);
1701        stack.on_turn(&state);
1702        assert_eq!(stack.active_overlay(), Some("bye"));
1703        assert_eq!(stack.active_postures(&state), ["SAY GOODBYE"]);
1704        assert!(!stack.is_terminated());
1705        assert!(!stack.is_complete());
1706
1707        stack.on_turn(&state);
1708        assert!(stack.is_terminated());
1709        assert!(stack.is_complete());
1710        assert!(stack.active_overlay().is_none());
1711        assert!(stack.active_steps(&state).is_empty());
1712        assert!(stack.active_postures(&state).is_empty());
1713        assert!(stack.unmet_requirements().is_empty());
1714        let denied = stack.admits_tool("main_tool", &state).unwrap_err();
1715        assert!(denied.contains("terminated"), "{denied}");
1716        assert!(denied.contains("bye"), "{denied}");
1717        let ex = stack.explain(&state);
1718        assert!(ex.active.is_empty());
1719        assert!(ex.allowed_tools.is_empty());
1720        assert_eq!(ex.blocked_tools.get("main_tool"), Some(&denied));
1721
1722        // Later turns change nothing, whatever state says — and neither does a
1723        // tool that slipped through (only possible in `Observe`): a flow that
1724        // has ended must not keep advancing.
1725        let _ = state.set("a_done", true);
1726        stack.on_turn(&state);
1727        assert!(stack.main().marking().done.is_empty());
1728        stack.on_tool_ok("main_tool", &state);
1729        stack.observe_tool("main_tool", true, &state);
1730        assert!(stack.main().marking().done.is_empty());
1731        assert!(stack.admits_tool("main_tool", &state).is_err());
1732    }
1733
1734    /// `Observe` exists to record what a session did wrong without blocking it.
1735    /// A tool called after the conversation ended is exactly that, and the
1736    /// monitor cannot see it — the denial belongs to the stack — so the stack
1737    /// records it. The marking still does not move.
1738    #[test]
1739    fn observe_mode_records_a_tool_used_after_termination() {
1740        let state = State::new();
1741        let bye = {
1742            let flow = Flow::new()
1743                .step("bye")
1744                .terminal()
1745                .require(["bye"])
1746                .build()
1747                .expect("valid")
1748                .compile()
1749                .expect("compiles");
1750            Overlay::new("bye", Guard::is_true("intent:bye"), flow, Resume::Terminate)
1751        };
1752        let mut stack = FlowStack::new(main_flow(), Enforcement::Observe).with_overlay(bye);
1753        let _ = state.set("intent:bye", true);
1754        stack.on_turn(&state); // closing turn
1755        stack.on_turn(&state); // terminated
1756        assert!(stack.is_terminated());
1757
1758        let _ = state.set("a_done", true);
1759        stack.observe_tool("anything", true, &state);
1760        let violations = stack.main().violations();
1761        assert_eq!(violations.len(), 1, "{violations:?}");
1762        assert_eq!(violations[0].subject, "anything");
1763        assert!(
1764            violations[0].reason.contains("terminated"),
1765            "{violations:?}"
1766        );
1767        // Recorded, not acted on: the ended flow did not advance.
1768        assert!(stack.main().marking().done.is_empty());
1769    }
1770
1771    #[test]
1772    fn repair_raises_then_clears_signals() {
1773        let state = State::new();
1774        let mut stack = FlowStack::new(main_flow(), Enforcement::Enforce)
1775            .with_repair("a", RepairPolicy::new(1, 3));
1776        stack.on_turn(&state);
1777        assert_eq!(state.get::<bool>("repair:a:reprompt"), Some(true));
1778        assert_eq!(state.get::<bool>("repair:a:escalate"), None);
1779        let _ = state.set("a_done", true);
1780        stack.on_turn(&state);
1781        stack.on_turn(&state);
1782        assert_eq!(state.get::<bool>("repair:a:reprompt"), Some(false));
1783    }
1784
1785    /// The shape the conversation compiler lowers for `escalate_to`: `collect`
1786    /// completes on `info` or on its escalate flag; `handoff` follows, gated on
1787    /// the flag; `done` follows `collect` only when it completed properly.
1788    fn escalating_flow() -> CompiledFlow {
1789        Flow::new()
1790            .step("collect")
1791            .done(Guard::any(vec![
1792                Guard::is_true("info"),
1793                Guard::is_true(escalate_flag("collect")),
1794            ]))
1795            .step("handoff")
1796            .after("collect")
1797            .gate(Guard::is_true(escalate_flag("collect")))
1798            .done(Guard::is_true("handoff_complete"))
1799            .step("done")
1800            .after_when("collect", Guard::is_true("info"))
1801            .terminal()
1802            .build()
1803            .expect("valid")
1804            .compile()
1805            .expect("compiles")
1806    }
1807
1808    /// `escalate_to` lowers to an edge gated on the escalate signal. Gates are
1809    /// evaluated every turn, so the signal must stay latched once the step
1810    /// has completed by escalating, or the hand-off target is active for one
1811    /// turn and then vanishes.
1812    #[test]
1813    fn escalation_edge_stays_open_after_the_step_completes() {
1814        let state = State::new();
1815        let mut stack = FlowStack::new(escalating_flow(), Enforcement::Enforce)
1816            .with_repair("collect", RepairPolicy::new(1, 2).escalate_to("handoff"));
1817
1818        stack.on_turn(&state); // active 1 turn: reprompt
1819        stack.on_turn(&state); // active 2 turns: escalate -> collect done -> handoff
1820        assert!(
1821            stack
1822                .explain(&state)
1823                .active
1824                .contains(&"handoff".to_string())
1825        );
1826        // The turn after, collect has left the active set; handoff must stay.
1827        stack.on_turn(&state);
1828        assert!(
1829            stack
1830                .explain(&state)
1831                .active
1832                .contains(&"handoff".to_string())
1833        );
1834        assert_eq!(state.get::<bool>(&reprompt_flag("collect")), Some(false));
1835        assert_eq!(state.get::<bool>(&escalate_flag("collect")), Some(true));
1836    }
1837
1838    /// A `Constraint::Reset` that un-latches an escalated step must also shed
1839    /// its latched escalate signal, before the re-latch: the lowered
1840    /// completion guard references that signal and would complete the step
1841    /// again on the spot, routing straight back to the hand-off target.
1842    #[test]
1843    fn reset_clears_a_latched_escalation() {
1844        let state = State::new();
1845        let main = Flow::new()
1846            .step("collect")
1847            .done(Guard::any(vec![
1848                Guard::is_true("info"),
1849                Guard::is_true(escalate_flag("collect")),
1850            ]))
1851            .step("handoff")
1852            .after("collect")
1853            .gate(Guard::is_true(escalate_flag("collect")))
1854            .done(Guard::is_true("handoff_complete"))
1855            .step("done")
1856            .after_when("collect", Guard::is_true("info"))
1857            .terminal()
1858            .reset(["collect"])
1859            .when(Guard::is_true("retry"))
1860            .build()
1861            .expect("valid")
1862            .compile()
1863            .expect("compiles");
1864        let mut stack = FlowStack::new(main, Enforcement::Enforce)
1865            .with_repair("collect", RepairPolicy::new(1, 2).escalate_to("handoff"));
1866
1867        stack.on_turn(&state);
1868        stack.on_turn(&state); // escalated
1869        assert_eq!(stack.explain(&state).active, ["handoff"]);
1870
1871        // The reset fires: collect is back, handoff is gone, the count restarts.
1872        let _ = state.set("retry", true);
1873        stack.on_turn(&state);
1874        assert_eq!(stack.explain(&state).active, ["collect"]);
1875        assert_eq!(state.get::<bool>(&escalate_flag("collect")), Some(false));
1876        assert_eq!(state.get::<bool>(&reprompt_flag("collect")), Some(true));
1877
1878        // A second stall escalates again from that fresh count.
1879        stack.on_turn(&state);
1880        assert_eq!(stack.explain(&state).active, ["handoff"]);
1881        assert_eq!(state.get::<bool>(&escalate_flag("collect")), Some(true));
1882    }
1883
1884    #[test]
1885    fn state_only_reset_clears_repair_without_counting_a_turn() {
1886        let state = State::new();
1887        let main = Flow::new()
1888            .step("collect")
1889            .done(Guard::is_true(escalate_flag("collect")))
1890            .reset(["collect"])
1891            .when(Guard::is_true("retry"))
1892            .build()
1893            .unwrap()
1894            .compile()
1895            .unwrap();
1896        let mut stack = FlowStack::new(main, Enforcement::Enforce)
1897            .with_repair("collect", RepairPolicy::new(1, 2));
1898        stack.on_turn(&state);
1899        stack.on_turn(&state);
1900        assert!(stack.marking().done.contains("collect"));
1901
1902        let _ = state.set("retry", true);
1903        stack.relatch(&state);
1904        assert_eq!(stack.marking().turns, 2);
1905        assert!(!stack.marking().done.contains("collect"));
1906        assert_eq!(state.get::<bool>(&escalate_flag("collect")), Some(false));
1907        assert_eq!(state.get::<bool>(&reprompt_flag("collect")), Some(false));
1908        stack.on_turn(&state);
1909        assert!(!stack.marking().done.contains("collect"));
1910        stack.on_turn(&state);
1911        assert!(stack.marking().done.contains("collect"));
1912    }
1913
1914    /// A reset can be gated on a *tool*, not just a state flag — `reset(..)
1915    /// .when(called_ok("start_over"))` is the natural "start over" button. That
1916    /// edge fires inside `on_tool_ok`, not at a turn boundary, so the repair
1917    /// signals must be shed there too, or the escalated step re-completes on its
1918    /// own stale flag exactly as it would at a turn boundary.
1919    #[test]
1920    fn a_tool_triggered_reset_clears_a_latched_escalation() {
1921        let state = State::new();
1922        let main = Flow::new()
1923            .step("collect")
1924            .allow(["start_over"])
1925            .done(Guard::any(vec![
1926                Guard::is_true("info"),
1927                Guard::is_true(escalate_flag("collect")),
1928            ]))
1929            .step("handoff")
1930            .after("collect")
1931            .gate(Guard::is_true(escalate_flag("collect")))
1932            .done(Guard::is_true("handoff_complete"))
1933            .step("done")
1934            .after_when("collect", Guard::is_true("info"))
1935            .terminal()
1936            .reset(["collect"])
1937            .when(Guard::called_ok("start_over"))
1938            .build()
1939            .expect("valid")
1940            .compile()
1941            .expect("compiles");
1942        let mut stack = FlowStack::new(main, Enforcement::Enforce)
1943            .with_repair("collect", RepairPolicy::new(1, 2).escalate_to("handoff"));
1944
1945        stack.on_turn(&state);
1946        stack.on_turn(&state); // escalated
1947        assert_eq!(stack.explain(&state).active, ["handoff"]);
1948
1949        // The caller hits "start over" mid-turn.
1950        stack.on_tool_ok("start_over", &state);
1951        assert_eq!(state.get::<bool>(&escalate_flag("collect")), Some(false));
1952        assert_eq!(stack.explain(&state).active, ["collect"]);
1953
1954        // And it stays reset across the next boundary rather than snapping back.
1955        stack.on_turn(&state);
1956        assert_eq!(stack.explain(&state).active, ["collect"]);
1957    }
1958
1959    #[test]
1960    fn tool_admission_follows_the_active_layer() {
1961        let state = State::new();
1962        let main = Flow::new()
1963            .step("a")
1964            .allow(["main_tool"])
1965            .done(Guard::is_true("a_done"))
1966            .step("b")
1967            .after("a")
1968            .terminal()
1969            .build()
1970            .expect("valid")
1971            .compile()
1972            .expect("compiles");
1973        let ov = {
1974            let flow = Flow::new()
1975                .step("answer")
1976                .allow(["faq_tool"])
1977                .done(Guard::is_true("faq_answered"))
1978                .step("faq_end")
1979                .after("answer")
1980                .terminal()
1981                .require(["faq_end"])
1982                .build()
1983                .expect("valid")
1984                .compile()
1985                .expect("compiles");
1986            Overlay::new("faq", Guard::is_true("intent:faq"), flow, Resume::Previous)
1987        };
1988        let mut stack = FlowStack::new(main, Enforcement::Enforce).with_overlay(ov);
1989        assert!(stack.admits_tool("main_tool", &state).is_ok());
1990        assert!(stack.admits_tool("faq_tool", &state).is_err());
1991        let _ = state.set("intent:faq", true);
1992        stack.on_turn(&state);
1993        assert!(stack.admits_tool("faq_tool", &state).is_ok());
1994        assert!(stack.admits_tool("main_tool", &state).is_err());
1995    }
1996
1997    fn answer(state: &State, question: &str, outcome: crate::flow::Outcome, turn: &str) {
1998        let _ = state.set(crate::flow::DECISION_TURN_KEY, turn);
1999        let _ = state.set(
2000            crate::flow::decision_key(question),
2001            serde_json::to_value(crate::flow::DecisionRecord {
2002                outcome,
2003                value: serde_json::Value::Null,
2004                confidence: None,
2005                turn: turn.into(),
2006            })
2007            .unwrap(),
2008        );
2009    }
2010
2011    fn booking_with_handoff() -> FlowStack {
2012        let main = Flow::new()
2013            .step("collect")
2014            .done(Guard::captured(["slot"]))
2015            .step("confirm")
2016            .after("collect")
2017            .allow(["book"])
2018            .commit("book", Guard::decided("confirmed"))
2019            .done(Guard::called_ok("book"))
2020            .step("end")
2021            .after("confirm")
2022            .terminal()
2023            .build()
2024            .expect("valid")
2025            .compile()
2026            .expect("compiles");
2027        let handoff = Flow::new()
2028            .step("transfer")
2029            .allow(["transfer"])
2030            .done(Guard::called_ok("transfer"))
2031            .build()
2032            .expect("valid")
2033            .compile()
2034            .expect("compiles");
2035        FlowStack::new(main, Enforcement::Enforce).with_overlay(Overlay::new(
2036            "handoff",
2037            Guard::decided("wants_person"),
2038            handoff,
2039            Resume::Terminate,
2040        ))
2041    }
2042
2043    /// `ask` leads to `book` when the caller wants to book, and to `faq`
2044    /// behind a flag no decision sets.
2045    fn routed() -> FlowStack {
2046        let main = Flow::new()
2047            .step("ask")
2048            .allow(["lookup"])
2049            .done(Guard::any([
2050                Guard::decided("wants_booking"),
2051                Guard::is_true("faq_flag"),
2052            ]))
2053            .step("book")
2054            .after_when("ask", Guard::decided("wants_booking"))
2055            .allow(["book_table"])
2056            .done(Guard::called_ok("book_table"))
2057            .step("faq")
2058            .after_when("ask", Guard::is_true("faq_flag"))
2059            .allow(["answer"])
2060            .done(Guard::called_ok("answer"))
2061            .build()
2062            .expect("valid")
2063            .compile()
2064            .expect("compiles");
2065        FlowStack::new(main, Enforcement::Enforce)
2066    }
2067
2068    #[test]
2069    fn a_step_one_decision_away_is_offered_and_decided_at_the_gate() {
2070        let mut stack = routed();
2071        let state = State::new();
2072        stack.on_turn(&state);
2073        let monitor = stack.current();
2074        let frontier: Vec<_> = monitor
2075            .frontier_steps(&state)
2076            .iter()
2077            .map(|s| s.id.clone())
2078            .collect();
2079        assert_eq!(frontier, ["book"], "faq waits on a flag, not a decision");
2080        assert!(stack.offers_tool("lookup", &state), "the active step's");
2081        assert!(stack.offers_tool("book_table", &state), "one decision away");
2082        assert!(!stack.offers_tool("answer", &state));
2083        assert!(
2084            stack.admits_tool("book_table", &state).is_err(),
2085            "offered is not admitted"
2086        );
2087        assert_eq!(
2088            stack
2089                .gate_scope(&["book_table".to_string()], &state)
2090                .questions,
2091            ["wants_booking".to_string()].into()
2092        );
2093
2094        // The gate asks about the turn in progress; a yes opens the step.
2095        answer(&state, "wants_booking", crate::flow::Outcome::Yes, "2:a");
2096        stack.on_decisions(&state);
2097        assert!(stack.admits_tool("book_table", &state).is_ok());
2098        assert!(
2099            !stack.offers_tool("lookup", &state),
2100            "ask is done, and its tool goes with it"
2101        );
2102    }
2103
2104    #[test]
2105    fn a_no_keeps_the_step_closed() {
2106        let mut stack = routed();
2107        let state = State::new();
2108        stack.on_turn(&state);
2109        answer(&state, "wants_booking", crate::flow::Outcome::No, "2:a");
2110        stack.on_decisions(&state);
2111        assert!(stack.admits_tool("book_table", &state).is_err());
2112        // Still one decision away: the next turn may say yes.
2113        assert!(stack.offers_tool("book_table", &state));
2114    }
2115
2116    /// A main step that allows only `lookup`, with a handoff digression
2117    /// behind `trigger`.
2118    fn talk_with_handoff(trigger: Guard) -> FlowStack {
2119        let flow = |step: &str, tool: &str| {
2120            Flow::new()
2121                .step(step)
2122                .allow([tool])
2123                .done(Guard::called_ok(tool))
2124                .build()
2125                .expect("valid")
2126                .compile()
2127                .expect("compiles")
2128        };
2129        FlowStack::new(flow("talk", "lookup"), Enforcement::Enforce).with_overlay(Overlay::new(
2130            "handoff",
2131            trigger,
2132            flow("transfer", "transfer"),
2133            Resume::Terminate,
2134        ))
2135    }
2136
2137    #[test]
2138    fn a_digression_a_decision_opens_offers_its_entry_tools() {
2139        let state = State::new();
2140        let mut stack = talk_with_handoff(Guard::decided("wants_person"));
2141        stack.on_turn(&state);
2142        assert!(stack.offers_tool("transfer", &state));
2143        assert!(stack.admits_tool("transfer", &state).is_err());
2144        assert_eq!(
2145            stack
2146                .gate_scope(&["transfer".to_string()], &state)
2147                .questions,
2148            ["wants_person".to_string()].into()
2149        );
2150        answer(&state, "wants_person", crate::flow::Outcome::Yes, "2:a");
2151        stack.on_decisions(&state);
2152        assert!(stack.admits_tool("transfer", &state).is_ok());
2153
2154        // A trigger no decision sets is not offered ahead.
2155        let mut flagged = talk_with_handoff(Guard::is_true("intent:human_agent"));
2156        flagged.on_turn(&State::new());
2157        assert!(!flagged.offers_tool("transfer", &State::new()));
2158    }
2159
2160    #[test]
2161    fn the_decision_scope_names_guards_and_triggers_and_what_active_steps_read() {
2162        let stack = booking_with_handoff();
2163        let state = State::new();
2164        let scope = stack.decision_scope(&state);
2165        assert_eq!(
2166            scope.questions,
2167            ["confirmed", "wants_person"].map(String::from).into()
2168        );
2169        assert!(
2170            scope.reads.contains("slot"),
2171            "collect reads the slot: {scope:?}"
2172        );
2173    }
2174
2175    #[test]
2176    fn the_gate_scope_names_only_what_decides_these_calls() {
2177        let mut stack = booking_with_handoff();
2178        let state = State::new();
2179        let _ = state.set("slot", "19:00");
2180        stack.on_turn(&state);
2181        let scope = |tools: &[&str]| {
2182            stack
2183                .gate_scope(
2184                    &tools.iter().map(ToString::to_string).collect::<Vec<_>>(),
2185                    &state,
2186                )
2187                .questions
2188        };
2189        assert_eq!(scope(&["book"]), ["confirmed".to_string()].into());
2190        assert_eq!(scope(&["transfer"]), ["wants_person".to_string()].into());
2191        assert!(
2192            scope(&["check_availability"]).is_empty(),
2193            "a call no decision governs waits for none"
2194        );
2195    }
2196
2197    #[test]
2198    fn a_decided_commit_is_admitted_only_for_the_current_turn() {
2199        let mut stack = booking_with_handoff();
2200        let state = State::new();
2201        let _ = state.set("slot", "19:00");
2202        stack.on_turn(&state);
2203        assert!(
2204            stack.admits_tool("book", &state).is_err(),
2205            "not confirmed yet"
2206        );
2207        answer(&state, "confirmed", crate::flow::Outcome::Yes, "t1");
2208        assert!(stack.admits_tool("book", &state).is_ok());
2209        // The caller spoke again; the yes was about the previous turn.
2210        let _ = state.set(crate::flow::DECISION_TURN_KEY, "t2");
2211        let refusal = stack.admits_tool("book", &state).unwrap_err();
2212        assert!(refusal.contains("confirmed"), "{refusal}");
2213    }
2214
2215    #[test]
2216    fn fresh_decisions_open_a_digression_mid_turn() {
2217        let mut stack = booking_with_handoff();
2218        let state = State::new();
2219        stack.on_turn(&state);
2220        assert_eq!(stack.active_overlay(), None);
2221        answer(&state, "wants_person", crate::flow::Outcome::Yes, "t1");
2222        stack.on_decisions(&state);
2223        assert_eq!(stack.active_overlay(), Some("handoff"));
2224        assert!(stack.admits_tool("transfer", &state).is_ok());
2225        stack.on_tool_ok("transfer", &state);
2226        stack.on_turn(&state);
2227        stack.on_turn(&state);
2228        assert!(stack.is_terminated(), "one transfer completes the handoff");
2229    }
2230}