Skip to main content

gemini_adk_rs/flow/
mod.rs

1//! `Flow` — a governed conversation/tool DAG.
2//!
3//! A [`Flow`] is a directed acyclic graph of [`Step`]s. A `Step` is the *only*
4//! node type; it unifies "conversation stage" and "tool-call milestone" by
5//! differing only in attributes, not in kind. A step is *done* when its
6//! completion [`Guard`] latches true; edges (`after`) are dependencies. The
7//! [`FlowMonitor`] maintains a [`Marking`] (the set of done steps) by observing
8//! the session trace, **projects** active steps' postures into turn-boundary
9//! steering, and **enforces** ordering by admitting/denying tool calls.
10//!
11//! The vocabulary is deliberately closed: the only
12//! nouns are `Flow`, `Step`, `Guard`, `Posture`, `Marking`, `Verdict`. Words
13//! like *phase*, *transition*, *watch*, *needs* are lowering details and never
14//! appear here.
15//!
16//! Because every [`Guard`] atom is a named, parameterized predicate, a `Flow`
17//! is fully serializable — enabling data-driven scripts edited without a
18//! recompile. The `custom` closure escape hatch is available in code but is not
19//! serializable.
20
21use std::collections::{BTreeMap, BTreeSet, HashMap};
22use std::sync::Arc;
23
24use serde::{Deserialize, Deserializer, Serialize, Serializer};
25use serde_json::Value;
26
27use crate::error::ConfigError;
28use crate::orchestration::{AgentMode, call_agent};
29use crate::state::State;
30use crate::text::TextAgent;
31
32pub mod decided;
33pub mod stack;
34pub mod timing;
35pub mod verbatim;
36pub use decided::{
37    DECISION_PREFIX, DECISION_TURN_KEY, Decided, DecisionRecord, Expect, Outcome, decision_key,
38};
39pub use stack::{
40    DecisionScope, FlowStack, OVERLAY_STATE_KEY, Overlay, RepairPolicy, Resume, SharedFlowStack,
41    TERMINATED_STATE_KEY, TOOL_CALL_KEY, TOOL_DENIED_KEY, TOOL_RESULT_KEY, correction_flag,
42    escalate_flag, reprompt_flag,
43};
44pub use timing::{DEFAULT_REPROMPT, VOICE_TIMING_KEY, VoiceTiming};
45pub use verbatim::{VERBATIM_KEY, VerbatimRequirement, verbatim_flag};
46
47/// Evaluation context handed to a [`Guard`]: the session state plus the
48/// current flow marking.
49pub struct FlowCtx<'a> {
50    /// The session state.
51    pub state: &'a State,
52    /// The current flow marking (done steps + tool-call counts).
53    pub marking: &'a Marking,
54}
55
56/// A serializable predicate atom — the closed set of guard primitives.
57#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
58#[serde(rename_all = "snake_case")]
59pub enum Pred {
60    /// Always true.
61    Always,
62    /// State key holds boolean `true`.
63    IsTrue(String),
64    /// State key is present.
65    IsSet(String),
66    /// State key equals the given JSON value.
67    Eq(String, Value),
68    /// All of the given state keys are present (e.g. extracted slots).
69    Captured(Vec<String>),
70    /// The named tool has completed successfully at least once.
71    CalledOk(String),
72    /// The named step is done.
73    Done(String),
74    /// A decision model's answer to a declared question, about the caller's
75    /// current turn (see [`decided`]).
76    Decided(Decided),
77    /// Conjunction.
78    All(Vec<Pred>),
79    /// Disjunction.
80    Any(Vec<Pred>),
81    /// Negation.
82    Not(Box<Pred>),
83}
84
85/// Three-valued conjunction: false if any is false, unknown if any is unknown.
86fn all_of(values: impl IntoIterator<Item = Option<bool>>) -> Option<bool> {
87    let mut unknown = false;
88    for value in values {
89        match value {
90            Some(false) => return Some(false),
91            None => unknown = true,
92            Some(true) => {}
93        }
94    }
95    if unknown { None } else { Some(true) }
96}
97
98/// Three-valued disjunction: true if any is true, unknown if any is unknown.
99fn any_of(values: impl IntoIterator<Item = Option<bool>>) -> Option<bool> {
100    let mut unknown = false;
101    for value in values {
102        match value {
103            Some(true) => return Some(true),
104            None => unknown = true,
105            Some(false) => {}
106        }
107    }
108    if unknown { None } else { Some(false) }
109}
110
111impl Pred {
112    /// [`eval`](Self::eval) with every `decided` atom unknown. See
113    /// [`Guard::possible`].
114    fn possible(&self, ctx: &FlowCtx) -> Option<bool> {
115        match self {
116            Pred::Decided(_) => None,
117            Pred::All(ps) => all_of(ps.iter().map(|p| p.possible(ctx))),
118            Pred::Any(ps) => any_of(ps.iter().map(|p| p.possible(ctx))),
119            Pred::Not(p) => p.possible(ctx).map(|b| !b),
120            other => Some(other.eval(ctx)),
121        }
122    }
123
124    fn eval(&self, ctx: &FlowCtx) -> bool {
125        match self {
126            Pred::Always => true,
127            Pred::IsTrue(k) => ctx.state.get::<bool>(k) == Some(true),
128            Pred::IsSet(k) => ctx.state.contains(k),
129            Pred::Eq(k, v) => ctx.state.get::<Value>(k).as_ref() == Some(v),
130            Pred::Captured(fields) => fields.iter().all(|f| ctx.state.contains(f)),
131            Pred::CalledOk(t) => ctx.marking.tool_ok.contains_key(t),
132            Pred::Done(s) => ctx.marking.done.contains(s),
133            Pred::Decided(d) => d.holds(ctx.state),
134            Pred::All(ps) => ps.iter().all(|p| p.eval(ctx)),
135            Pred::Any(ps) => ps.iter().any(|p| p.eval(ctx)),
136            Pred::Not(p) => !p.eval(ctx),
137        }
138    }
139
140    /// This predicate as a short prose clause. See [`Guard::describe`].
141    fn describe(&self) -> String {
142        fn join(ps: &[Pred], sep: &str) -> String {
143            ps.iter().map(Pred::describe).collect::<Vec<_>>().join(sep)
144        }
145        match self {
146            Pred::Always => "nothing".to_string(),
147            Pred::IsTrue(k) => format!("'{k}' must be true"),
148            Pred::IsSet(k) => format!("'{k}' must be known"),
149            Pred::Eq(k, v) => format!("'{k}' must be {v}"),
150            Pred::Captured(fields) => {
151                format!("these must be known: {}", fields.join(", "))
152            }
153            Pred::CalledOk(t) => format!("'{t}' must have run successfully"),
154            Pred::Done(s) => format!("step '{s}' must be complete"),
155            Pred::Decided(d) => d.describe(),
156            Pred::All(ps) => join(ps, " and "),
157            Pred::Any(ps) => join(ps, " or "),
158            Pred::Not(p) => format!("it must not be the case that {}", p.describe()),
159        }
160    }
161
162    /// Step ids referenced by `Done(..)` atoms (for validation).
163    fn referenced_steps(&self, out: &mut Vec<String>) {
164        match self {
165            Pred::Done(s) => out.push(s.clone()),
166            Pred::All(ps) | Pred::Any(ps) => ps.iter().for_each(|p| p.referenced_steps(out)),
167            Pred::Not(p) => p.referenced_steps(out),
168            _ => {}
169        }
170    }
171
172    /// Tool names referenced by `called_ok` atoms (for reset forgiveness).
173    fn referenced_tools(&self, out: &mut Vec<String>) {
174        match self {
175            Pred::CalledOk(t) => out.push(t.clone()),
176            Pred::All(ps) | Pred::Any(ps) => ps.iter().for_each(|p| p.referenced_tools(out)),
177            Pred::Not(p) => p.referenced_tools(out),
178            _ => {}
179        }
180    }
181
182    /// Questions referenced by `decided` atoms.
183    fn referenced_decisions(&self, out: &mut BTreeSet<String>) {
184        match self {
185            Pred::Decided(d) => {
186                out.insert(d.question.clone());
187            }
188            Pred::All(ps) | Pred::Any(ps) => ps.iter().for_each(|p| p.referenced_decisions(out)),
189            Pred::Not(p) => p.referenced_decisions(out),
190            _ => {}
191        }
192    }
193
194    /// State keys this predicate reads (`is_true`/`is_set`/`eq`/`captured`
195    /// atoms, recursively). `called_ok`/`done` reference tools/steps, not
196    /// state, and are excluded.
197    fn referenced_state_keys(&self, out: &mut BTreeSet<String>) {
198        match self {
199            Pred::IsTrue(k) | Pred::IsSet(k) | Pred::Eq(k, _) => {
200                out.insert(k.clone());
201            }
202            Pred::Captured(fields) => out.extend(fields.iter().cloned()),
203            Pred::All(ps) | Pred::Any(ps) => {
204                ps.iter().for_each(|p| p.referenced_state_keys(out));
205            }
206            Pred::Not(p) => p.referenced_state_keys(out),
207            _ => {}
208        }
209    }
210
211    /// Evaluate to a [`GuardTrace`]: the predicate tree with each node's prose
212    /// description and its truth value under `ctx`. The atom-granular answer
213    /// to "why is this step not done?".
214    fn explain(&self, ctx: &FlowCtx) -> GuardTrace {
215        let children = match self {
216            Pred::All(ps) | Pred::Any(ps) => ps.iter().map(|p| p.explain(ctx)).collect(),
217            Pred::Not(p) => vec![p.explain(ctx)],
218            _ => Vec::new(),
219        };
220        GuardTrace {
221            desc: match self {
222                // Composite nodes describe only the connective; the operands
223                // carry their own descriptions as children.
224                Pred::All(_) => "all of".to_string(),
225                Pred::Any(_) => "any of".to_string(),
226                Pred::Not(_) => "not".to_string(),
227                atom => atom.describe(),
228            },
229            holds: self.eval(ctx),
230            children,
231        }
232    }
233}
234
235/// A [`Guard`] evaluated to a truth tree: each predicate node with its prose
236/// description and whether it currently holds. Serializable, so a devtool can
237/// render exactly which atom a stuck step is waiting on.
238#[derive(Clone, Debug, Serialize, schemars::JsonSchema)]
239pub struct GuardTrace {
240    /// Prose description of this node (from [`Guard::describe`] vocabulary).
241    pub desc: String,
242    /// Whether this node currently holds.
243    pub holds: bool,
244    /// Operand traces for `all`/`any`/`not`; empty for atoms.
245    #[serde(default, skip_serializing_if = "Vec::is_empty")]
246    pub children: Vec<GuardTrace>,
247}
248
249/// Render a grounding template against `state`.
250///
251/// - `{key}` interpolates the value at `key` (strings bare, other JSON compact);
252///   an absent key renders empty.
253/// - `{key?yes:no}` renders `yes` when `key` is *truthy* (present and not
254///   `false`/`null`/`0`/`""`), else `no`.
255///
256/// This is the realization of `Effect::ground`: a deterministic projection of
257/// known `State` into a steering line, so the model restates facts rather than
258/// inventing them.
259pub fn render_ground(template: &str, state: &State) -> String {
260    let mut out = String::with_capacity(template.len());
261    let mut rest = template;
262    while let Some(open) = rest.find('{') {
263        out.push_str(&rest[..open]);
264        let after = &rest[open + 1..];
265        let Some(close) = after.find('}') else {
266            // Unbalanced brace: emit the remainder verbatim.
267            out.push_str(&rest[open..]);
268            return out;
269        };
270        let expr = &after[..close];
271        out.push_str(&render_expr(expr, state));
272        rest = &after[close + 1..];
273    }
274    out.push_str(rest);
275    out
276}
277
278fn render_expr(expr: &str, state: &State) -> String {
279    if let Some((cond, arms)) = expr.split_once('?') {
280        let (yes, no) = arms.split_once(':').unwrap_or((arms, ""));
281        if is_truthy(state, cond.trim()) {
282            yes.to_string()
283        } else {
284            no.to_string()
285        }
286    } else {
287        match state.get::<Value>(expr.trim()) {
288            Some(Value::String(s)) => s,
289            Some(v) => v.to_string(),
290            None => String::new(),
291        }
292    }
293}
294
295fn is_truthy(state: &State, key: &str) -> bool {
296    match state.get::<Value>(key) {
297        None | Some(Value::Null) => false,
298        Some(Value::Bool(b)) => b,
299        Some(Value::Number(n)) => n.as_f64().map(|f| f != 0.0).unwrap_or(true),
300        Some(Value::String(s)) => !s.is_empty(),
301        Some(_) => true,
302    }
303}
304
305type CustomFn = Arc<dyn Fn(&FlowCtx) -> bool + Send + Sync>;
306
307/// A boolean predicate over `(state, marking)` — the *only* predicate type.
308///
309/// Use the constructors ([`Guard::is_true`], [`Guard::captured`],
310/// [`Guard::called_ok`], …) for the serializable closed atoms, or
311/// [`Guard::custom`] for a bespoke closure (not serializable).
312#[derive(Clone)]
313pub enum Guard {
314    /// A serializable predicate built from the closed atom set.
315    Spec(Pred),
316    /// A code-only escape hatch. Not serializable.
317    Custom(CustomFn),
318}
319
320impl Guard {
321    /// Always true.
322    pub fn always() -> Self {
323        Guard::Spec(Pred::Always)
324    }
325    /// State key holds boolean `true`.
326    pub fn is_true(key: impl Into<String>) -> Self {
327        Guard::Spec(Pred::IsTrue(key.into()))
328    }
329    /// State key is present.
330    pub fn is_set(key: impl Into<String>) -> Self {
331        Guard::Spec(Pred::IsSet(key.into()))
332    }
333    /// State key equals the given JSON value.
334    pub fn eq(key: impl Into<String>, value: impl Into<Value>) -> Self {
335        Guard::Spec(Pred::Eq(key.into(), value.into()))
336    }
337    /// All of the given state keys are present (extracted slots).
338    pub fn captured<I, S>(fields: I) -> Self
339    where
340        I: IntoIterator<Item = S>,
341        S: Into<String>,
342    {
343        Guard::Spec(Pred::Captured(fields.into_iter().map(Into::into).collect()))
344    }
345    /// The named tool has completed successfully.
346    pub fn called_ok(tool: impl Into<String>) -> Self {
347        Guard::Spec(Pred::CalledOk(tool.into()))
348    }
349    /// The named step is done.
350    pub fn done(step: impl Into<String>) -> Self {
351        Guard::Spec(Pred::Done(step.into()))
352    }
353    /// The caller's current turn settles the declared question `question`: a
354    /// boolean answered yes, a choice that picked an option, or a score. See
355    /// [`decided`].
356    pub fn decided(question: impl Into<String>) -> Self {
357        Self::decided_as(question, Expect::Yes)
358    }
359    /// The caller's current turn answers the boolean `question` no (or a
360    /// choice picks "none of these").
361    pub fn decided_no(question: impl Into<String>) -> Self {
362        Self::decided_as(question, Expect::No)
363    }
364    /// The caller's current turn picks `option` for the choice `question`.
365    pub fn decided_is(question: impl Into<String>, option: impl Into<String>) -> Self {
366        Self::decided_as(question, Expect::Is(option.into()))
367    }
368    /// The score `question` is at least `bound`.
369    pub fn decided_at_least(question: impl Into<String>, bound: f64) -> Self {
370        Self::decided_as(question, Expect::AtLeast(bound))
371    }
372    /// The score `question` is at most `bound`.
373    pub fn decided_at_most(question: impl Into<String>, bound: f64) -> Self {
374        Self::decided_as(question, Expect::AtMost(bound))
375    }
376    fn decided_as(question: impl Into<String>, expect: Expect) -> Self {
377        Guard::Spec(Pred::Decided(Decided {
378            question: question.into(),
379            expect,
380        }))
381    }
382    /// True once an orchestrated agent named `name` has produced a result
383    /// (its `{name}:result` state key is set). Pairs with the
384    /// [`orchestration`](crate::orchestration) `call`/`dispatch`/`background`.
385    pub fn resolved(name: impl AsRef<str>) -> Self {
386        Guard::Spec(Pred::IsSet(format!("{}:result", name.as_ref())))
387    }
388    /// Conjunction.
389    ///
390    /// If every input is a serializable atom, the result is a serializable
391    /// `Pred::All`. If any input is a [`Guard::custom`], the result is itself a
392    /// custom guard that evaluates the conjunction at runtime — the custom guard
393    /// is **never silently dropped** (it merely makes the combinator
394    /// non-serializable, which surfaces as an error only if you try to serialize
395    /// the flow).
396    pub fn all(guards: impl IntoIterator<Item = Guard>) -> Self {
397        let guards: Vec<Guard> = guards.into_iter().collect();
398        if guards.iter().all(|g| matches!(g, Guard::Spec(_))) {
399            Guard::Spec(Pred::All(specs_unchecked(guards)))
400        } else {
401            Guard::Custom(Arc::new(move |ctx| guards.iter().all(|g| g.eval(ctx))))
402        }
403    }
404    /// Disjunction.
405    ///
406    /// Mirrors [`Guard::all`]: custom inputs are preserved as a runtime closure
407    /// rather than erased.
408    pub fn any(guards: impl IntoIterator<Item = Guard>) -> Self {
409        let guards: Vec<Guard> = guards.into_iter().collect();
410        if guards.iter().all(|g| matches!(g, Guard::Spec(_))) {
411            Guard::Spec(Pred::Any(specs_unchecked(guards)))
412        } else {
413            Guard::Custom(Arc::new(move |ctx| guards.iter().any(|g| g.eval(ctx))))
414        }
415    }
416    /// Negation of a serializable atom.
417    #[allow(clippy::should_implement_trait)]
418    pub fn not(guard: Guard) -> Self {
419        match guard {
420            Guard::Spec(p) => Guard::Spec(Pred::Not(Box::new(p))),
421            // Negating a custom guard yields a custom guard.
422            Guard::Custom(f) => Guard::Custom(Arc::new(move |ctx| !f(ctx))),
423        }
424    }
425    /// This guard as a short prose clause, for telling a model what a refusal
426    /// is waiting on.
427    ///
428    /// A refusal that names only the tool leaves the model to guess the
429    /// precondition, and a wrong guess is indistinguishable from a wrong model:
430    /// in the governed collections evaluation, `record_promise_to_pay` was
431    /// refused with "not available in the current step", and the model — with
432    /// nothing else to go on — decided it must need to re-verify the caller and
433    /// asked for the card digits it had already checked.
434    pub fn describe(&self) -> String {
435        match self {
436            Guard::Spec(p) => p.describe(),
437            Guard::Custom(_) => "a condition set by the application".to_string(),
438        }
439    }
440
441    /// A bespoke closure over `(state, marking)`. Not serializable.
442    pub fn custom(f: impl Fn(&FlowCtx) -> bool + Send + Sync + 'static) -> Self {
443        Guard::Custom(Arc::new(f))
444    }
445
446    /// Evaluate the guard as the caller's next words could leave it: every
447    /// `decided` atom unknown, since its question is asked again about each
448    /// turn. `Some(value)` when no decision can change the outcome, `None`
449    /// when one could make the guard hold or fail. A custom guard is
450    /// evaluated as it stands.
451    pub fn possible(&self, ctx: &FlowCtx) -> Option<bool> {
452        match self {
453            Guard::Spec(p) => p.possible(ctx),
454            Guard::Custom(f) => Some(f(ctx)),
455        }
456    }
457
458    /// Evaluate the guard.
459    pub fn eval(&self, ctx: &FlowCtx) -> bool {
460        match self {
461            Guard::Spec(p) => p.eval(ctx),
462            Guard::Custom(f) => f(ctx),
463        }
464    }
465
466    /// Evaluate against state alone, with an empty [`Marking`].
467    ///
468    /// For contexts outside a governed flow (phase transitions, watcher
469    /// conditions) where no marking exists: `called_ok`/`done` atoms evaluate
470    /// `false` there — a validator should reject them in such positions.
471    pub fn eval_state(&self, state: &State) -> bool {
472        let marking = Marking::default();
473        self.eval(&FlowCtx {
474            state,
475            marking: &marking,
476        })
477    }
478
479    /// Evaluate to a [`GuardTrace`] — the predicate tree with per-node truth
480    /// values. A [`Guard::custom`] yields a single opaque node.
481    pub fn explain_trace(&self, ctx: &FlowCtx) -> GuardTrace {
482        match self {
483            Guard::Spec(p) => p.explain(ctx),
484            Guard::Custom(f) => GuardTrace {
485                desc: "a condition set by the application".to_string(),
486                holds: f(ctx),
487                children: Vec::new(),
488            },
489        }
490    }
491
492    fn referenced_steps(&self, out: &mut Vec<String>) {
493        if let Guard::Spec(p) = self {
494            p.referenced_steps(out);
495        }
496    }
497
498    fn referenced_state_keys(&self, out: &mut BTreeSet<String>) {
499        if let Guard::Spec(p) = self {
500            p.referenced_state_keys(out);
501        }
502    }
503
504    /// The questions this guard's `decided` atoms name.
505    pub fn decisions(&self) -> BTreeSet<String> {
506        let mut out = BTreeSet::new();
507        if let Guard::Spec(p) = self {
508            p.referenced_decisions(&mut out);
509        }
510        out
511    }
512
513    /// The state keys this guard reads (`is_true`/`is_set`/`eq`/`captured`
514    /// atoms). A custom guard reads nothing that can be named, so it
515    /// reports none.
516    pub fn state_keys(&self) -> BTreeSet<String> {
517        let mut keys = BTreeSet::new();
518        self.referenced_state_keys(&mut keys);
519        keys
520    }
521
522    fn referenced_tools(&self, out: &mut Vec<String>) {
523        if let Guard::Spec(p) = self {
524            p.referenced_tools(out);
525        }
526    }
527}
528
529/// Unwrap a list of guards known to be all `Spec` into their predicates.
530///
531/// The caller (`Guard::all`/`Guard::any`) only invokes this after verifying every
532/// guard is a `Spec`, so the `Custom` arm is unreachable.
533fn specs_unchecked(guards: Vec<Guard>) -> Vec<Pred> {
534    guards
535        .into_iter()
536        .map(|g| match g {
537            Guard::Spec(p) => p,
538            Guard::Custom(_) => unreachable!("specs_unchecked called with a custom guard"),
539        })
540        .collect()
541}
542
543impl Serialize for Guard {
544    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
545        match self {
546            Guard::Spec(p) => p.serialize(s),
547            Guard::Custom(_) => Err(serde::ser::Error::custom(
548                "custom guards are not serializable; use Guard atoms for data-driven flows",
549            )),
550        }
551    }
552}
553
554impl<'de> Deserialize<'de> for Guard {
555    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
556        Ok(Guard::Spec(Pred::deserialize(d)?))
557    }
558}
559
560// A serializable guard is exactly a `Pred` atom on the wire (the `Custom`
561// variant is code-only and rejected by `Serialize`), so its JSON Schema is
562// `Pred`'s. Inline the `Pred` subschema wherever a `Guard` appears.
563impl schemars::JsonSchema for Guard {
564    fn is_referenceable() -> bool {
565        false
566    }
567    fn schema_name() -> String {
568        "Guard".to_string()
569    }
570    fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
571        generator.subschema_for::<Pred>()
572    }
573}
574
575impl std::fmt::Debug for Guard {
576    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
577        match self {
578            Guard::Spec(p) => write!(f, "{p:?}"),
579            Guard::Custom(_) => write!(f, "Custom(<fn>)"),
580        }
581    }
582}
583
584/// A dependency edge into a step.
585///
586/// In JSON, a plain string (`"verify"`) is an unconditional edge — satisfied
587/// once the source step is done. An object (`{"step": "triage", "when":
588/// {"is_true": "routine"}}`) is a **conditional edge**: satisfied only while
589/// the source is done *and* the guard holds. Conditional edges out of one
590/// source into sibling steps are how a flow branches; pair them with
591/// [`Join::Any`] on the merge step. Unconditional edges serialize back to the
592/// plain string form, so existing documents round-trip unchanged.
593#[derive(Clone, Debug)]
594pub struct Edge {
595    /// The source step this edge depends on.
596    pub step: String,
597    /// Optional condition; the edge is satisfied only while it holds.
598    pub when: Option<Guard>,
599}
600
601impl Edge {
602    /// An unconditional edge from `step`.
603    pub fn to(step: impl Into<String>) -> Self {
604        Edge {
605            step: step.into(),
606            when: None,
607        }
608    }
609    /// A conditional edge from `step`, satisfied only while `when` holds.
610    pub fn when(step: impl Into<String>, when: Guard) -> Self {
611        Edge {
612            step: step.into(),
613            when: Some(when),
614        }
615    }
616}
617
618impl<S: Into<String>> From<S> for Edge {
619    fn from(step: S) -> Self {
620        Edge::to(step)
621    }
622}
623
624impl Serialize for Edge {
625    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
626        match &self.when {
627            // Unconditional edges keep the original plain-string form.
628            None => self.step.serialize(s),
629            Some(when) => {
630                use serde::ser::SerializeStruct;
631                let mut out = s.serialize_struct("Edge", 2)?;
632                out.serialize_field("step", &self.step)?;
633                out.serialize_field("when", when)?;
634                out.end()
635            }
636        }
637    }
638}
639
640impl<'de> Deserialize<'de> for Edge {
641    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
642        #[derive(Deserialize)]
643        #[serde(untagged)]
644        enum Repr {
645            Simple(String),
646            Conditional {
647                step: String,
648                #[serde(default)]
649                when: Option<Guard>,
650            },
651        }
652        Ok(match Repr::deserialize(d)? {
653            Repr::Simple(step) => Edge { step, when: None },
654            Repr::Conditional { step, when } => Edge { step, when },
655        })
656    }
657}
658
659impl schemars::JsonSchema for Edge {
660    fn schema_name() -> String {
661        "Edge".to_string()
662    }
663    fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
664        #[derive(schemars::JsonSchema)]
665        #[serde(untagged)]
666        #[allow(
667            dead_code,
668            reason = "variants exist only to derive the JSON schema; never constructed"
669        )]
670        enum EdgeSchema {
671            Simple(String),
672            Conditional { step: String, when: Option<Pred> },
673        }
674        EdgeSchema::json_schema(generator)
675    }
676}
677
678/// How a step's dependency edges combine.
679#[derive(
680    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
681)]
682#[serde(rename_all = "snake_case")]
683pub enum Join {
684    /// Every edge must be satisfied (the default — a synchronizing join).
685    #[default]
686    All,
687    /// Any one satisfied edge suffices — the merge node after a branch.
688    Any,
689}
690
691impl Join {
692    fn is_all(&self) -> bool {
693        *self == Join::All
694    }
695}
696
697/// A node in the flow DAG — the only node type.
698#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema)]
699pub struct Step {
700    /// Unique step id.
701    pub id: String,
702    /// Dependency edges; how they combine is set by `join`.
703    #[serde(default, skip_serializing_if = "Vec::is_empty")]
704    pub after: Vec<Edge>,
705    /// How the `after` edges combine: `all` (default) or `any`.
706    #[serde(default, skip_serializing_if = "Join::is_all")]
707    pub join: Join,
708    /// Extra eligibility predicate beyond dependencies.
709    #[serde(default, skip_serializing_if = "Option::is_none")]
710    pub gate: Option<Guard>,
711    /// Completion condition. Required for non-terminal steps.
712    #[serde(default, skip_serializing_if = "Option::is_none")]
713    pub done: Option<Guard>,
714    /// Instruction imposed while this step is active (projected as steering).
715    #[serde(default, skip_serializing_if = "Option::is_none")]
716    pub posture: Option<String>,
717    /// A grounding template projected while active: a curated, `State`-interpolated
718    /// fact line that pins the model to known values (anti-hallucination). See
719    /// [`render_ground`]. Serializable, like `posture`.
720    #[serde(default, skip_serializing_if = "Option::is_none")]
721    pub ground: Option<String>,
722    /// Tools available while this step is active (whitelist; empty = no restriction).
723    #[serde(default, skip_serializing_if = "Vec::is_empty")]
724    pub allow: Vec<String>,
725    /// Tools forbidden while this step is active.
726    #[serde(default, skip_serializing_if = "Vec::is_empty")]
727    pub deny: Vec<String>,
728    /// A terminal step — reaching it (deps + gate) marks it done with no milestone.
729    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
730    pub terminal: bool,
731}
732
733/// A cross-cutting flow constraint.
734#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema)]
735#[serde(rename_all = "snake_case")]
736pub enum Constraint {
737    /// A tool may complete at most once.
738    Once(String),
739    /// Step `0` must be done before step `1` starts.
740    Before(String, String),
741    /// A tool is forbidden until the guard holds.
742    NeverUntil {
743        /// The gated tool.
744        tool: String,
745        /// The guard that must hold to permit it.
746        until: Guard,
747    },
748    /// These steps must be done for the flow to be complete.
749    Require(Vec<String>),
750    /// Un-latch the named steps when the guard *becomes* true (rising edge) —
751    /// the loop primitive. The DAG stays acyclic and statically checkable;
752    /// iteration is explicit marking surgery instead of back-edges.
753    ///
754    /// A reset also forgives the completion evidence the steps' `done` guards
755    /// reference: `called_ok` counts for those tools are cleared (so a `once`
756    /// on such a tool permits one run per latch-cycle). State keys the guards
757    /// read are the application's to clear — a reset never touches [`State`].
758    Reset {
759        /// The steps to un-latch.
760        steps: Vec<String>,
761        /// Fires on this guard's rising edge.
762        when: Guard,
763    },
764}
765
766/// A governed conversation/tool DAG.
767#[derive(Clone, Debug, Default, Serialize, Deserialize, schemars::JsonSchema)]
768pub struct Flow {
769    /// The steps (DAG nodes).
770    pub steps: Vec<Step>,
771    /// Cross-cutting constraints.
772    #[serde(default, skip_serializing_if = "Vec::is_empty")]
773    pub constraints: Vec<Constraint>,
774    /// Tools that require confirmation when reached (set by `commit`).
775    #[serde(default, skip_serializing_if = "Vec::is_empty")]
776    pub confirm_tools: Vec<String>,
777    /// Cross-cutting tools exempt from step `allow` whitelists.
778    ///
779    /// A step's `allow` list excludes by omission, which is correct for the
780    /// domain tools a step is *about* and wrong for infrastructure no step is
781    /// about — memory recall, escalation, logging. Naming a tool here says "this
782    /// is not part of any step's repertoire", not "this is ungovernable":
783    /// `deny`, `once` and `never(..).until(..)` all still bind, because each of
784    /// those *names* the tool and so is a decision about it.
785    #[serde(default, skip_serializing_if = "Vec::is_empty")]
786    pub ambient: Vec<String>,
787}
788
789impl Flow {
790    /// Every question a `decided` atom names in this flow: step gates and
791    /// `done` guards, edge guards, and constraints.
792    pub fn decisions(&self) -> BTreeSet<String> {
793        let mut out = BTreeSet::new();
794        let mut add = |g: &Guard| out.extend(g.decisions());
795        for step in &self.steps {
796            step.gate.iter().chain(step.done.iter()).for_each(&mut add);
797            step.after
798                .iter()
799                .filter_map(|e| e.when.as_ref())
800                .for_each(&mut add);
801        }
802        for c in &self.constraints {
803            match c {
804                Constraint::NeverUntil { until, .. } => add(until),
805                Constraint::Reset { when, .. } => add(when),
806                _ => {}
807            }
808        }
809        out
810    }
811
812    /// Start building a flow.
813    #[allow(
814        clippy::new_ret_no_self,
815        reason = "Flow::new() is the builder entry point; a Flow comes from FlowBuilder::build/compile"
816    )]
817    pub fn new() -> FlowBuilder {
818        FlowBuilder::default()
819    }
820
821    fn step(&self, id: &str) -> Option<&Step> {
822        self.steps.iter().find(|s| s.id == id)
823    }
824
825    /// Validate referential integrity and acyclicity. Every problem found is
826    /// reported in the returned [`ConfigError`], not just the first.
827    pub fn validate(&self) -> Result<(), ConfigError> {
828        let mut errs = Vec::new();
829        let ids: BTreeSet<&str> = self.steps.iter().map(|s| s.id.as_str()).collect();
830        if ids.len() != self.steps.len() {
831            errs.push("duplicate step ids".into());
832        }
833        for s in &self.steps {
834            for d in &s.after {
835                if !ids.contains(d.step.as_str()) {
836                    errs.push(format!(
837                        "step '{}' depends on unknown step '{}'",
838                        s.id, d.step
839                    ));
840                }
841                if let Some(when) = &d.when {
842                    let mut refs = Vec::new();
843                    when.referenced_steps(&mut refs);
844                    for r in refs {
845                        if !ids.contains(r.as_str()) {
846                            errs.push(format!(
847                                "step '{}' edge condition references unknown step '{r}'",
848                                s.id
849                            ));
850                        }
851                    }
852                }
853            }
854            if !s.terminal && s.done.is_none() {
855                errs.push(format!(
856                    "non-terminal step '{}' has no `done` condition (it can never complete)",
857                    s.id
858                ));
859            }
860            for g in s.gate.iter().chain(s.done.iter()) {
861                let mut refs = Vec::new();
862                g.referenced_steps(&mut refs);
863                for r in refs {
864                    if !ids.contains(r.as_str()) {
865                        errs.push(format!(
866                            "step '{}' guard references unknown step '{r}'",
867                            s.id
868                        ));
869                    }
870                }
871            }
872        }
873        for c in &self.constraints {
874            match c {
875                Constraint::Before(a, b) => {
876                    for x in [a, b] {
877                        if !ids.contains(x.as_str()) {
878                            errs.push(format!("constraint `before` references unknown step '{x}'"));
879                        }
880                    }
881                }
882                Constraint::Require(rs) => {
883                    for r in rs {
884                        if !ids.contains(r.as_str()) {
885                            errs.push(format!(
886                                "constraint `require` references unknown step '{r}'"
887                            ));
888                        }
889                    }
890                }
891                Constraint::Reset { steps, .. } => {
892                    for r in steps {
893                        if !ids.contains(r.as_str()) {
894                            errs.push(format!("constraint `reset` references unknown step '{r}'"));
895                        }
896                    }
897                }
898                _ => {}
899            }
900        }
901        if self.has_cycle() {
902            errs.push("flow dependency graph has a cycle (must be a DAG)".into());
903        }
904        ConfigError::from_issues(errs)
905    }
906
907    /// Every tool name referenced anywhere in the flow (allow/deny/once/
908    /// never_until/confirm). The universe over which [`ToolSurface`] reasons.
909    fn tool_universe(&self) -> BTreeSet<String> {
910        let mut tools = BTreeSet::new();
911        for s in &self.steps {
912            tools.extend(s.allow.iter().cloned());
913            tools.extend(s.deny.iter().cloned());
914        }
915        for c in &self.constraints {
916            match c {
917                Constraint::Once(t) => {
918                    tools.insert(t.clone());
919                }
920                Constraint::NeverUntil { tool, .. } => {
921                    tools.insert(tool.clone());
922                }
923                _ => {}
924            }
925        }
926        tools.extend(self.confirm_tools.iter().cloned());
927        tools.extend(self.ambient.iter().cloned());
928        tools
929    }
930
931    /// Every state key any guard in the flow reads (`is_true`/`is_set`/`eq`/
932    /// `captured` atoms in step gates, completion guards, and `never…until`
933    /// constraints).
934    ///
935    /// A key in this set that nothing in the session *writes* — no tool, no
936    /// extractor, no promotion — can never latch, which is the dominant silent
937    /// failure in data-authored flows. Validators diff this set against the
938    /// declared writers to catch it at load time, the way
939    /// [`compile_with_tools`](Self::compile_with_tools) catches tool typos.
940    pub fn state_keys_read(&self) -> BTreeSet<String> {
941        let mut keys = BTreeSet::new();
942        for s in &self.steps {
943            for g in s.gate.iter().chain(s.done.iter()) {
944                g.referenced_state_keys(&mut keys);
945            }
946            for e in &s.after {
947                if let Some(when) = &e.when {
948                    when.referenced_state_keys(&mut keys);
949                }
950            }
951        }
952        for c in &self.constraints {
953            match c {
954                Constraint::NeverUntil { until, .. } => until.referenced_state_keys(&mut keys),
955                Constraint::Reset { when, .. } => when.referenced_state_keys(&mut keys),
956                _ => {}
957            }
958        }
959        keys
960    }
961
962    /// Steps reachable from a root (a step with no `after` deps), following both
963    /// `after` edges and `Before(a, b)` ordering edges.
964    fn reachable_steps(&self) -> BTreeSet<String> {
965        let ids: BTreeSet<&str> = self.steps.iter().map(|s| s.id.as_str()).collect();
966        // Forward edges: a -> b when b.after contains a, or Before(a, b).
967        let mut succ: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
968        for s in &self.steps {
969            for d in &s.after {
970                if ids.contains(d.step.as_str()) {
971                    succ.entry(d.step.as_str()).or_default().push(s.id.as_str());
972                }
973            }
974        }
975        for c in &self.constraints {
976            if let Constraint::Before(a, b) = c
977                && ids.contains(a.as_str())
978                && ids.contains(b.as_str())
979            {
980                succ.entry(a.as_str()).or_default().push(b.as_str());
981            }
982        }
983        let roots: Vec<&str> = self
984            .steps
985            .iter()
986            .filter(|s| s.after.is_empty())
987            .map(|s| s.id.as_str())
988            .collect();
989        let mut seen = BTreeSet::new();
990        let mut stack = roots;
991        while let Some(id) = stack.pop() {
992            if seen.insert(id.to_string())
993                && let Some(next) = succ.get(id)
994            {
995                stack.extend(next.iter().copied());
996            }
997        }
998        seen
999    }
1000
1001    /// Compile and validate the flow into a [`CompiledFlow`], turning a class of
1002    /// runtime surprises into load-time errors.
1003    ///
1004    /// On top of [`validate`](Self::validate)'s referential/acyclicity checks this
1005    /// reports: unreachable steps, commit tools guarded by an always-true
1006    /// condition (an effectively *unguarded* commit, which defeats the
1007    /// confirm-before-commit contract), `never…until` guards whose `done(step)`
1008    /// atoms reference unknown steps (unsatisfiable — the tool would be forbidden
1009    /// forever), and ordering cycles across the combined `after` + `before` edges
1010    /// (which deadlock every step on the cycle). Precomputes the [`ToolSurface`]
1011    /// universe.
1012    ///
1013    /// To additionally validate tool names against a known registry, use
1014    /// [`compile_with_tools`](Self::compile_with_tools).
1015    pub fn compile(self) -> Result<CompiledFlow, FlowErrors> {
1016        self.compile_internal(None)
1017    }
1018
1019    /// Compile like [`compile`](Self::compile), additionally validating every
1020    /// tool name the flow references (step `allow`/`deny`, `once`,
1021    /// `never…until`, and commit/confirm tools) against the given registry of
1022    /// known tool names.
1023    ///
1024    /// A referenced tool missing from `tools` is reported as
1025    /// [`FlowError::UnknownTool`] — catching typos and drift between a flow
1026    /// script and the tools actually registered on the session.
1027    ///
1028    /// ```ignore
1029    /// let compiled = flow.compile_with_tools(&["lookup_account", "charge_card"])?;
1030    /// ```
1031    pub fn compile_with_tools(self, tools: &[&str]) -> Result<CompiledFlow, FlowErrors> {
1032        self.compile_internal(Some(tools))
1033    }
1034
1035    fn compile_internal(self, registry: Option<&[&str]>) -> Result<CompiledFlow, FlowErrors> {
1036        let mut errors = Vec::new();
1037        if let Err(err) = self.validate() {
1038            errors.extend(err.issues.into_iter().map(FlowError::Invalid));
1039        }
1040
1041        // Graph-shape checks (only meaningful once the graph is acyclic/valid).
1042        if errors.is_empty() {
1043            // Unreachable steps.
1044            let reachable = self.reachable_steps();
1045            for s in &self.steps {
1046                if !reachable.contains(&s.id) {
1047                    errors.push(FlowError::UnreachableStep(s.id.clone()));
1048                }
1049            }
1050            // Ordering cycles across the combined `after` + `before(a, b)` edges.
1051            // `validate()` only walks `after`; a cycle closed by a `Before`
1052            // constraint deadlocks every step on it (none can become eligible).
1053            if let Some(cycle) = self.ordering_cycle() {
1054                errors.push(FlowError::OrderingCycle(cycle));
1055            }
1056        }
1057
1058        // A commit tool guarded by an always-true condition is effectively
1059        // unguarded — the confirm-before-commit contract would never gate it.
1060        for tool in &self.confirm_tools {
1061            let guard = self.constraints.iter().find_map(|c| match c {
1062                Constraint::NeverUntil { tool: t, until } if t == tool => Some(until),
1063                _ => None,
1064            });
1065            let unguarded = matches!(guard, None | Some(Guard::Spec(Pred::Always)));
1066            if unguarded {
1067                errors.push(FlowError::UnguardedCommitTool(tool.clone()));
1068            }
1069        }
1070
1071        // An unsatisfiable `never(tool).until(guard)`: the guard's `done(step)`
1072        // atom references a step that doesn't exist, so it can never latch and
1073        // the tool is forbidden forever. (Step gate/done guards are already
1074        // covered by `validate()`; constraints were not.)
1075        let ids: BTreeSet<&str> = self.steps.iter().map(|s| s.id.as_str()).collect();
1076        for c in &self.constraints {
1077            if let Constraint::NeverUntil { tool, until } = c {
1078                let mut refs = Vec::new();
1079                until.referenced_steps(&mut refs);
1080                for r in refs {
1081                    if !ids.contains(r.as_str()) {
1082                        errors.push(FlowError::UnsatisfiableGuard {
1083                            tool: tool.clone(),
1084                            step: r,
1085                        });
1086                    }
1087                }
1088            }
1089        }
1090
1091        // Dangling tool names vs a known registry (opt-in).
1092        if let Some(known) = registry {
1093            for tool in self.tool_universe() {
1094                if !known.contains(&tool.as_str()) {
1095                    errors.push(FlowError::UnknownTool(tool));
1096                }
1097            }
1098        }
1099
1100        if errors.is_empty() {
1101            let surface = ToolSurface {
1102                tools: self.tool_universe(),
1103            };
1104            Ok(CompiledFlow {
1105                flow: self,
1106                surface,
1107            })
1108        } else {
1109            Err(FlowErrors(errors))
1110        }
1111    }
1112
1113    /// Find a cycle over the combined dependency edges (`after` plus
1114    /// `before(a, b)` ordering constraints), if any. Returns the step ids on
1115    /// the cycle path. `None` when the combined graph is acyclic.
1116    fn ordering_cycle(&self) -> Option<Vec<String>> {
1117        // Predecessor edges: step -> everything that must be done before it.
1118        let mut deps: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
1119        for s in &self.steps {
1120            let entry = deps.entry(s.id.as_str()).or_default();
1121            entry.extend(s.after.iter().map(|e| e.step.as_str()));
1122        }
1123        for c in &self.constraints {
1124            if let Constraint::Before(a, b) = c {
1125                deps.entry(b.as_str()).or_default().push(a.as_str());
1126            }
1127        }
1128        // DFS with colors; on a back-edge, report the current path suffix.
1129        fn dfs<'a>(
1130            id: &'a str,
1131            deps: &BTreeMap<&'a str, Vec<&'a str>>,
1132            color: &mut BTreeMap<&'a str, u8>,
1133            path: &mut Vec<&'a str>,
1134        ) -> Option<Vec<String>> {
1135            color.insert(id, 1);
1136            path.push(id);
1137            for d in deps.get(id).into_iter().flatten() {
1138                match color.get(d).copied() {
1139                    Some(1) => {
1140                        let start = path.iter().position(|p| p == d).unwrap_or(0);
1141                        return Some(
1142                            path[start..]
1143                                .iter()
1144                                .map(std::string::ToString::to_string)
1145                                .collect(),
1146                        );
1147                    }
1148                    Some(2) => {}
1149                    _ => {
1150                        if let Some(cycle) = dfs(d, deps, color, path) {
1151                            return Some(cycle);
1152                        }
1153                    }
1154                }
1155            }
1156            path.pop();
1157            color.insert(id, 2);
1158            None
1159        }
1160        let mut color: BTreeMap<&str, u8> = BTreeMap::new();
1161        for s in &self.steps {
1162            if color.get(s.id.as_str()).copied().unwrap_or(0) == 0 {
1163                let mut path = Vec::new();
1164                if let Some(cycle) = dfs(&s.id, &deps, &mut color, &mut path) {
1165                    return Some(cycle);
1166                }
1167            }
1168        }
1169        None
1170    }
1171
1172    fn has_cycle(&self) -> bool {
1173        // DFS with colors over the `after` dependency edges.
1174        let mut color: BTreeMap<&str, u8> = BTreeMap::new();
1175        fn dfs<'a>(flow: &'a Flow, id: &'a str, color: &mut BTreeMap<&'a str, u8>) -> bool {
1176            color.insert(id, 1);
1177            if let Some(step) = flow.step(id) {
1178                for d in &step.after {
1179                    match color.get(d.step.as_str()).copied() {
1180                        Some(1) => return true,
1181                        Some(2) => {}
1182                        _ => {
1183                            if dfs(flow, &d.step, color) {
1184                                return true;
1185                            }
1186                        }
1187                    }
1188                }
1189            }
1190            color.insert(id, 2);
1191            false
1192        }
1193        for s in &self.steps {
1194            if color.get(s.id.as_str()).copied().unwrap_or(0) == 0 && dfs(self, &s.id, &mut color) {
1195                return true;
1196            }
1197        }
1198        false
1199    }
1200
1201    /// Render the flow as a Mermaid `flowchart` — the spec *is* the diagram.
1202    pub fn to_mermaid(&self) -> String {
1203        let mut out = String::from("flowchart TD\n");
1204        for s in &self.steps {
1205            let shape = if s.terminal {
1206                format!("    {}([{}])\n", s.id, s.id)
1207            } else {
1208                format!("    {}[{}]\n", s.id, s.id)
1209            };
1210            out.push_str(&shape);
1211        }
1212        for s in &self.steps {
1213            for d in &s.after {
1214                match &d.when {
1215                    Some(when) => {
1216                        let label = when.describe().replace('|', "/");
1217                        out.push_str(&format!("    {} -->|{label}| {}\n", d.step, s.id));
1218                    }
1219                    None => out.push_str(&format!("    {} --> {}\n", d.step, s.id)),
1220                }
1221            }
1222        }
1223        out
1224    }
1225}
1226
1227/// The runtime position in a flow: which steps are done and how often each
1228/// tool has succeeded.
1229#[derive(Clone, Debug, Default)]
1230pub struct Marking {
1231    /// Steps that have latched done.
1232    pub done: BTreeSet<String>,
1233    /// Per-tool successful-completion counts.
1234    pub tool_ok: BTreeMap<String, u32>,
1235    /// Turns observed.
1236    pub turns: u32,
1237}
1238
1239/// The conformance status of a step.
1240#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1241#[serde(rename_all = "snake_case")]
1242pub enum Verdict {
1243    /// Not yet eligible.
1244    Pending,
1245    /// Eligible and awaiting completion.
1246    Active,
1247    /// Completed.
1248    Done,
1249    /// A successor completed while this never did (an out-of-order deviation).
1250    Skipped,
1251}
1252
1253/// A recorded conformance deviation (observe mode) or denial (enforce mode).
1254#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
1255pub struct Violation {
1256    /// What was attempted (e.g. a tool name).
1257    pub subject: String,
1258    /// Why it was a violation.
1259    pub reason: String,
1260}
1261
1262/// How a [`FlowMonitor`] treats off-path activity — enforcement vs observation.
1263///
1264/// Distinct from [`AgentMode`], which is the unrelated *resolver execution
1265/// discipline* (`Call`/`Dispatch`/`Background`).
1266#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
1267pub enum Enforcement {
1268    /// Block inadmissible tool calls and steer back on-path.
1269    #[default]
1270    Enforce,
1271    /// Allow everything, but record deviations for audit/analytics.
1272    Observe,
1273}
1274
1275/// An action fired the first time a step becomes active: run an agent in an
1276/// [`AgentMode`]. Built with [`on_enter`]. The result lands in `{name}:result` (the
1277/// name defaults to the step id), so a *downstream* step can complete on it via
1278/// [`Guard::resolved`] — this is how a flow drives orchestration in-session.
1279#[derive(Clone)]
1280pub struct StepAction {
1281    name: Option<String>,
1282    agent: Arc<dyn TextAgent>,
1283    mode: AgentMode,
1284}
1285
1286/// Build a step-enter action that runs `agent` in `mode` when the step first
1287/// activates. Pair with [`FlowMonitor::on_enter`].
1288///
1289/// ```ignore
1290/// let mon = FlowMonitor::new(flow, Enforcement::Enforce)
1291///     .on_enter("check", on_enter(availability_agent, AgentMode::Dispatch));
1292/// ```
1293pub fn on_enter(agent: Arc<dyn TextAgent>, mode: AgentMode) -> StepAction {
1294    StepAction {
1295        name: None,
1296        agent,
1297        mode,
1298    }
1299}
1300
1301impl StepAction {
1302    /// Override the result name (defaults to the step id it is attached to).
1303    pub fn named(mut self, name: impl Into<String>) -> Self {
1304        self.name = Some(name.into());
1305        self
1306    }
1307
1308    /// Run the action. `Call` awaits inline; `Dispatch`/`Background` spawn it
1309    /// detached so the turn is never blocked.
1310    pub(crate) async fn fire(&self, step_id: &str, state: &State) {
1311        let name = self.name.clone().unwrap_or_else(|| step_id.to_string());
1312        match self.mode {
1313            AgentMode::Call => {
1314                let _ = call_agent(&name, self.agent.clone(), state).await;
1315            }
1316            AgentMode::Dispatch | AgentMode::Background => {
1317                let agent = self.agent.clone();
1318                let state = state.clone();
1319                tokio::spawn(async move {
1320                    let _ = call_agent(&name, agent, &state).await;
1321                });
1322            }
1323        }
1324    }
1325}
1326
1327/// A shared, lock-protected [`FlowMonitor`] — the form in which the Live
1328/// control plane owns a governed flow, so runtime surfaces (e.g.
1329/// [`LiveHandle::explain`](crate::live::LiveHandle::explain)) can
1330/// snapshot it concurrently. All monitor methods are synchronous: lock
1331/// briefly and never hold the guard across an `await`.
1332pub type SharedFlowMonitor = Arc<parking_lot::Mutex<FlowMonitor>>;
1333
1334/// Observes the session trace, maintains the [`Marking`], answers tool
1335/// admissibility, and projects active postures.
1336pub struct FlowMonitor {
1337    flow: Flow,
1338    mode: Enforcement,
1339    marking: Marking,
1340    violations: Vec<Violation>,
1341    /// Per-step actions fired the first time the step becomes active.
1342    enter_actions: HashMap<String, StepAction>,
1343    /// Steps whose `on_enter` action has already fired (fire-once).
1344    announced: BTreeSet<String>,
1345    /// Previous guard values for `Constraint::Reset` rising-edge detection,
1346    /// in constraint order.
1347    reset_prev: Vec<bool>,
1348}
1349
1350impl FlowMonitor {
1351    /// Create a monitor for a (presumed-valid) flow.
1352    ///
1353    /// Prefer [`FlowMonitor::compiled`] or [`FlowMonitor::try_new`], which carry
1354    /// proof of compilation; this convenience skips compilation for flows already
1355    /// known valid (e.g. built in-process by trusted code).
1356    pub fn new(flow: Flow, mode: Enforcement) -> Self {
1357        Self {
1358            flow,
1359            mode,
1360            marking: Marking::default(),
1361            violations: Vec::new(),
1362            enter_actions: HashMap::new(),
1363            announced: BTreeSet::new(),
1364            reset_prev: Vec::new(),
1365        }
1366    }
1367
1368    /// Create a monitor from a [`CompiledFlow`] — the validated path.
1369    pub fn compiled(flow: CompiledFlow, mode: Enforcement) -> Self {
1370        Self::new(flow.into_flow(), mode)
1371    }
1372
1373    /// Compile `flow` and create a monitor, surfacing structural errors instead
1374    /// of trusting the caller.
1375    pub fn try_new(flow: Flow, mode: Enforcement) -> Result<Self, FlowErrors> {
1376        Ok(Self::compiled(flow.compile()?, mode))
1377    }
1378
1379    /// Wrap this monitor in a [`SharedFlowMonitor`] for shared ownership
1380    /// between the control lane (which advances it) and runtime accessors
1381    /// (which snapshot it, e.g.
1382    /// [`LiveHandle::explain`](crate::live::LiveHandle::explain)).
1383    pub fn into_shared(self) -> SharedFlowMonitor {
1384        Arc::new(parking_lot::Mutex::new(self))
1385    }
1386
1387    /// Wrap this monitor as the main layer of a [`FlowStack`] with no
1388    /// digressions — the form the Live control plane drives.
1389    pub fn into_stack(self) -> FlowStack {
1390        FlowStack::from_monitor(self)
1391    }
1392
1393    /// Re-enter the flow from its start: forget the marking, the fired
1394    /// `on_enter` actions and the reset edges. The flow, mode and registered
1395    /// actions are kept, and recorded violations stay for audit. `State` is not
1396    /// touched — the next re-latch runs against whatever facts it holds.
1397    pub fn restart(&mut self) {
1398        self.marking = Marking::default();
1399        self.announced.clear();
1400        self.reset_prev.clear();
1401    }
1402
1403    /// Explain the current control-plane state: active steps, which tools are
1404    /// admitted vs blocked (with reasons), and unmet requirements.
1405    ///
1406    /// This is the deterministic answer to "why did the assistant ask that?" —
1407    /// model-readable, without the model driving control flow.
1408    pub fn explain(&self, state: &State) -> FlowExplanation {
1409        let active_steps = self.active_steps(state);
1410        let active: Vec<String> = active_steps.iter().map(|s| s.id.clone()).collect();
1411        let ctx = self.ctx(state);
1412        let active_progress = active_steps
1413            .iter()
1414            .filter_map(|s| {
1415                s.done
1416                    .as_ref()
1417                    .map(|g| (s.id.clone(), g.explain_trace(&ctx)))
1418            })
1419            .collect();
1420        let mut allowed_tools = Vec::new();
1421        let mut blocked_tools = BTreeMap::new();
1422        for tool in self.flow.tool_universe() {
1423            match self.admits_tool(&tool, state) {
1424                Ok(()) => allowed_tools.push(tool),
1425                Err(reason) => {
1426                    blocked_tools.insert(tool, reason);
1427                }
1428            }
1429        }
1430        FlowExplanation {
1431            active,
1432            allowed_tools,
1433            blocked_tools,
1434            missing_requirements: self.unmet_requirements(),
1435            active_progress,
1436        }
1437    }
1438
1439    /// Attach an action fired the first time `step` becomes active (see
1440    /// [`on_enter`](on_enter())). Chainable at construction time.
1441    pub fn on_enter(mut self, step: impl Into<String>, action: StepAction) -> Self {
1442        self.enter_actions.insert(step.into(), action);
1443        self
1444    }
1445
1446    /// Steps that became active since the last call — each reported exactly once
1447    /// over the session. Drives [`on_enter`](Self::on_enter) firing.
1448    pub fn take_newly_active(&mut self, state: &State) -> Vec<String> {
1449        let mut fresh = Vec::new();
1450        for s in self.active_steps(state) {
1451            if !self.announced.contains(&s.id) {
1452                fresh.push(s.id.clone());
1453            }
1454        }
1455        for id in &fresh {
1456            self.announced.insert(id.clone());
1457        }
1458        fresh
1459    }
1460
1461    /// The enter-action registered for a step, if any.
1462    pub fn enter_action(&self, step: &str) -> Option<&StepAction> {
1463        self.enter_actions.get(step)
1464    }
1465
1466    /// Fire enter-actions for every step that just became active. Convenience
1467    /// over [`take_newly_active`](Self::take_newly_active) + [`enter_action`](Self::enter_action);
1468    /// call it right after [`on_turn`](Self::on_turn).
1469    pub async fn fire_enter_actions(&mut self, state: &State) {
1470        for id in self.take_newly_active(state) {
1471            if let Some(action) = self.enter_actions.get(&id) {
1472                action.fire(&id, state).await;
1473            }
1474        }
1475    }
1476
1477    /// The enforcement mode this monitor runs in.
1478    pub fn mode(&self) -> Enforcement {
1479        self.mode
1480    }
1481
1482    /// Replace a step's posture in place. Returns `false` if no such step.
1483    ///
1484    /// Postures are re-projected at every turn boundary, so an edit takes
1485    /// effect on the next turn — the safe subset of live spec editing. The
1486    /// DAG, guards, and tool gates are structural and stay fixed.
1487    pub fn set_posture(&mut self, step_id: &str, posture: Option<String>) -> bool {
1488        match self.flow.steps.iter_mut().find(|s| s.id == step_id) {
1489            Some(step) => {
1490                step.posture = posture;
1491                true
1492            }
1493            None => false,
1494        }
1495    }
1496
1497    /// Replace a step's grounding template in place. Returns `false` if no
1498    /// such step. Same next-turn semantics as [`set_posture`](Self::set_posture).
1499    pub fn set_ground(&mut self, step_id: &str, ground: Option<String>) -> bool {
1500        match self.flow.steps.iter_mut().find(|s| s.id == step_id) {
1501            Some(step) => {
1502                step.ground = ground;
1503                true
1504            }
1505            None => false,
1506        }
1507    }
1508
1509    /// Evaluate a [`Guard`] against this monitor's current context (the given
1510    /// `state` plus the monitor's marking). Used to test overlay/digression
1511    /// triggers without exposing the internal context.
1512    pub fn eval(&self, guard: &Guard, state: &State) -> bool {
1513        guard.eval(&self.ctx(state))
1514    }
1515    /// The current marking.
1516    pub fn marking(&self) -> &Marking {
1517        &self.marking
1518    }
1519    /// Recorded violations.
1520    pub fn violations(&self) -> &[Violation] {
1521        &self.violations
1522    }
1523
1524    /// Record a deviation the *caller* detected — one this monitor cannot see
1525    /// for itself. A [`FlowStack`] uses it for a tool called after a
1526    /// `Resume::Terminate` digression ended the conversation: the denial is the
1527    /// stack's, not this flow's, so `observe_tool` would find nothing wrong.
1528    pub fn record_violation(&mut self, subject: impl Into<String>, reason: impl Into<String>) {
1529        self.violations.push(Violation {
1530            subject: subject.into(),
1531            reason: reason.into(),
1532        });
1533    }
1534    /// The underlying flow.
1535    pub fn flow(&self) -> &Flow {
1536        &self.flow
1537    }
1538
1539    fn ctx<'a>(&'a self, state: &'a State) -> FlowCtx<'a> {
1540        FlowCtx {
1541            state,
1542            marking: &self.marking,
1543        }
1544    }
1545
1546    fn eligible(&self, step: &Step, state: &State) -> bool {
1547        let ctx = self.ctx(state);
1548        let edge_ok = |e: &Edge| {
1549            self.marking.done.contains(&e.step)
1550                && e.when.as_ref().map(|g| g.eval(&ctx)).unwrap_or(true)
1551        };
1552        let deps_done = if step.after.is_empty() {
1553            true
1554        } else {
1555            match step.join {
1556                Join::All => step.after.iter().all(edge_ok),
1557                Join::Any => step.after.iter().any(edge_ok),
1558            }
1559        };
1560        // Enforce `Constraint::Before(a, step)`: `a` must be done before this
1561        // step may start (an ordering constraint declared outside `after`).
1562        let before_ok = self.flow.constraints.iter().all(|c| match c {
1563            Constraint::Before(a, b) if *b == step.id => self.marking.done.contains(a),
1564            _ => true,
1565        });
1566        let gate_ok = step
1567            .gate
1568            .as_ref()
1569            .map(|g| g.eval(&self.ctx(state)))
1570            .unwrap_or(true);
1571        deps_done && before_ok && gate_ok
1572    }
1573
1574    /// Re-evaluate completion latches to a fixpoint. Call after any event that
1575    /// can change state or the marking (turn boundary, tool completion).
1576    ///
1577    /// [`Constraint::Reset`] constraints are applied first, on their guard's
1578    /// rising edge: the named steps un-latch, their `on_enter` re-arms, and
1579    /// the `called_ok` evidence their completion guards reference is forgiven
1580    /// — the loop primitive over an otherwise monotonic marking.
1581    pub fn relatch(&mut self, state: &State) {
1582        self.apply_resets(state);
1583        loop {
1584            let mut newly_done: Vec<String> = Vec::new();
1585            for s in &self.flow.steps {
1586                if self.marking.done.contains(&s.id) {
1587                    continue;
1588                }
1589                if !self.eligible(s, state) {
1590                    continue;
1591                }
1592                let complete = if s.terminal {
1593                    true
1594                } else {
1595                    s.done
1596                        .as_ref()
1597                        .map(|g| g.eval(&self.ctx(state)))
1598                        .unwrap_or(false)
1599                };
1600                if complete {
1601                    newly_done.push(s.id.clone());
1602                }
1603            }
1604            if newly_done.is_empty() {
1605                break;
1606            }
1607            for id in newly_done {
1608                self.marking.done.insert(id);
1609            }
1610        }
1611    }
1612
1613    /// Apply [`Constraint::Reset`] constraints on their guards' rising edges.
1614    /// Returns the steps that were un-latched.
1615    fn apply_resets(&mut self, state: &State) -> Vec<String> {
1616        let mut reset: Vec<String> = Vec::new();
1617        // Evaluate all guards first (immutable borrow), then mutate.
1618        let mut edges: Vec<(usize, bool)> = Vec::new();
1619        {
1620            let ctx = self.ctx(state);
1621            for (i, c) in self.flow.constraints.iter().enumerate() {
1622                if let Constraint::Reset { when, .. } = c {
1623                    edges.push((i, when.eval(&ctx)));
1624                }
1625            }
1626        }
1627        for (slot, (index, now)) in edges.into_iter().enumerate() {
1628            let prev = self.reset_prev.get(slot).copied().unwrap_or(false);
1629            if self.reset_prev.len() <= slot {
1630                self.reset_prev.resize(slot + 1, false);
1631            }
1632            self.reset_prev[slot] = now;
1633            if !now || prev {
1634                continue;
1635            }
1636            let Constraint::Reset { steps, .. } = &self.flow.constraints[index] else {
1637                continue;
1638            };
1639            let steps = steps.clone();
1640            for step_id in &steps {
1641                if !self.marking.done.remove(step_id) {
1642                    continue;
1643                }
1644                reset.push(step_id.clone());
1645                self.announced.remove(step_id);
1646                // Forgive the completion evidence this step's done guard
1647                // references, so `called_ok` (and any `once` on those tools)
1648                // count per latch-cycle. State keys stay the app's to clear.
1649                if let Some(step) = self.flow.steps.iter().find(|s| &s.id == step_id) {
1650                    let mut tools = Vec::new();
1651                    if let Some(done) = &step.done {
1652                        done.referenced_tools(&mut tools);
1653                    }
1654                    for tool in tools {
1655                        self.marking.tool_ok.remove(&tool);
1656                    }
1657                }
1658            }
1659        }
1660        reset
1661    }
1662
1663    /// Record a turn boundary, then re-latch.
1664    pub fn on_turn(&mut self, state: &State) {
1665        self.begin_turn(state);
1666        self.relatch(state);
1667    }
1668
1669    /// The first half of [`on_turn`](Self::on_turn): count the turn and apply
1670    /// [`Constraint::Reset`] edges, returning the steps that were un-latched.
1671    ///
1672    /// A caller that keeps evidence *about* steps outside the marking — the
1673    /// [`FlowStack`] and its repair signals — needs to see a reset before the
1674    /// re-latch runs, or a completion guard that references that evidence
1675    /// re-completes the step on the spot. Follow with
1676    /// [`relatch`](Self::relatch); the reset edges are consumed, so the
1677    /// re-latch does not apply them twice.
1678    pub fn begin_turn(&mut self, state: &State) -> Vec<String> {
1679        self.marking.turns += 1;
1680        self.apply_resets(state)
1681    }
1682
1683    /// Record a successful tool call, then re-latch.
1684    pub fn on_tool_ok(&mut self, tool: &str, state: &State) {
1685        self.begin_tool_ok(tool, state);
1686        self.relatch(state);
1687    }
1688
1689    /// The first half of [`on_tool_ok`](Self::on_tool_ok): count the call and
1690    /// apply [`Constraint::Reset`] edges, returning the steps that were
1691    /// un-latched.
1692    ///
1693    /// A reset can be gated on a tool — `reset(..).when(called_ok("start_over"))`
1694    /// — in which case its edge fires here rather than at a turn boundary. A
1695    /// caller holding evidence outside the marking needs the same chance to shed
1696    /// it that [`begin_turn`](Self::begin_turn) gives; follow with
1697    /// [`relatch`](Self::relatch).
1698    pub fn begin_tool_ok(&mut self, tool: &str, state: &State) -> Vec<String> {
1699        *self.marking.tool_ok.entry(tool.to_string()).or_insert(0) += 1;
1700        self.apply_resets(state)
1701    }
1702
1703    /// The state keys the flow could act on now: those read by the active
1704    /// steps' gates and `done` guards, by the edges leaving them, and by the
1705    /// constraints. A decision that `writes` one of these is worth asking.
1706    pub fn reads_now(&self, state: &State) -> BTreeSet<String> {
1707        let active: BTreeSet<&str> = self
1708            .active_steps(state)
1709            .into_iter()
1710            .map(|s| s.id.as_str())
1711            .collect();
1712        let mut out = BTreeSet::new();
1713        for step in &self.flow.steps {
1714            if active.contains(step.id.as_str()) {
1715                for g in step.gate.iter().chain(step.done.iter()) {
1716                    out.extend(g.state_keys());
1717                }
1718            }
1719            for edge in &step.after {
1720                if active.contains(edge.step.as_str())
1721                    && let Some(when) = &edge.when
1722                {
1723                    out.extend(when.state_keys());
1724                }
1725            }
1726        }
1727        for c in &self.flow.constraints {
1728            if let Constraint::NeverUntil { until: g, .. } | Constraint::Reset { when: g, .. } = c {
1729                out.extend(g.state_keys());
1730            }
1731        }
1732        out
1733    }
1734
1735    /// Steps that are eligible but not yet done.
1736    pub fn active_steps(&self, state: &State) -> Vec<&Step> {
1737        self.flow
1738            .steps
1739            .iter()
1740            .filter(|s| !self.marking.done.contains(&s.id) && self.eligible(s, state))
1741            .collect()
1742    }
1743
1744    /// Postures of the active steps — to inject as turn-boundary steering.
1745    pub fn active_postures(&self, state: &State) -> Vec<String> {
1746        self.active_steps(state)
1747            .into_iter()
1748            .filter_map(|s| s.posture.clone())
1749            .collect()
1750    }
1751
1752    /// Rendered grounding lines of the active steps — curated, `State`-
1753    /// interpolated facts to inject as turn-boundary steering (anti-hallucination).
1754    pub fn active_grounds(&self, state: &State) -> Vec<String> {
1755        self.active_steps(state)
1756            .into_iter()
1757            .filter_map(|s| s.ground.as_ref().map(|t| render_ground(t, state)))
1758            .filter(|s| !s.trim().is_empty())
1759            .collect()
1760    }
1761
1762    /// Terminal steps that are done — the flow's closing.
1763    ///
1764    /// A terminal step completes on eligibility, so it is never *active* and
1765    /// its posture is never among [`active_postures`](Self::active_postures).
1766    /// Its instruction is the flow's last word ("hand off to a human now"),
1767    /// which the [`FlowStack`] projects on the turn a digression completes.
1768    pub fn closing_steps(&self) -> Vec<&Step> {
1769        self.flow
1770            .steps
1771            .iter()
1772            .filter(|s| s.terminal && self.marking.done.contains(&s.id))
1773            .collect()
1774    }
1775
1776    /// Postures of the [`closing_steps`](Self::closing_steps).
1777    pub fn closing_postures(&self) -> Vec<String> {
1778        self.closing_steps()
1779            .into_iter()
1780            .filter_map(|s| s.posture.clone())
1781            .collect()
1782    }
1783
1784    /// Rendered grounding lines of the [`closing_steps`](Self::closing_steps).
1785    pub fn closing_grounds(&self, state: &State) -> Vec<String> {
1786        self.closing_steps()
1787            .into_iter()
1788            .filter_map(|s| s.ground.as_ref().map(|t| render_ground(t, state)))
1789            .filter(|s| !s.trim().is_empty())
1790            .collect()
1791    }
1792
1793    /// Required steps not yet done (drives repair).
1794    pub fn unmet_requirements(&self) -> Vec<String> {
1795        self.flow
1796            .constraints
1797            .iter()
1798            .flat_map(|c| match c {
1799                Constraint::Require(rs) => rs.clone(),
1800                _ => Vec::new(),
1801            })
1802            .filter(|r| !self.marking.done.contains(r))
1803            .collect()
1804    }
1805
1806    /// Whether all required steps are done.
1807    pub fn is_complete(&self) -> bool {
1808        self.unmet_requirements().is_empty()
1809    }
1810
1811    /// The conformance verdict for a step.
1812    pub fn verdict(&self, step_id: &str, state: &State) -> Verdict {
1813        if self.marking.done.contains(step_id) {
1814            return Verdict::Done;
1815        }
1816        if let Some(step) = self.flow.step(step_id)
1817            && self.eligible(step, state)
1818        {
1819            return Verdict::Active;
1820        }
1821        // Skipped: a successor is done but this step never completed.
1822        let bypassed = self.flow.steps.iter().any(|s| {
1823            s.after.iter().any(|d| d.step == step_id) && self.marking.done.contains(&s.id)
1824        });
1825        if bypassed {
1826            Verdict::Skipped
1827        } else {
1828            Verdict::Pending
1829        }
1830    }
1831
1832    /// Decide whether a tool call may proceed. `Ok(())` admits it; `Err(reason)`
1833    /// denies it (the caller blocks in Enforce mode, or records in Observe).
1834    pub fn admits_tool(&self, tool: &str, state: &State) -> Result<(), String> {
1835        match self.admissibility(tool, state) {
1836            Ok(()) => Ok(()),
1837            Err(denial) => Err(self.render_denial(tool, &denial, state)),
1838        }
1839    }
1840
1841    /// Whether `tool` would be admitted once every `never(tool).until(..)`
1842    /// guard on it holds: the active steps allow it and it has not used up a
1843    /// `once`, or a [frontier](Self::frontier_steps) step allows it. Under
1844    /// `ContextUpdate` steering the model is offered these tools, so that it
1845    /// can call one in the turn its guard comes to hold or its step opens;
1846    /// the call itself is still decided by [`admits_tool`](Self::admits_tool).
1847    pub fn offers_tool(&self, tool: &str, state: &State) -> bool {
1848        match self.admissibility_with(tool, state, false) {
1849            Ok(()) => true,
1850            // An active step's `deny` and a spent `once` bind any step.
1851            Err(Denial::OnceExhausted | Denial::DeniedByStep(_)) => false,
1852            Err(_) => self
1853                .frontier_steps(state)
1854                .iter()
1855                .any(|s| s.allow.iter().any(|a| a == tool)),
1856        }
1857    }
1858
1859    /// Evaluate `guard` as the caller's next words could leave it, against
1860    /// this flow's marking. See [`Guard::possible`].
1861    pub fn possible(&self, guard: &Guard, state: &State) -> Option<bool> {
1862        guard.possible(&self.ctx(state))
1863    }
1864
1865    /// The steps one decision away: neither done nor active, but able to
1866    /// become active in the caller's next turn because what stands in their
1867    /// way is a `decided` atom, in their gate, an incoming edge, or the
1868    /// `done` guard of the active step they follow.
1869    ///
1870    /// A decision made after the caller's turn ends cannot change the tools
1871    /// the model has for that turn: measured on Gemini 3.8 Live, a tool
1872    /// declared even 0 ms after the turn ended was not used in that turn's
1873    /// reply (0 of 15), while one declared before it was (5 of 5). So under
1874    /// `ContextUpdate` steering these steps' tools are offered ahead, and a
1875    /// call to one is decided at the gate: the questions in its way
1876    /// ([`frontier_questions`](Self::frontier_questions)) are asked about the
1877    /// turn in progress, the flow relatches, and the call is admitted only if
1878    /// the step opened.
1879    pub fn frontier_steps(&self, state: &State) -> Vec<&Step> {
1880        let ctx = self.ctx(state);
1881        let active: BTreeSet<&str> = self
1882            .active_steps(state)
1883            .into_iter()
1884            .map(|s| s.id.as_str())
1885            .collect();
1886        let could = |g: Option<&Guard>| g.map_or(Some(true), |g| g.possible(&ctx));
1887        let source = |id: &str| -> Option<bool> {
1888            if self.marking.done.contains(id) {
1889                Some(true)
1890            } else if active.contains(id) {
1891                // An active step completes when its `done` guard holds.
1892                self.flow
1893                    .step(id)
1894                    .and_then(|s| s.done.as_ref())
1895                    .map_or(Some(false), |done| done.possible(&ctx))
1896            } else {
1897                Some(false)
1898            }
1899        };
1900        self.flow
1901            .steps
1902            .iter()
1903            .filter(|step| {
1904                if self.marking.done.contains(&step.id) || active.contains(step.id.as_str()) {
1905                    return false;
1906                }
1907                let before_ok = self.flow.constraints.iter().all(|c| match c {
1908                    Constraint::Before(a, b) if *b == step.id => self.marking.done.contains(a),
1909                    _ => true,
1910                });
1911                if !before_ok {
1912                    return false;
1913                }
1914                let edges = step
1915                    .after
1916                    .iter()
1917                    .map(|e| all_of([source(&e.step), could(e.when.as_ref())]));
1918                let deps = if step.after.is_empty() {
1919                    Some(true)
1920                } else {
1921                    match step.join {
1922                        Join::All => all_of(edges),
1923                        Join::Any => any_of(edges),
1924                    }
1925                };
1926                // Not eligible now, so only an unknown can open it.
1927                all_of([deps, could(step.gate.as_ref())]).is_none()
1928            })
1929            .collect()
1930    }
1931
1932    /// The questions that decide whether a [frontier](Self::frontier_steps)
1933    /// step allowing `tool` opens, with the state keys their guards read:
1934    /// the step's gate, its incoming edges, and the `done` guards of the
1935    /// active steps it follows. Empty when no frontier step allows `tool`.
1936    pub fn frontier_questions(&self, tool: &str, state: &State) -> DecisionScope {
1937        let active: BTreeSet<String> = self
1938            .active_steps(state)
1939            .into_iter()
1940            .map(|s| s.id.clone())
1941            .collect();
1942        let mut scope = DecisionScope::default();
1943        for step in self.frontier_steps(state) {
1944            if !step.allow.iter().any(|a| a == tool) {
1945                continue;
1946            }
1947            let mut add = |g: &Guard| {
1948                scope.questions.extend(g.decisions());
1949                scope.reads.extend(g.state_keys());
1950            };
1951            step.gate.iter().for_each(&mut add);
1952            for edge in &step.after {
1953                edge.when.iter().for_each(&mut add);
1954                if active.contains(&edge.step)
1955                    && let Some(done) = self.flow.step(&edge.step).and_then(|s| s.done.as_ref())
1956                {
1957                    add(done);
1958                }
1959            }
1960        }
1961        scope
1962    }
1963
1964    /// The state keys read by the `never(tool).until(..)` guards that refuse
1965    /// `tool` right now. Empty when no such guard is refusing it.
1966    pub fn blocking_keys(&self, tool: &str, state: &State) -> BTreeSet<String> {
1967        let ctx = self.ctx(state);
1968        self.flow
1969            .constraints
1970            .iter()
1971            .filter_map(|c| match c {
1972                Constraint::NeverUntil { tool: t, until } if t == tool && !until.eval(&ctx) => {
1973                    Some(until.state_keys())
1974                }
1975                _ => None,
1976            })
1977            .flatten()
1978            .collect()
1979    }
1980
1981    /// The admissibility decision, before it is put into words.
1982    ///
1983    /// Split from [`admits_tool`](Self::admits_tool) so that rendering a refusal
1984    /// can itself ask what *is* admissible without recursing: this function never
1985    /// renders, so `render_denial` may call it over the whole tool universe.
1986    fn admissibility(&self, tool: &str, state: &State) -> Result<(), Denial> {
1987        self.admissibility_with(tool, state, true)
1988    }
1989
1990    /// [`admissibility`](Self::admissibility), optionally ignoring
1991    /// `never(tool).until(..)` guards.
1992    fn admissibility_with(&self, tool: &str, state: &State, guards: bool) -> Result<(), Denial> {
1993        // 1. once(tool)
1994        for c in &self.flow.constraints {
1995            if let Constraint::Once(t) = c
1996                && t == tool
1997                && self.marking.tool_ok.contains_key(tool)
1998            {
1999                return Err(Denial::OnceExhausted);
2000            }
2001        }
2002        // 2. never(tool).until(guard)
2003        for c in &self.flow.constraints {
2004            if let Constraint::NeverUntil { tool: t, until } = c
2005                && guards
2006                && t == tool
2007                && !until.eval(&self.ctx(state))
2008            {
2009                return Err(Denial::NotYet(until.describe()));
2010            }
2011        }
2012        // 3. active allow/deny (whitelist while any active step restricts).
2013        let active = self.active_steps(state);
2014        if let Some(step) = active.iter().find(|s| s.deny.iter().any(|d| d == tool)) {
2015            return Err(Denial::DeniedByStep(step.id.clone()));
2016        }
2017        // An ambient tool is exempt from the whitelist's exclusion-by-omission,
2018        // having already cleared every constraint that names it explicitly.
2019        if self.flow.ambient.iter().any(|a| a == tool) {
2020            return Ok(());
2021        }
2022        let restricting: Vec<&&Step> = active.iter().filter(|s| !s.allow.is_empty()).collect();
2023        if !restricting.is_empty()
2024            && !restricting
2025                .iter()
2026                .any(|s| s.allow.iter().any(|a| a == tool))
2027        {
2028            return Err(Denial::NotInStep(
2029                restricting.iter().map(|s| s.id.clone()).collect(),
2030            ));
2031        }
2032        Ok(())
2033    }
2034
2035    /// Put a refusal into words the model can act on.
2036    ///
2037    /// A refusal reaches the model as a tool error, and it is the only thing the
2038    /// model learns about the gate. "'X' is not available in the current step"
2039    /// names what failed and nothing about what would succeed, so the model is
2040    /// left to infer the precondition — and in the governed collections
2041    /// evaluation it inferred wrongly, re-asking a verified caller for their card
2042    /// digits after `record_promise_to_pay` was refused. The monitor knows the
2043    /// active step, what that step is waiting for, and which tools *are*
2044    /// admitted; every refusal now carries it.
2045    fn render_denial(&self, tool: &str, denial: &Denial, state: &State) -> String {
2046        let head = match denial {
2047            Denial::OnceExhausted => {
2048                // Nothing to redirect to: the answer is "you already did this".
2049                return format!(
2050                    "'{tool}' has already run and may run only once in this \
2051                     conversation. Do not call it again."
2052                );
2053            }
2054            Denial::NotYet(condition) => {
2055                format!("'{tool}' is not permitted yet — first, {condition}.")
2056            }
2057            Denial::DeniedByStep(step) => {
2058                format!("'{tool}' is not allowed during the current step ('{step}').")
2059            }
2060            Denial::NotInStep(steps) => format!(
2061                "'{tool}' is not part of the current step ({}).",
2062                steps
2063                    .iter()
2064                    .map(|s| format!("'{s}'"))
2065                    .collect::<Vec<_>>()
2066                    .join(", ")
2067            ),
2068        };
2069
2070        // What the model may do instead. Drawn from the flow's own tool
2071        // universe, so it never invents a tool the session has not declared.
2072        let available: Vec<String> = self
2073            .flow
2074            .tool_universe()
2075            .into_iter()
2076            .filter(|t| self.admissibility(t, state).is_ok())
2077            .collect();
2078
2079        // In live runs the model told the caller "your table is booked" right
2080        // after its booking call was refused. Say plainly that nothing happened.
2081        let mut out = head;
2082        out.push_str(" It did not run, so do not tell the caller it is done.");
2083        if available.is_empty() {
2084            out.push_str(" No tool is available right now — continue the conversation instead.");
2085        } else {
2086            out.push_str(" Available now: ");
2087            out.push_str(&available.join(", "));
2088            out.push('.');
2089        }
2090        // The posture is the step's own words for what it wants; repeating it
2091        // here means the redirection and the reason arrive together, rather than
2092        // the model having to reconcile an error with steering sent earlier.
2093        let postures = self.active_postures(state);
2094        if let Some(first) = postures.first() {
2095            out.push(' ');
2096            out.push_str(first);
2097        }
2098        out
2099    }
2100
2101    /// Observe a tool call for conformance. In Enforce mode the caller has
2102    /// already gated via [`admits_tool`](Self::admits_tool); this records the
2103    /// call and, in Observe mode, logs a deviation if it was inadmissible.
2104    pub fn observe_tool(&mut self, tool: &str, ok: bool, state: &State) {
2105        if self.mode == Enforcement::Observe
2106            && let Err(reason) = self.admits_tool(tool, state)
2107        {
2108            self.violations.push(Violation {
2109                subject: tool.to_string(),
2110                reason,
2111            });
2112        }
2113        if ok {
2114            self.on_tool_ok(tool, state);
2115        }
2116    }
2117}
2118
2119/// Why a tool call was refused, before it is rendered into prose.
2120///
2121/// Structured rather than a string so the renderer can add the redirection —
2122/// what *is* available, and what the active step is waiting for — which is the
2123/// half a model needs and the old message never carried.
2124enum Denial {
2125    /// A `once(tool)` constraint, already spent.
2126    OnceExhausted,
2127    /// A `never(tool).until(guard)` whose guard has not latched; carries the
2128    /// rendered guard.
2129    NotYet(String),
2130    /// The named active step lists the tool in `deny`.
2131    DeniedByStep(String),
2132    /// Active steps restrict by `allow` and none of them names the tool;
2133    /// carries the restricting step ids.
2134    NotInStep(Vec<String>),
2135}
2136
2137/// A single problem found while compiling a [`Flow`].
2138#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2139#[serde(tag = "kind", content = "detail", rename_all = "snake_case")]
2140pub enum FlowError {
2141    /// A referential-integrity or acyclicity error from [`Flow::validate`].
2142    Invalid(String),
2143    /// A step that no path from a root can ever reach.
2144    UnreachableStep(String),
2145    /// A commit (confirm) tool whose gate is always true — effectively
2146    /// unguarded, defeating confirm-before-commit.
2147    UnguardedCommitTool(String),
2148    /// A tool referenced by the flow (step `allow`/`deny`, `once`,
2149    /// `never…until`, confirm) that is not in the registry given to
2150    /// [`Flow::compile_with_tools`].
2151    UnknownTool(String),
2152    /// A `never(tool).until(guard)` whose guard references a step id that
2153    /// doesn't exist — the guard can never latch, so the tool would be
2154    /// forbidden forever.
2155    UnsatisfiableGuard {
2156        /// The tool the constraint gates.
2157        tool: String,
2158        /// The unknown step id the guard's `done(..)` atom references.
2159        step: String,
2160    },
2161    /// A cycle over the combined `after` + `before(a, b)` ordering edges —
2162    /// every step on the cycle waits on another, so none can ever become
2163    /// eligible. Contains the step ids on the cycle.
2164    OrderingCycle(Vec<String>),
2165}
2166
2167impl std::fmt::Display for FlowError {
2168    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2169        match self {
2170            FlowError::Invalid(m) => write!(f, "{m}"),
2171            FlowError::UnreachableStep(id) => {
2172                write!(f, "step '{id}' is unreachable from any root")
2173            }
2174            FlowError::UnguardedCommitTool(t) => write!(
2175                f,
2176                "commit tool '{t}' is guarded by an always-true condition (effectively unguarded)"
2177            ),
2178            FlowError::UnknownTool(t) => write!(
2179                f,
2180                "flow references tool '{t}' which is not in the provided tool registry"
2181            ),
2182            FlowError::UnsatisfiableGuard { tool, step } => write!(
2183                f,
2184                "`never('{tool}').until(..)` references unknown step '{step}' — the guard can \
2185                 never hold, so '{tool}' would be forbidden forever"
2186            ),
2187            FlowError::OrderingCycle(steps) => write!(
2188                f,
2189                "ordering cycle across `after`/`before` edges: {} (no step on it can ever start)",
2190                steps.join(" -> ")
2191            ),
2192        }
2193    }
2194}
2195
2196/// All problems found while compiling a [`Flow`]; non-empty on failure.
2197#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2198pub struct FlowErrors(pub Vec<FlowError>);
2199
2200impl std::fmt::Display for FlowErrors {
2201    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2202        writeln!(f, "flow failed to compile ({} error(s)):", self.0.len())?;
2203        for e in &self.0 {
2204            writeln!(f, "  - {e}")?;
2205        }
2206        Ok(())
2207    }
2208}
2209
2210impl std::error::Error for FlowErrors {}
2211
2212/// The precomputed tool surface of a compiled flow: every tool name the flow
2213/// reasons about (step `allow`/`deny`, `once`, `never…until`, confirm), so
2214/// introspection can enumerate and explain gating decisions. Distinct from
2215/// [`tool::ToolPolicy`](crate::tool::ToolPolicy), which is a per-tool runtime
2216/// policy (timeout/cache/confirm).
2217#[derive(Debug, Clone, Default)]
2218pub struct ToolSurface {
2219    /// Every tool referenced anywhere in the flow.
2220    pub tools: BTreeSet<String>,
2221}
2222
2223/// A validated [`Flow`] plus its precomputed [`ToolSurface`].
2224///
2225/// Produced by [`Flow::compile`]. Holding one is proof the flow passed
2226/// compilation, so the runtime never re-discovers structural errors. This is the
2227/// IR the conversation compiler targets and the type richer surfaces build on.
2228#[derive(Debug, Clone)]
2229pub struct CompiledFlow {
2230    flow: Flow,
2231    surface: ToolSurface,
2232}
2233
2234impl CompiledFlow {
2235    /// The underlying validated flow.
2236    pub fn flow(&self) -> &Flow {
2237        &self.flow
2238    }
2239    /// The precomputed tool surface.
2240    pub fn tool_surface(&self) -> &ToolSurface {
2241        &self.surface
2242    }
2243    /// Render the flow as a Mermaid diagram.
2244    pub fn to_mermaid(&self) -> String {
2245        self.flow.to_mermaid()
2246    }
2247    /// Consume into the inner flow.
2248    pub fn into_flow(self) -> Flow {
2249        self.flow
2250    }
2251}
2252
2253/// A model-readable explanation of the current control-plane state — the
2254/// foundation of `why did the assistant ask that?`.
2255///
2256/// Produced by [`FlowMonitor::explain`]. `Serialize` so it can be surfaced to a
2257/// model, a devtool, or a log without the model driving control flow.
2258#[derive(Debug, Clone, Serialize)]
2259pub struct FlowExplanation {
2260    /// Steps eligible-but-not-done right now.
2261    pub active: Vec<String>,
2262    /// Tools currently admitted.
2263    pub allowed_tools: Vec<String>,
2264    /// Tools currently blocked, mapped to the reason.
2265    pub blocked_tools: BTreeMap<String, String>,
2266    /// Required steps not yet done (drives repair).
2267    pub missing_requirements: Vec<String>,
2268    /// Per-active-step completion-guard truth trees: exactly which atom each
2269    /// stuck step is waiting on. Terminal steps (no `done` guard) are absent.
2270    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2271    pub active_progress: BTreeMap<String, GuardTrace>,
2272}
2273
2274/// Observed governance state for a simulator, UI, or handoff.
2275///
2276/// Step lists describe the currently driving layer. `complete` describes the
2277/// entire stack, so a digression's closing turn does not finish the main task.
2278/// This is an observation, not a checkpoint for restoring a conversation.
2279#[derive(Debug, Clone, Serialize)]
2280pub struct FlowSnapshot {
2281    /// Active-layer admission and completion guards.
2282    #[serde(flatten)]
2283    pub explanation: FlowExplanation,
2284    /// Completed steps in the same layer as `explanation`.
2285    pub done: Vec<String>,
2286    /// Whether the whole stack is complete, including explicit termination.
2287    pub complete: bool,
2288    /// Active digressions, outermost first. Empty when the main flow drives.
2289    pub overlay_path: Vec<String>,
2290    /// Whether a terminating digression ended the conversation.
2291    pub terminated: bool,
2292}
2293
2294/// Builder for a [`Flow`] using the cemented verbs.
2295#[derive(Default)]
2296pub struct FlowBuilder {
2297    steps: Vec<Step>,
2298    constraints: Vec<Constraint>,
2299    confirm_tools: Vec<String>,
2300    ambient: Vec<String>,
2301    /// Builder misuse found while chaining, reported by [`build`](Self::build).
2302    issues: Vec<String>,
2303}
2304
2305impl FlowBuilder {
2306    /// Apply `configure` to the step most recently declared with
2307    /// [`step`](Self::step). With no step declared there is nothing to
2308    /// configure: the misuse is recorded and [`build`](Self::build) reports it.
2309    fn configure_step(&mut self, method: &str, configure: impl FnOnce(&mut Step)) {
2310        match self.steps.last_mut() {
2311            Some(step) => configure(step),
2312            None => self.issues.push(format!(
2313                "`.{method}(..)` was called before `.step(id)`: there is no step to configure"
2314            )),
2315        }
2316    }
2317
2318    /// Declare a new step.
2319    pub fn step(mut self, id: impl Into<String>) -> Self {
2320        self.steps.push(Step {
2321            id: id.into(),
2322            after: Vec::new(),
2323            join: Join::default(),
2324            gate: None,
2325            done: None,
2326            posture: None,
2327            ground: None,
2328            allow: Vec::new(),
2329            deny: Vec::new(),
2330            terminal: false,
2331        });
2332        self
2333    }
2334    /// Add a dependency (call multiple times for multiple deps).
2335    pub fn after(mut self, dep: impl Into<String>) -> Self {
2336        self.configure_step("after", |step| step.after.push(Edge::to(dep)));
2337        self
2338    }
2339    /// Add a **conditional** dependency: satisfied only while `when` holds.
2340    /// Conditional edges out of one source are how a flow branches; pair with
2341    /// [`join_any`](Self::join_any) on the merge step.
2342    pub fn after_when(mut self, dep: impl Into<String>, when: Guard) -> Self {
2343        self.configure_step("after_when", |step| step.after.push(Edge::when(dep, when)));
2344        self
2345    }
2346    /// Any one satisfied edge makes this step eligible (the merge node after
2347    /// a branch). Default is `all` — a synchronizing join.
2348    pub fn join_any(mut self) -> Self {
2349        self.configure_step("join_any", |step| step.join = Join::Any);
2350        self
2351    }
2352    /// Extra eligibility guard beyond dependencies.
2353    pub fn gate(mut self, g: Guard) -> Self {
2354        self.configure_step("gate", |step| step.gate = Some(g));
2355        self
2356    }
2357    /// Completion condition.
2358    pub fn done(mut self, g: Guard) -> Self {
2359        self.configure_step("done", |step| step.done = Some(g));
2360        self
2361    }
2362    /// Instruction imposed while active.
2363    pub fn posture(mut self, text: impl Into<String>) -> Self {
2364        self.configure_step("posture", |step| step.posture = Some(text.into()));
2365        self
2366    }
2367    /// A grounding template projected while active — a curated, `State`-
2368    /// interpolated fact line that pins the model to known values. `{key}`
2369    /// interpolates a value; `{key?yes:no}` picks by truthiness. See
2370    /// [`render_ground`].
2371    pub fn ground(mut self, template: impl Into<String>) -> Self {
2372        self.configure_step("ground", |step| step.ground = Some(template.into()));
2373        self
2374    }
2375    /// Tools available while active (whitelist).
2376    pub fn allow<I, S>(mut self, tools: I) -> Self
2377    where
2378        I: IntoIterator<Item = S>,
2379        S: Into<String>,
2380    {
2381        self.configure_step("allow", |step| {
2382            step.allow.extend(tools.into_iter().map(Into::into));
2383        });
2384        self
2385    }
2386    /// Tools forbidden while active.
2387    pub fn deny<I, S>(mut self, tools: I) -> Self
2388    where
2389        I: IntoIterator<Item = S>,
2390        S: Into<String>,
2391    {
2392        self.configure_step("deny", |step| {
2393            step.deny.extend(tools.into_iter().map(Into::into));
2394        });
2395        self
2396    }
2397    /// Mark the current step terminal.
2398    pub fn terminal(mut self) -> Self {
2399        self.configure_step("terminal", |step| step.terminal = true);
2400        self
2401    }
2402
2403    /// A tool may run at most once.
2404    pub fn once(mut self, tool: impl Into<String>) -> Self {
2405        self.constraints.push(Constraint::Once(tool.into()));
2406        self
2407    }
2408    /// Ordering invariant: `a` before `b`.
2409    pub fn before(mut self, a: impl Into<String>, b: impl Into<String>) -> Self {
2410        self.constraints
2411            .push(Constraint::Before(a.into(), b.into()));
2412        self
2413    }
2414    /// Required terminal steps for completion.
2415    pub fn require<I, S>(mut self, steps: I) -> Self
2416    where
2417        I: IntoIterator<Item = S>,
2418        S: Into<String>,
2419    {
2420        self.constraints.push(Constraint::Require(
2421            steps.into_iter().map(Into::into).collect(),
2422        ));
2423        self
2424    }
2425    /// Exempt cross-cutting tools from every step's `allow` whitelist.
2426    ///
2427    /// Flow-level, and order-independent with respect to `.step(..)`. Use it for
2428    /// tools that serve the conversation rather than any one step of it —
2429    /// memory recall, escalation, logging. A tool named here still obeys
2430    /// `deny`, `once` and `never(..).until(..)`; see [`Flow::ambient`].
2431    ///
2432    /// ```
2433    /// # use gemini_adk_rs::flow::{Flow, Guard};
2434    /// let flow = Flow::new()
2435    ///     .ambient(["recall_context"])
2436    ///     .step("book")
2437    ///     .allow(["book_table"])
2438    ///     .done(Guard::called_ok("book_table"))
2439    ///     .build()
2440    ///     .unwrap();
2441    /// assert_eq!(flow.ambient, ["recall_context"]);
2442    /// ```
2443    pub fn ambient<I, S>(mut self, tools: I) -> Self
2444    where
2445        I: IntoIterator<Item = S>,
2446        S: Into<String>,
2447    {
2448        self.ambient.extend(tools.into_iter().map(Into::into));
2449        self
2450    }
2451
2452    /// Un-latch `steps` whenever the guard given to
2453    /// [`when`](ResetBuilder::when) *becomes* true — the loop primitive.
2454    /// See [`Constraint::Reset`] for the exact forgiveness semantics.
2455    pub fn reset<I, S>(self, steps: I) -> ResetBuilder
2456    where
2457        I: IntoIterator<Item = S>,
2458        S: Into<String>,
2459    {
2460        ResetBuilder {
2461            builder: self,
2462            steps: steps.into_iter().map(Into::into).collect(),
2463        }
2464    }
2465
2466    /// Forbid a tool until a guard holds (`never(tool).until(guard)`).
2467    pub fn never(self, tool: impl Into<String>) -> NeverBuilder {
2468        NeverBuilder {
2469            fb: self,
2470            tool: tool.into(),
2471        }
2472    }
2473    /// Commit-tool sugar: at most once, gated until `until`, and flagged for
2474    /// confirmation. Composes `once` + `never…until` + the confirmation seam.
2475    pub fn commit(mut self, tool: impl Into<String>, until: Guard) -> Self {
2476        let tool = tool.into();
2477        self.constraints.push(Constraint::Once(tool.clone()));
2478        self.constraints.push(Constraint::NeverUntil {
2479            tool: tool.clone(),
2480            until,
2481        });
2482        self.confirm_tools.push(tool);
2483        self
2484    }
2485
2486    /// Finalize and validate the flow.
2487    ///
2488    /// Fails if a step-level verb (`after`, `gate`, `allow`, ...) was chained
2489    /// before the first [`step`](Self::step), as well as on any validation
2490    /// issue; every problem found is reported.
2491    pub fn build(self) -> Result<Flow, ConfigError> {
2492        let mut issues = self.issues;
2493        let flow = Flow {
2494            steps: self.steps,
2495            constraints: self.constraints,
2496            confirm_tools: self.confirm_tools,
2497            ambient: self.ambient,
2498        };
2499        if let Err(err) = flow.validate() {
2500            issues.extend(err.issues);
2501        }
2502        ConfigError::from_issues(issues)?;
2503        Ok(flow)
2504    }
2505}
2506
2507/// Sub-builder for `never(tool).until(guard)`.
2508pub struct NeverBuilder {
2509    fb: FlowBuilder,
2510    tool: String,
2511}
2512
2513impl NeverBuilder {
2514    /// Permit the tool once the guard holds.
2515    pub fn until(mut self, guard: Guard) -> FlowBuilder {
2516        self.fb.constraints.push(Constraint::NeverUntil {
2517            tool: self.tool,
2518            until: guard,
2519        });
2520        self.fb
2521    }
2522}
2523
2524/// Intermediate for `reset(steps).when(guard)`.
2525pub struct ResetBuilder {
2526    builder: FlowBuilder,
2527    steps: Vec<String>,
2528}
2529
2530impl ResetBuilder {
2531    /// Fire the reset on this guard's rising edge.
2532    pub fn when(mut self, guard: Guard) -> FlowBuilder {
2533        self.builder.constraints.push(Constraint::Reset {
2534            steps: self.steps,
2535            when: guard,
2536        });
2537        self.builder
2538    }
2539}
2540
2541#[cfg(test)]
2542mod tests {
2543    use super::*;
2544    use serde_json::json;
2545
2546    #[test]
2547    fn step_verbs_before_the_first_step_fail_at_build() {
2548        let err = Flow::new()
2549            .after("greet")
2550            .terminal()
2551            .step("greet")
2552            .build()
2553            .expect_err("verbs chained before `.step(id)` have no step to configure");
2554        assert!(
2555            err.issues.iter().any(|i| i.contains("`.after(..)`")),
2556            "{err:?}"
2557        );
2558        assert!(
2559            err.issues.iter().any(|i| i.contains("`.terminal(..)`")),
2560            "{err:?}"
2561        );
2562    }
2563
2564    /// A refusal must say what would succeed, not only what failed.
2565    ///
2566    /// The old message was "'X' is not available in the current step" — the
2567    /// tool's own name and nothing else. The model cannot act on that: it knows
2568    /// the call was rejected but not what the gate is holding out for, so it
2569    /// guesses. In the governed collections evaluation it guessed identity
2570    /// verification and re-asked a caller it had already verified for their card
2571    /// digits, which read as the model losing the tool result when in fact the
2572    /// gate had told it nothing.
2573    #[test]
2574    fn a_refusal_names_what_is_available_instead() {
2575        let state = State::new();
2576        let mon = FlowMonitor::new(debt_flow(), Enforcement::Enforce);
2577
2578        let reason = mon
2579            .admits_tool("charge_card", &state)
2580            .expect_err("charge_card is gated behind verification");
2581
2582        assert!(
2583            reason.contains("lookup_account"),
2584            "a refusal must point at the tool that would make progress: {reason}"
2585        );
2586        assert!(
2587            reason.contains("ptp_confirmed"),
2588            "a refusal must name the condition it is waiting on: {reason}"
2589        );
2590    }
2591
2592    /// The step's own posture rides along, so the reason and the redirection
2593    /// arrive in one payload rather than the model having to reconcile an error
2594    /// with steering sent on an earlier turn.
2595    #[test]
2596    fn a_refusal_carries_the_active_steps_posture() {
2597        let state = State::new();
2598        let mon = FlowMonitor::new(debt_flow(), Enforcement::Enforce);
2599
2600        let reason = mon
2601            .admits_tool("charge_card", &state)
2602            .expect_err("charge_card is gated behind verification");
2603
2604        assert!(
2605            reason.contains("Verify the caller's identity."),
2606            "the active step's posture belongs in the refusal: {reason}"
2607        );
2608    }
2609
2610    /// In live runs the model announced a booking right after its booking call
2611    /// was refused; the refusal says the tool did not run.
2612    #[test]
2613    fn a_refusal_says_nothing_was_done() {
2614        let state = State::new();
2615        let mon = FlowMonitor::new(debt_flow(), Enforcement::Enforce);
2616        let reason = mon
2617            .admits_tool("charge_card", &state)
2618            .expect_err("charge_card is gated behind verification");
2619        assert!(
2620            reason.contains("It did not run, so do not tell the caller it is done."),
2621            "{reason}"
2622        );
2623    }
2624
2625    /// A spent `once` is the one refusal with nothing to redirect to: the answer
2626    /// is "you already did this", and offering alternatives would invite a
2627    /// retry under another name.
2628    #[test]
2629    fn a_spent_once_constraint_does_not_offer_alternatives() {
2630        let state = State::new();
2631        let flow = Flow::new()
2632            .step("pay")
2633            .allow(["charge_card"])
2634            .done(Guard::called_ok("charge_card"))
2635            .once("charge_card")
2636            .build()
2637            .expect("valid flow");
2638        let mut mon = FlowMonitor::new(flow, Enforcement::Enforce);
2639        mon.on_tool_ok("charge_card", &state);
2640
2641        let reason = mon
2642            .admits_tool("charge_card", &state)
2643            .expect_err("once is spent");
2644
2645        assert!(
2646            reason.contains("already run"),
2647            "a spent `once` must say so plainly: {reason}"
2648        );
2649        assert!(
2650            !reason.contains("Available now"),
2651            "nothing to redirect to — offering a menu invites a retry: {reason}"
2652        );
2653    }
2654
2655    /// The redirection is computed against live state, so it changes as the
2656    /// conversation progresses rather than describing the flow's opening move
2657    /// forever.
2658    #[test]
2659    fn the_redirection_tracks_the_conversation() {
2660        let state = State::new();
2661        let mon = FlowMonitor::new(debt_flow(), Enforcement::Enforce);
2662
2663        let before = mon
2664            .admits_tool("charge_card", &state)
2665            .expect_err("gated before the promise is confirmed");
2666        assert!(
2667            before.contains("ptp_confirmed") && before.contains("lookup_account"),
2668            "{before}"
2669        );
2670
2671        // Verification lands and the call moves on to the disclosure step. The
2672        // same constraint still blocks `charge_card`, but where the caller *is*
2673        // has changed, and the refusal has to change with it.
2674        let _ = state.set("identity_verified", true);
2675        let mut mon = mon;
2676        mon.on_turn(&state);
2677        let after = mon
2678            .admits_tool("charge_card", &state)
2679            .expect_err("the promise is still unconfirmed");
2680
2681        assert!(
2682            after.contains("Give the disclosure."),
2683            "the refusal must carry the posture of the step that is now active, \
2684             not the one that was active when the session opened: {after}"
2685        );
2686        assert!(
2687            !after.contains("Verify the caller's identity."),
2688            "a completed step's posture must not keep riding along on refusals — \
2689             that is how a verified caller gets asked to verify again: {after}"
2690        );
2691        assert_ne!(
2692            before, after,
2693            "the refusal did not change when the flow advanced"
2694        );
2695    }
2696
2697    /// Guard prose is what makes a refusal legible; pinned so the atoms do not
2698    /// silently start rendering as debug output.
2699    #[test]
2700    fn guards_describe_themselves_in_prose() {
2701        assert_eq!(
2702            Guard::is_true("verified").describe(),
2703            "'verified' must be true"
2704        );
2705        assert_eq!(
2706            Guard::captured(["amount", "date"]).describe(),
2707            "these must be known: amount, date"
2708        );
2709        assert_eq!(
2710            Guard::called_ok("disclose").describe(),
2711            "'disclose' must have run successfully"
2712        );
2713        assert_eq!(
2714            Guard::all([Guard::is_true("a"), Guard::done("b")]).describe(),
2715            "'a' must be true and step 'b' must be complete"
2716        );
2717        assert_eq!(
2718            Guard::custom(|_| true).describe(),
2719            "a condition set by the application",
2720            "a custom guard has no readable spec, and must not pretend otherwise"
2721        );
2722    }
2723
2724    fn debt_flow() -> Flow {
2725        Flow::new()
2726            .step("verify")
2727            .posture("Verify the caller's identity.")
2728            .allow(["lookup_account"])
2729            .done(Guard::is_true("identity_verified"))
2730            .step("disclose")
2731            .after("verify")
2732            .posture("Give the disclosure.")
2733            .done(Guard::is_true("disclosure_given"))
2734            .step("capture_ptp")
2735            .after("disclose")
2736            .done(Guard::captured(["ptp_amount", "ptp_date"]))
2737            .step("take_payment")
2738            .after("capture_ptp")
2739            .allow(["charge_card"])
2740            .done(Guard::called_ok("charge_card"))
2741            .step("close")
2742            .after("capture_ptp")
2743            .terminal()
2744            .never("charge_card")
2745            .until(Guard::is_true("ptp_confirmed"))
2746            .once("charge_card")
2747            .require(["close"])
2748            .build()
2749            .expect("valid flow")
2750    }
2751
2752    #[test]
2753    fn validates_and_detects_unknown_dep() {
2754        let bad = Flow::new()
2755            .step("a")
2756            .done(Guard::is_true("x"))
2757            .step("b")
2758            .after("missing")
2759            .terminal()
2760            .build();
2761        assert!(bad.is_err());
2762    }
2763
2764    #[test]
2765    fn detects_cycle() {
2766        // a after b, b after a — build() should reject.
2767        let steps = vec![
2768            Step {
2769                id: "a".into(),
2770                after: vec!["b".into()],
2771                join: Join::default(),
2772                gate: None,
2773                done: Some(Guard::always()),
2774                posture: None,
2775                ground: None,
2776                allow: vec![],
2777                deny: vec![],
2778                terminal: false,
2779            },
2780            Step {
2781                id: "b".into(),
2782                after: vec!["a".into()],
2783                join: Join::default(),
2784                gate: None,
2785                done: Some(Guard::always()),
2786                posture: None,
2787                ground: None,
2788                allow: vec![],
2789                deny: vec![],
2790                terminal: false,
2791            },
2792        ];
2793        let flow = Flow {
2794            steps,
2795            ..Flow::default()
2796        };
2797        assert!(flow.validate().is_err());
2798    }
2799
2800    #[test]
2801    fn marking_latches_in_order() {
2802        let flow = debt_flow();
2803        let mut mon = FlowMonitor::new(flow, Enforcement::Enforce);
2804        let state = State::new();
2805
2806        // Nothing done; only `verify` is active.
2807        assert_eq!(
2808            mon.active_steps(&state)
2809                .iter()
2810                .map(|s| s.id.as_str())
2811                .collect::<Vec<_>>(),
2812            vec!["verify"]
2813        );
2814
2815        let _ = state.set("identity_verified", true);
2816        mon.on_turn(&state);
2817        assert!(mon.marking().done.contains("verify"));
2818        assert_eq!(mon.verdict("verify", &state), Verdict::Done);
2819        assert_eq!(mon.verdict("disclose", &state), Verdict::Active);
2820
2821        let _ = state.set("disclosure_given", true);
2822        let _ = state.set("ptp_amount", 200);
2823        let _ = state.set("ptp_date", "2026-06-05");
2824        mon.on_turn(&state);
2825        // disclose + capture_ptp latch; close is terminal+eligible -> done.
2826        assert!(mon.marking().done.contains("capture_ptp"));
2827        assert!(mon.marking().done.contains("close"));
2828        assert!(mon.is_complete());
2829    }
2830
2831    #[test]
2832    fn enforces_never_until_and_once() {
2833        let flow = debt_flow();
2834        let mut mon = FlowMonitor::new(flow, Enforcement::Enforce);
2835        let state = State::new();
2836        // get to take_payment being active
2837        let _ = state.set("identity_verified", true);
2838        let _ = state.set("disclosure_given", true);
2839        let _ = state.set("ptp_amount", 200);
2840        let _ = state.set("ptp_date", "x");
2841        mon.on_turn(&state);
2842
2843        // charge_card blocked until ptp_confirmed.
2844        assert!(mon.admits_tool("charge_card", &state).is_err());
2845        let _ = state.set("ptp_confirmed", true);
2846        assert!(mon.admits_tool("charge_card", &state).is_ok());
2847
2848        // after it succeeds once, `once` blocks a second call.
2849        mon.on_tool_ok("charge_card", &state);
2850        assert!(mon.admits_tool("charge_card", &state).is_err());
2851    }
2852
2853    #[test]
2854    fn whitelist_scopes_tools_to_active_step() {
2855        let flow = debt_flow();
2856        let mon = FlowMonitor::new(flow, Enforcement::Enforce);
2857        let state = State::new();
2858        // In `verify`, only lookup_account is allowed.
2859        assert!(mon.admits_tool("lookup_account", &state).is_ok());
2860        assert!(mon.admits_tool("charge_card", &state).is_err());
2861    }
2862
2863    #[test]
2864    fn observe_mode_records_violations_not_blocks() {
2865        let flow = debt_flow();
2866        let mut mon = FlowMonitor::new(flow, Enforcement::Observe);
2867        let state = State::new();
2868        // charge_card out of order in observe mode -> recorded, still "runs".
2869        mon.observe_tool("charge_card", true, &state);
2870        assert_eq!(mon.violations().len(), 1);
2871        assert_eq!(mon.violations()[0].subject, "charge_card");
2872    }
2873
2874    #[test]
2875    fn compile_accepts_valid_flow_and_collects_tool_universe() {
2876        let compiled = debt_flow().compile().expect("valid flow compiles");
2877        // Tool universe spans allow/deny/once/never_until/confirm.
2878        assert!(compiled.tool_surface().tools.contains("charge_card"));
2879        assert!(compiled.tool_surface().tools.contains("lookup_account"));
2880        let _ = FlowMonitor::compiled(compiled, Enforcement::Enforce);
2881    }
2882
2883    #[test]
2884    fn compile_rejects_unreachable_step() {
2885        // `orphan` has no `after` and nothing leads to it — but it IS a root, so
2886        // to make it unreachable we give it an `after` on a step, then never make
2887        // that path lead anywhere. Simplest: a step depending on a missing root is
2888        // caught by validate; here we test a step unreachable via a broken chain.
2889        let flow = Flow::new()
2890            .step("a")
2891            .done(Guard::is_true("a_done"))
2892            .step("b")
2893            .after("a")
2894            .done(Guard::is_true("b_done"))
2895            .step("island")
2896            .after("b")
2897            .gate(Guard::is_true("never"))
2898            .terminal()
2899            .build()
2900            .expect("structurally valid");
2901        // island is reachable via a->b->island, so this compiles; assert it does.
2902        assert!(flow.compile().is_ok());
2903    }
2904
2905    #[test]
2906    fn compile_rejects_unguarded_commit_tool() {
2907        // commit tool gated by an always-true guard is effectively unguarded.
2908        let flow = Flow::new()
2909            .step("s")
2910            .allow(["pay"])
2911            .done(Guard::called_ok("pay"))
2912            .terminal()
2913            .commit("pay", Guard::always())
2914            .build()
2915            .expect("structurally valid");
2916        let err = flow
2917            .compile()
2918            .expect_err("unguarded commit must fail to compile");
2919        assert!(
2920            err.0
2921                .iter()
2922                .any(|e| matches!(e, FlowError::UnguardedCommitTool(t) if t == "pay"))
2923        );
2924    }
2925
2926    #[test]
2927    fn compile_with_tools_accepts_a_covering_registry() {
2928        let compiled = debt_flow()
2929            .compile_with_tools(&["lookup_account", "charge_card", "unrelated_extra"])
2930            .expect("registry covers the flow's tool universe");
2931        assert!(compiled.tool_surface().tools.contains("charge_card"));
2932    }
2933
2934    #[test]
2935    fn compile_with_tools_reports_dangling_tool_names() {
2936        // `charge_card` is referenced (allow/once/never_until) but missing from
2937        // the registry — a typo/drift the compiler must catch.
2938        let err = debt_flow()
2939            .compile_with_tools(&["lookup_account"])
2940            .expect_err("dangling tool must fail to compile");
2941        assert!(
2942            err.0
2943                .iter()
2944                .any(|e| matches!(e, FlowError::UnknownTool(t) if t == "charge_card"))
2945        );
2946        // Plain compile() stays registry-agnostic.
2947        assert!(debt_flow().compile().is_ok());
2948    }
2949
2950    #[test]
2951    fn compile_rejects_never_until_guard_on_unknown_step() {
2952        // `never(pay).until(done("missing"))` can never latch — `pay` would be
2953        // forbidden forever. validate() doesn't check constraint guards; compile must.
2954        let flow = Flow::new()
2955            .step("s")
2956            .allow(["pay"])
2957            .done(Guard::called_ok("pay"))
2958            .never("pay")
2959            .until(Guard::done("missing"))
2960            .build()
2961            .expect("structurally valid for build()");
2962        let err = flow.compile().expect_err("unsatisfiable guard must fail");
2963        assert!(err.0.iter().any(|e| matches!(
2964            e,
2965            FlowError::UnsatisfiableGuard { tool, step } if tool == "pay" && step == "missing"
2966        )));
2967    }
2968
2969    #[test]
2970    fn compile_rejects_before_cycle() {
2971        // `after` edges are acyclic, but before(a, b) + before(b, a) closes an
2972        // ordering cycle: neither step can ever become eligible. validate()'s
2973        // cycle check only walks `after`, so compile must catch this.
2974        let flow = Flow::new()
2975            .step("a")
2976            .done(Guard::is_true("a_done"))
2977            .step("b")
2978            .done(Guard::is_true("b_done"))
2979            .before("a", "b")
2980            .before("b", "a")
2981            .build()
2982            .expect("build() only checks `after` cycles");
2983        let err = flow
2984            .compile()
2985            .expect_err("before-cycle must fail to compile");
2986        assert!(err.0.iter().any(|e| matches!(
2987            e,
2988            FlowError::OrderingCycle(steps)
2989                if steps.contains(&"a".to_string()) && steps.contains(&"b".to_string())
2990        )));
2991    }
2992
2993    #[test]
2994    fn explain_reports_blocked_tools_and_reasons() {
2995        let flow = debt_flow();
2996        let mon = FlowMonitor::new(flow, Enforcement::Enforce);
2997        let state = State::new();
2998        let ex = mon.explain(&state);
2999        // In the initial `verify` step, charge_card is blocked; explain says so.
3000        assert!(ex.blocked_tools.contains_key("charge_card"));
3001        assert!(ex.active.contains(&"verify".to_string()));
3002    }
3003
3004    #[test]
3005    fn before_constraint_gates_step_eligibility() {
3006        // Regression: `before(a, b)` was validated but never enforced — `b` could
3007        // start before `a` was done. `a` and `b` have no `after` edge, so only the
3008        // Before constraint orders them.
3009        let flow = Flow::new()
3010            .step("a")
3011            .done(Guard::is_true("a_done"))
3012            .step("b")
3013            .done(Guard::is_true("b_done"))
3014            .before("a", "b")
3015            .build()
3016            .expect("valid flow");
3017        let mut mon = FlowMonitor::new(flow, Enforcement::Enforce);
3018        let state = State::new();
3019
3020        // `b` is NOT active until `a` is done, even though its own gate is open.
3021        let active: Vec<String> = mon
3022            .active_steps(&state)
3023            .iter()
3024            .map(|s| s.id.clone())
3025            .collect();
3026        assert!(active.contains(&"a".to_string()));
3027        assert!(
3028            !active.contains(&"b".to_string()),
3029            "b must wait for a (Before)"
3030        );
3031
3032        let _ = state.set("a_done", true);
3033        mon.on_turn(&state);
3034        let active: Vec<String> = mon
3035            .active_steps(&state)
3036            .iter()
3037            .map(|s| s.id.clone())
3038            .collect();
3039        assert!(active.contains(&"b".to_string()), "b active once a is done");
3040    }
3041
3042    #[test]
3043    fn custom_guard_in_combinator_is_not_erased() {
3044        // Regression: a custom guard nested in all()/any() was lowered to
3045        // Pred::Always, silently deleting it. It must still evaluate.
3046        let always_false = Guard::all([Guard::is_true("present"), Guard::custom(|_| false)]);
3047        // Mixed combinator is a Custom guard (non-serializable), not a Spec.
3048        assert!(matches!(always_false, Guard::Custom(_)));
3049
3050        let state = State::new();
3051        let _ = state.set("present", true);
3052        let marking = Marking::default();
3053        let ctx = FlowCtx {
3054            state: &state,
3055            marking: &marking,
3056        };
3057        // Would be `true` if the custom guard had been erased to Always.
3058        assert!(!always_false.eval(&ctx), "custom guard must still veto");
3059
3060        // all-spec combinator stays serializable.
3061        let serializable = Guard::all([Guard::is_true("a"), Guard::is_set("b")]);
3062        assert!(matches!(serializable, Guard::Spec(_)));
3063    }
3064
3065    #[test]
3066    fn serde_round_trips_data_driven_flow() {
3067        let flow = debt_flow();
3068        let jsonv = serde_json::to_value(&flow).expect("serialize");
3069        let back: Flow = serde_json::from_value(jsonv).expect("deserialize");
3070        back.validate().expect("round-tripped flow is valid");
3071        assert_eq!(back.steps.len(), flow.steps.len());
3072    }
3073
3074    #[test]
3075    fn custom_guard_is_not_serializable() {
3076        let flow = Flow::new()
3077            .step("a")
3078            .done(Guard::custom(|ctx| ctx.state.contains("ready")))
3079            .terminal()
3080            .build()
3081            .unwrap();
3082        assert!(serde_json::to_value(&flow).is_err());
3083    }
3084
3085    #[test]
3086    fn mermaid_export_has_nodes_and_edges() {
3087        let m = debt_flow().to_mermaid();
3088        assert!(m.contains("flowchart TD"));
3089        assert!(m.contains("verify --> disclose"));
3090        assert!(m.contains("close([close])")); // terminal shape
3091    }
3092
3093    struct WriteAgent;
3094    #[async_trait::async_trait]
3095    impl TextAgent for WriteAgent {
3096        fn name(&self) -> &str {
3097            "writer"
3098        }
3099        async fn run(&self, _state: &State) -> Result<String, crate::error::AgentError> {
3100            Ok("available".to_string())
3101        }
3102    }
3103
3104    #[tokio::test]
3105    async fn on_enter_fires_once_when_step_activates() {
3106        // collect -> check ; `check` runs an agent on enter whose result
3107        // (`check:result`) then completes a downstream `book` step.
3108        let flow = Flow::new()
3109            .step("collect")
3110            .done(Guard::is_true("collected"))
3111            .step("check")
3112            .after("collect")
3113            .done(Guard::resolved("check"))
3114            .step("book")
3115            .after("check")
3116            .terminal()
3117            .require(["book"])
3118            .build()
3119            .expect("valid flow");
3120
3121        let mut mon = FlowMonitor::new(flow, Enforcement::Enforce)
3122            .on_enter("check", on_enter(Arc::new(WriteAgent), AgentMode::Call));
3123        let state = State::new();
3124
3125        // Only `collect` is active at the start.
3126        assert_eq!(mon.take_newly_active(&state), vec!["collect".to_string()]);
3127        // Re-asking yields nothing — fire-once.
3128        assert!(mon.take_newly_active(&state).is_empty());
3129
3130        // Complete `collect`; `check` becomes active and its on_enter fires.
3131        let _ = state.set("collected", true);
3132        mon.on_turn(&state);
3133        mon.fire_enter_actions(&state).await;
3134        assert_eq!(
3135            state.get::<String>("check:result").as_deref(),
3136            Some("available")
3137        );
3138
3139        // The resolved result completes `check`, then terminal `book`.
3140        mon.on_turn(&state);
3141        assert!(mon.marking().done.contains("check"));
3142        assert!(mon.is_complete());
3143        // No further newly-active steps to announce.
3144        assert!(mon.take_newly_active(&state).is_empty());
3145    }
3146
3147    #[test]
3148    fn ground_template_interpolates_and_branches() {
3149        let state = State::new();
3150        let _ = state.set("when", "3pm");
3151        let _ = state.set("available", true);
3152        let _ = state.set("prior_visits", 2);
3153        assert_eq!(
3154            render_ground(
3155                "{when} is {available?open:taken}; {prior_visits} prior visits.",
3156                &state
3157            ),
3158            "3pm is open; 2 prior visits."
3159        );
3160        // Falsy branch + absent key renders empty.
3161        let _ = state.set("available", false);
3162        assert_eq!(
3163            render_ground("slot {missing}is {available?free:full}", &state),
3164            "slot is full"
3165        );
3166    }
3167
3168    #[test]
3169    fn active_grounds_projects_only_active_steps() {
3170        let flow = Flow::new()
3171            .step("collect")
3172            .ground("Known time: {when}.")
3173            .done(Guard::is_set("when"))
3174            .step("done")
3175            .after("collect")
3176            .terminal()
3177            .build()
3178            .expect("valid flow");
3179        let mut mon = FlowMonitor::new(flow, Enforcement::Enforce);
3180        let state = State::new();
3181        let _ = state.set("when", "3pm");
3182        assert_eq!(
3183            mon.active_grounds(&state),
3184            vec!["Known time: 3pm.".to_string()]
3185        );
3186        // Once collect completes, its ground no longer projects.
3187        mon.on_turn(&state);
3188        assert!(mon.active_grounds(&state).is_empty());
3189    }
3190
3191    #[test]
3192    fn eq_guard_matches_state_value() {
3193        let g = Guard::eq("status", json!("active"));
3194        let state = State::new();
3195        let marking = Marking::default();
3196        assert!(!g.eval(&FlowCtx {
3197            state: &state,
3198            marking: &marking
3199        }));
3200        let _ = state.set("status", "active");
3201        assert!(g.eval(&FlowCtx {
3202            state: &state,
3203            marking: &marking
3204        }));
3205    }
3206
3207    // ─── ambient tools ──────────────────────────────────────────────────────
3208    //
3209    // A step's `allow` list is a whitelist, so it excludes by omission: every
3210    // tool the author did not think to name is denied for the duration. That is
3211    // right for domain tools — naming `charge_card` is a statement that this is
3212    // the step where money moves — and wrong for cross-cutting infrastructure
3213    // that no step is *about*. Memory recall is the motivating case: a flow
3214    // author writing `.allow(["book_table"])` is saying "book here, don't search
3215    // the catalogue", not "stop remembering who the caller is".
3216    //
3217    // `ambient` names those tools once, at flow level. They are exempt from the
3218    // whitelist's implicit exclusion and from nothing else: a constraint that
3219    // *names* the tool still binds, because naming it is a deliberate act.
3220
3221    fn ambient_flow() -> Flow {
3222        Flow::new()
3223            .ambient(["recall_context"])
3224            .step("gather")
3225            .allow(["ask_diet"])
3226            .done(Guard::is_set("user:diet"))
3227            .step("book")
3228            .after("gather")
3229            .allow(["book_table"])
3230            .done(Guard::called_ok("book_table"))
3231            .build()
3232            .expect("flow is structurally valid")
3233    }
3234
3235    #[test]
3236    fn an_ambient_tool_survives_a_step_whitelist() {
3237        let mon = FlowMonitor::new(ambient_flow(), Enforcement::Enforce);
3238        let state = State::new();
3239        assert_eq!(
3240            mon.admits_tool("ask_diet", &state),
3241            Ok(()),
3242            "the step's own tool is admitted"
3243        );
3244        assert!(
3245            mon.admits_tool("book_table", &state).is_err(),
3246            "a later step's tool is still excluded by `gather`'s whitelist"
3247        );
3248        assert_eq!(
3249            mon.admits_tool("recall_context", &state),
3250            Ok(()),
3251            "an ambient tool must not be caught by a whitelist that never meant to exclude it"
3252        );
3253    }
3254
3255    #[test]
3256    fn an_ambient_tool_is_still_denied_when_a_step_names_it() {
3257        // `deny` names the tool, so it is a decision about that tool rather than
3258        // a side effect of listing others. Ambient must not override it.
3259        let flow = Flow::new()
3260            .ambient(["recall_context"])
3261            .step("sensitive")
3262            .deny(["recall_context"])
3263            .done(Guard::is_true("done"))
3264            .build()
3265            .expect("flow is structurally valid");
3266        let mon = FlowMonitor::new(flow, Enforcement::Enforce);
3267        assert!(
3268            mon.admits_tool("recall_context", &State::new()).is_err(),
3269            "an explicit `deny` outranks ambient"
3270        );
3271    }
3272
3273    #[test]
3274    fn an_ambient_tool_still_obeys_never_until() {
3275        let flow = Flow::new()
3276            .ambient(["manage_memory"])
3277            .step("verify")
3278            .done(Guard::is_true("verified"))
3279            .never("manage_memory")
3280            .until(Guard::is_true("verified"))
3281            .build()
3282            .expect("flow is structurally valid");
3283        let mon = FlowMonitor::new(flow, Enforcement::Enforce);
3284        let state = State::new();
3285        assert!(
3286            mon.admits_tool("manage_memory", &state).is_err(),
3287            "`never(..).until(..)` names the tool; ambient must not unlock it"
3288        );
3289        let _ = state.set("verified", true);
3290        assert_eq!(
3291            mon.admits_tool("manage_memory", &state),
3292            Ok(()),
3293            "once the guard holds the constraint stops binding"
3294        );
3295    }
3296
3297    #[test]
3298    fn an_ambient_tool_still_obeys_once() {
3299        let flow = Flow::new()
3300            .ambient(["summarize"])
3301            .step("work")
3302            .done(Guard::called_ok("summarize"))
3303            .once("summarize")
3304            .build()
3305            .expect("flow is structurally valid");
3306        let mut mon = FlowMonitor::new(flow, Enforcement::Enforce);
3307        let state = State::new();
3308        assert_eq!(mon.admits_tool("summarize", &state), Ok(()));
3309        mon.observe_tool("summarize", true, &state);
3310        assert!(
3311            mon.admits_tool("summarize", &state).is_err(),
3312            "`once` names the tool; ambient must not exempt it"
3313        );
3314    }
3315
3316    #[test]
3317    fn ambient_tools_join_the_tool_universe() {
3318        // Otherwise `compile_with_tools` would report a registry that covers the
3319        // flow as complete while an ambient tool it never heard of gets called.
3320        let flow = ambient_flow();
3321        assert!(
3322            flow.tool_universe().contains("recall_context"),
3323            "an ambient tool is part of the flow's tool universe"
3324        );
3325        assert!(
3326            ambient_flow()
3327                .compile_with_tools(&["ask_diet", "book_table"])
3328                .is_err(),
3329            "a registry missing the ambient tool must not compile clean"
3330        );
3331        assert!(
3332            ambient_flow()
3333                .compile_with_tools(&["ask_diet", "book_table", "recall_context"])
3334                .is_ok(),
3335            "a covering registry compiles"
3336        );
3337    }
3338
3339    #[test]
3340    fn a_flow_with_no_ambient_tools_is_unchanged() {
3341        // The whole point is that this is additive: a flow that never mentions
3342        // `ambient` must gate exactly as it did before the field existed.
3343        let mon = FlowMonitor::new(debt_flow(), Enforcement::Enforce);
3344        let state = State::new();
3345        assert_eq!(mon.admits_tool("lookup_account", &state), Ok(()));
3346        assert!(mon.admits_tool("charge_card", &state).is_err());
3347        assert!(mon.admits_tool("anything_else", &state).is_err());
3348    }
3349
3350    #[test]
3351    fn explain_trace_reports_per_atom_truth() {
3352        let state = State::new();
3353        let _ = state.set("ptp_amount", 200);
3354        let marking = Marking::default();
3355        let ctx = FlowCtx {
3356            state: &state,
3357            marking: &marking,
3358        };
3359        let guard = Guard::all([
3360            Guard::captured(["ptp_amount", "ptp_date"]),
3361            Guard::is_true("confirmed"),
3362        ]);
3363        let trace = guard.explain_trace(&ctx);
3364        assert!(!trace.holds);
3365        assert_eq!(trace.desc, "all of");
3366        assert_eq!(trace.children.len(), 2);
3367        // `captured` is a single atom (one node); `is_true` is false.
3368        assert!(!trace.children[0].holds, "ptp_date missing");
3369        assert!(!trace.children[1].holds);
3370        // JSON-serializable for devtools.
3371        assert!(serde_json::to_value(&trace).is_ok());
3372    }
3373
3374    #[test]
3375    fn explanation_carries_active_step_progress() {
3376        let mon = FlowMonitor::new(debt_flow(), Enforcement::Enforce);
3377        let state = State::new();
3378        let ex = mon.explain(&state);
3379        let verify = ex.active_progress.get("verify").expect("verify is active");
3380        assert!(!verify.holds);
3381        assert!(verify.desc.contains("identity_verified"));
3382    }
3383
3384    #[test]
3385    fn state_keys_read_covers_guards_and_constraints() {
3386        let keys = debt_flow().state_keys_read();
3387        for k in [
3388            "identity_verified",
3389            "disclosure_given",
3390            "ptp_amount",
3391            "ptp_date",
3392        ] {
3393            assert!(keys.contains(k), "missing read key {k}");
3394        }
3395        // Tool/step references are not state keys.
3396        assert!(!keys.contains("charge_card"));
3397    }
3398
3399    #[test]
3400    fn posture_updates_take_effect_in_place() {
3401        let mut mon = FlowMonitor::new(debt_flow(), Enforcement::Enforce);
3402        let state = State::new();
3403        assert!(mon.set_posture("verify", Some("New posture.".into())));
3404        assert!(!mon.set_posture("no_such_step", None));
3405        assert_eq!(
3406            mon.active_postures(&state),
3407            vec!["New posture.".to_string()]
3408        );
3409    }
3410
3411    #[test]
3412    fn eval_state_treats_marking_atoms_as_false() {
3413        let state = State::new();
3414        let _ = state.set("ready", true);
3415        assert!(Guard::is_true("ready").eval_state(&state));
3416        assert!(!Guard::called_ok("any_tool").eval_state(&state));
3417    }
3418
3419    #[test]
3420    fn conditional_edges_branch_and_any_join_merges() {
3421        // decide ─(routine)→ schedule ─┐
3422        //        ─(emergency)→ escalate ─┴→ close (join: any)
3423        let flow = Flow::new()
3424            .step("decide")
3425            .done(Guard::is_set("severity"))
3426            .step("schedule")
3427            .after_when("decide", Guard::eq("severity", "routine"))
3428            .done(Guard::called_ok("book"))
3429            .allow(["book"])
3430            .step("escalate")
3431            .after_when("decide", Guard::eq("severity", "emergency"))
3432            .done(Guard::called_ok("transfer"))
3433            .allow(["transfer"])
3434            .step("close")
3435            .after("schedule")
3436            .after("escalate")
3437            .join_any()
3438            .terminal()
3439            .build()
3440            .expect("valid");
3441        let mut mon = FlowMonitor::new(flow, Enforcement::Enforce);
3442        let state = State::new();
3443        let _ = state.set("severity", "routine");
3444        mon.relatch(&state);
3445        let active: Vec<String> = mon.explain(&state).active;
3446        assert!(
3447            active.contains(&"schedule".to_string()),
3448            "routine branch opens"
3449        );
3450        assert!(
3451            !active.contains(&"escalate".to_string()),
3452            "emergency branch stays closed"
3453        );
3454        // Merge via any-join: schedule alone completing closes the flow.
3455        mon.on_tool_ok("book", &state);
3456        assert!(mon.marking().done.contains("close"), "any-join merged");
3457    }
3458
3459    #[test]
3460    fn reset_unlatches_on_rising_edge_and_forgives_called_ok() {
3461        let flow = Flow::new()
3462            .step("pay")
3463            .allow(["charge"])
3464            .done(Guard::called_ok("charge"))
3465            .once("charge")
3466            .reset(["pay"])
3467            .when(Guard::is_true("declined"))
3468            .build()
3469            .expect("valid");
3470        let mut mon = FlowMonitor::new(flow, Enforcement::Enforce);
3471        let state = State::new();
3472        mon.relatch(&state);
3473        mon.on_tool_ok("charge", &state);
3474        assert!(mon.marking().done.contains("pay"));
3475        assert!(mon.admits_tool("charge", &state).is_err(), "once spent");
3476
3477        // Decline: rising edge un-latches pay and forgives the charge.
3478        let _ = state.set("declined", true);
3479        mon.relatch(&state);
3480        assert!(!mon.marking().done.contains("pay"), "un-latched");
3481        assert!(
3482            mon.admits_tool("charge", &state).is_ok(),
3483            "once counts per latch-cycle"
3484        );
3485
3486        // Still-true guard does not re-fire (edge, not level).
3487        mon.on_tool_ok("charge", &state);
3488        mon.relatch(&state);
3489        assert!(
3490            mon.marking().done.contains("pay"),
3491            "second charge latches again"
3492        );
3493    }
3494
3495    #[test]
3496    fn edge_serde_keeps_plain_strings_and_round_trips_conditions() {
3497        let flow = Flow::new()
3498            .step("a")
3499            .terminal()
3500            .step("b")
3501            .after("a")
3502            .after_when("a", Guard::is_true("x"))
3503            .join_any()
3504            .terminal()
3505            .build()
3506            .expect("valid");
3507        let json = serde_json::to_value(&flow).expect("serialize");
3508        // Unconditional edge stays the original plain string.
3509        assert_eq!(json["steps"][1]["after"][0], serde_json::json!("a"));
3510        assert_eq!(
3511            json["steps"][1]["after"][1],
3512            serde_json::json!({"step": "a", "when": {"is_true": "x"}})
3513        );
3514        assert_eq!(json["steps"][1]["join"], serde_json::json!("any"));
3515        let back: Flow = serde_json::from_value(json).expect("deserialize");
3516        assert_eq!(back.steps[1].after.len(), 2);
3517        assert!(back.steps[1].after[1].when.is_some());
3518    }
3519
3520    #[test]
3521    fn flow_json_schema_generates() {
3522        let schema = serde_json::to_value(schemars::schema_for!(Flow)).expect("schema");
3523        let text = schema.to_string();
3524        // The Guard schema must surface the Pred atoms.
3525        assert!(text.contains("is_true"));
3526        assert!(text.contains("never_until"));
3527    }
3528
3529    #[test]
3530    fn possible_leaves_a_decision_unknown_and_settles_the_rest() {
3531        let state = State::new();
3532        let _ = state.set("yes", true);
3533        let marking = Marking::default();
3534        let ctx = FlowCtx {
3535            state: &state,
3536            marking: &marking,
3537        };
3538        let decided = Guard::decided("q");
3539        assert_eq!(decided.possible(&ctx), None);
3540        assert_eq!(Guard::not(decided.clone()).possible(&ctx), None);
3541        assert_eq!(Guard::is_true("yes").possible(&ctx), Some(true));
3542        // A false conjunct settles a conjunction; a true disjunct a disjunction.
3543        assert_eq!(
3544            Guard::all([decided.clone(), Guard::is_true("no")]).possible(&ctx),
3545            Some(false)
3546        );
3547        assert_eq!(
3548            Guard::any([decided.clone(), Guard::is_true("yes")]).possible(&ctx),
3549            Some(true)
3550        );
3551        assert_eq!(
3552            Guard::all([decided.clone(), Guard::is_true("yes")]).possible(&ctx),
3553            None
3554        );
3555        assert_eq!(
3556            Guard::any([decided, Guard::is_true("no")]).possible(&ctx),
3557            None
3558        );
3559    }
3560}