1use 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
47pub struct FlowCtx<'a> {
50 pub state: &'a State,
52 pub marking: &'a Marking,
54}
55
56#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
58#[serde(rename_all = "snake_case")]
59pub enum Pred {
60 Always,
62 IsTrue(String),
64 IsSet(String),
66 Eq(String, Value),
68 Captured(Vec<String>),
70 CalledOk(String),
72 Done(String),
74 Decided(Decided),
77 All(Vec<Pred>),
79 Any(Vec<Pred>),
81 Not(Box<Pred>),
83}
84
85fn 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
98fn 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 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 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 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 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 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 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 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 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#[derive(Clone, Debug, Serialize, schemars::JsonSchema)]
239pub struct GuardTrace {
240 pub desc: String,
242 pub holds: bool,
244 #[serde(default, skip_serializing_if = "Vec::is_empty")]
246 pub children: Vec<GuardTrace>,
247}
248
249pub 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 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#[derive(Clone)]
313pub enum Guard {
314 Spec(Pred),
316 Custom(CustomFn),
318}
319
320impl Guard {
321 pub fn always() -> Self {
323 Guard::Spec(Pred::Always)
324 }
325 pub fn is_true(key: impl Into<String>) -> Self {
327 Guard::Spec(Pred::IsTrue(key.into()))
328 }
329 pub fn is_set(key: impl Into<String>) -> Self {
331 Guard::Spec(Pred::IsSet(key.into()))
332 }
333 pub fn eq(key: impl Into<String>, value: impl Into<Value>) -> Self {
335 Guard::Spec(Pred::Eq(key.into(), value.into()))
336 }
337 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 pub fn called_ok(tool: impl Into<String>) -> Self {
347 Guard::Spec(Pred::CalledOk(tool.into()))
348 }
349 pub fn done(step: impl Into<String>) -> Self {
351 Guard::Spec(Pred::Done(step.into()))
352 }
353 pub fn decided(question: impl Into<String>) -> Self {
357 Self::decided_as(question, Expect::Yes)
358 }
359 pub fn decided_no(question: impl Into<String>) -> Self {
362 Self::decided_as(question, Expect::No)
363 }
364 pub fn decided_is(question: impl Into<String>, option: impl Into<String>) -> Self {
366 Self::decided_as(question, Expect::Is(option.into()))
367 }
368 pub fn decided_at_least(question: impl Into<String>, bound: f64) -> Self {
370 Self::decided_as(question, Expect::AtLeast(bound))
371 }
372 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 pub fn resolved(name: impl AsRef<str>) -> Self {
386 Guard::Spec(Pred::IsSet(format!("{}:result", name.as_ref())))
387 }
388 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 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 #[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 Guard::Custom(f) => Guard::Custom(Arc::new(move |ctx| !f(ctx))),
423 }
424 }
425 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 pub fn custom(f: impl Fn(&FlowCtx) -> bool + Send + Sync + 'static) -> Self {
443 Guard::Custom(Arc::new(f))
444 }
445
446 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 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 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 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 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 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
529fn 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
560impl 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#[derive(Clone, Debug)]
594pub struct Edge {
595 pub step: String,
597 pub when: Option<Guard>,
599}
600
601impl Edge {
602 pub fn to(step: impl Into<String>) -> Self {
604 Edge {
605 step: step.into(),
606 when: None,
607 }
608 }
609 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 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#[derive(
680 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
681)]
682#[serde(rename_all = "snake_case")]
683pub enum Join {
684 #[default]
686 All,
687 Any,
689}
690
691impl Join {
692 fn is_all(&self) -> bool {
693 *self == Join::All
694 }
695}
696
697#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema)]
699pub struct Step {
700 pub id: String,
702 #[serde(default, skip_serializing_if = "Vec::is_empty")]
704 pub after: Vec<Edge>,
705 #[serde(default, skip_serializing_if = "Join::is_all")]
707 pub join: Join,
708 #[serde(default, skip_serializing_if = "Option::is_none")]
710 pub gate: Option<Guard>,
711 #[serde(default, skip_serializing_if = "Option::is_none")]
713 pub done: Option<Guard>,
714 #[serde(default, skip_serializing_if = "Option::is_none")]
716 pub posture: Option<String>,
717 #[serde(default, skip_serializing_if = "Option::is_none")]
721 pub ground: Option<String>,
722 #[serde(default, skip_serializing_if = "Vec::is_empty")]
724 pub allow: Vec<String>,
725 #[serde(default, skip_serializing_if = "Vec::is_empty")]
727 pub deny: Vec<String>,
728 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
730 pub terminal: bool,
731}
732
733#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema)]
735#[serde(rename_all = "snake_case")]
736pub enum Constraint {
737 Once(String),
739 Before(String, String),
741 NeverUntil {
743 tool: String,
745 until: Guard,
747 },
748 Require(Vec<String>),
750 Reset {
759 steps: Vec<String>,
761 when: Guard,
763 },
764}
765
766#[derive(Clone, Debug, Default, Serialize, Deserialize, schemars::JsonSchema)]
768pub struct Flow {
769 pub steps: Vec<Step>,
771 #[serde(default, skip_serializing_if = "Vec::is_empty")]
773 pub constraints: Vec<Constraint>,
774 #[serde(default, skip_serializing_if = "Vec::is_empty")]
776 pub confirm_tools: Vec<String>,
777 #[serde(default, skip_serializing_if = "Vec::is_empty")]
786 pub ambient: Vec<String>,
787}
788
789impl Flow {
790 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 #[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 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 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 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 fn reachable_steps(&self) -> BTreeSet<String> {
965 let ids: BTreeSet<&str> = self.steps.iter().map(|s| s.id.as_str()).collect();
966 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 pub fn compile(self) -> Result<CompiledFlow, FlowErrors> {
1016 self.compile_internal(None)
1017 }
1018
1019 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 if errors.is_empty() {
1043 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 if let Some(cycle) = self.ordering_cycle() {
1054 errors.push(FlowError::OrderingCycle(cycle));
1055 }
1056 }
1057
1058 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 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 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 fn ordering_cycle(&self) -> Option<Vec<String>> {
1117 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 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 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 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#[derive(Clone, Debug, Default)]
1230pub struct Marking {
1231 pub done: BTreeSet<String>,
1233 pub tool_ok: BTreeMap<String, u32>,
1235 pub turns: u32,
1237}
1238
1239#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1241#[serde(rename_all = "snake_case")]
1242pub enum Verdict {
1243 Pending,
1245 Active,
1247 Done,
1249 Skipped,
1251}
1252
1253#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
1255pub struct Violation {
1256 pub subject: String,
1258 pub reason: String,
1260}
1261
1262#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
1267pub enum Enforcement {
1268 #[default]
1270 Enforce,
1271 Observe,
1273}
1274
1275#[derive(Clone)]
1280pub struct StepAction {
1281 name: Option<String>,
1282 agent: Arc<dyn TextAgent>,
1283 mode: AgentMode,
1284}
1285
1286pub 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 pub fn named(mut self, name: impl Into<String>) -> Self {
1304 self.name = Some(name.into());
1305 self
1306 }
1307
1308 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
1327pub type SharedFlowMonitor = Arc<parking_lot::Mutex<FlowMonitor>>;
1333
1334pub struct FlowMonitor {
1337 flow: Flow,
1338 mode: Enforcement,
1339 marking: Marking,
1340 violations: Vec<Violation>,
1341 enter_actions: HashMap<String, StepAction>,
1343 announced: BTreeSet<String>,
1345 reset_prev: Vec<bool>,
1348}
1349
1350impl FlowMonitor {
1351 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 pub fn compiled(flow: CompiledFlow, mode: Enforcement) -> Self {
1370 Self::new(flow.into_flow(), mode)
1371 }
1372
1373 pub fn try_new(flow: Flow, mode: Enforcement) -> Result<Self, FlowErrors> {
1376 Ok(Self::compiled(flow.compile()?, mode))
1377 }
1378
1379 pub fn into_shared(self) -> SharedFlowMonitor {
1384 Arc::new(parking_lot::Mutex::new(self))
1385 }
1386
1387 pub fn into_stack(self) -> FlowStack {
1390 FlowStack::from_monitor(self)
1391 }
1392
1393 pub fn restart(&mut self) {
1398 self.marking = Marking::default();
1399 self.announced.clear();
1400 self.reset_prev.clear();
1401 }
1402
1403 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 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 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 pub fn enter_action(&self, step: &str) -> Option<&StepAction> {
1463 self.enter_actions.get(step)
1464 }
1465
1466 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 pub fn mode(&self) -> Enforcement {
1479 self.mode
1480 }
1481
1482 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 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 pub fn eval(&self, guard: &Guard, state: &State) -> bool {
1513 guard.eval(&self.ctx(state))
1514 }
1515 pub fn marking(&self) -> &Marking {
1517 &self.marking
1518 }
1519 pub fn violations(&self) -> &[Violation] {
1521 &self.violations
1522 }
1523
1524 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 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 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 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 fn apply_resets(&mut self, state: &State) -> Vec<String> {
1616 let mut reset: Vec<String> = Vec::new();
1617 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 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 pub fn on_turn(&mut self, state: &State) {
1665 self.begin_turn(state);
1666 self.relatch(state);
1667 }
1668
1669 pub fn begin_turn(&mut self, state: &State) -> Vec<String> {
1679 self.marking.turns += 1;
1680 self.apply_resets(state)
1681 }
1682
1683 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 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 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 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 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 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 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 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 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 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 pub fn is_complete(&self) -> bool {
1808 self.unmet_requirements().is_empty()
1809 }
1810
1811 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 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 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 pub fn offers_tool(&self, tool: &str, state: &State) -> bool {
1848 match self.admissibility_with(tool, state, false) {
1849 Ok(()) => true,
1850 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 pub fn possible(&self, guard: &Guard, state: &State) -> Option<bool> {
1862 guard.possible(&self.ctx(state))
1863 }
1864
1865 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 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 all_of([deps, could(step.gate.as_ref())]).is_none()
1928 })
1929 .collect()
1930 }
1931
1932 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 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 fn admissibility(&self, tool: &str, state: &State) -> Result<(), Denial> {
1987 self.admissibility_with(tool, state, true)
1988 }
1989
1990 fn admissibility_with(&self, tool: &str, state: &State, guards: bool) -> Result<(), Denial> {
1993 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 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 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 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 fn render_denial(&self, tool: &str, denial: &Denial, state: &State) -> String {
2046 let head = match denial {
2047 Denial::OnceExhausted => {
2048 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 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 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 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 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
2119enum Denial {
2125 OnceExhausted,
2127 NotYet(String),
2130 DeniedByStep(String),
2132 NotInStep(Vec<String>),
2135}
2136
2137#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2139#[serde(tag = "kind", content = "detail", rename_all = "snake_case")]
2140pub enum FlowError {
2141 Invalid(String),
2143 UnreachableStep(String),
2145 UnguardedCommitTool(String),
2148 UnknownTool(String),
2152 UnsatisfiableGuard {
2156 tool: String,
2158 step: String,
2160 },
2161 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#[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#[derive(Debug, Clone, Default)]
2218pub struct ToolSurface {
2219 pub tools: BTreeSet<String>,
2221}
2222
2223#[derive(Debug, Clone)]
2229pub struct CompiledFlow {
2230 flow: Flow,
2231 surface: ToolSurface,
2232}
2233
2234impl CompiledFlow {
2235 pub fn flow(&self) -> &Flow {
2237 &self.flow
2238 }
2239 pub fn tool_surface(&self) -> &ToolSurface {
2241 &self.surface
2242 }
2243 pub fn to_mermaid(&self) -> String {
2245 self.flow.to_mermaid()
2246 }
2247 pub fn into_flow(self) -> Flow {
2249 self.flow
2250 }
2251}
2252
2253#[derive(Debug, Clone, Serialize)]
2259pub struct FlowExplanation {
2260 pub active: Vec<String>,
2262 pub allowed_tools: Vec<String>,
2264 pub blocked_tools: BTreeMap<String, String>,
2266 pub missing_requirements: Vec<String>,
2268 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2271 pub active_progress: BTreeMap<String, GuardTrace>,
2272}
2273
2274#[derive(Debug, Clone, Serialize)]
2280pub struct FlowSnapshot {
2281 #[serde(flatten)]
2283 pub explanation: FlowExplanation,
2284 pub done: Vec<String>,
2286 pub complete: bool,
2288 pub overlay_path: Vec<String>,
2290 pub terminated: bool,
2292}
2293
2294#[derive(Default)]
2296pub struct FlowBuilder {
2297 steps: Vec<Step>,
2298 constraints: Vec<Constraint>,
2299 confirm_tools: Vec<String>,
2300 ambient: Vec<String>,
2301 issues: Vec<String>,
2303}
2304
2305impl FlowBuilder {
2306 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 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 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 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 pub fn join_any(mut self) -> Self {
2349 self.configure_step("join_any", |step| step.join = Join::Any);
2350 self
2351 }
2352 pub fn gate(mut self, g: Guard) -> Self {
2354 self.configure_step("gate", |step| step.gate = Some(g));
2355 self
2356 }
2357 pub fn done(mut self, g: Guard) -> Self {
2359 self.configure_step("done", |step| step.done = Some(g));
2360 self
2361 }
2362 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 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 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 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 pub fn terminal(mut self) -> Self {
2399 self.configure_step("terminal", |step| step.terminal = true);
2400 self
2401 }
2402
2403 pub fn once(mut self, tool: impl Into<String>) -> Self {
2405 self.constraints.push(Constraint::Once(tool.into()));
2406 self
2407 }
2408 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 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 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 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 pub fn never(self, tool: impl Into<String>) -> NeverBuilder {
2468 NeverBuilder {
2469 fb: self,
2470 tool: tool.into(),
2471 }
2472 }
2473 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 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
2507pub struct NeverBuilder {
2509 fb: FlowBuilder,
2510 tool: String,
2511}
2512
2513impl NeverBuilder {
2514 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
2524pub struct ResetBuilder {
2526 builder: FlowBuilder,
2527 steps: Vec<String>,
2528}
2529
2530impl ResetBuilder {
2531 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 #[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 #[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 #[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 #[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 #[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 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 #[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 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 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 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 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 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 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 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 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 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 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 assert!(flow.compile().is_ok());
2903 }
2904
2905 #[test]
2906 fn compile_rejects_unguarded_commit_tool() {
2907 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 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 assert!(debt_flow().compile().is_ok());
2948 }
2949
2950 #[test]
2951 fn compile_rejects_never_until_guard_on_unknown_step() {
2952 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 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 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 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 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 let always_false = Guard::all([Guard::is_true("present"), Guard::custom(|_| false)]);
3047 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 assert!(!always_false.eval(&ctx), "custom guard must still veto");
3059
3060 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])")); }
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 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 assert_eq!(mon.take_newly_active(&state), vec!["collect".to_string()]);
3127 assert!(mon.take_newly_active(&state).is_empty());
3129
3130 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 mon.on_turn(&state);
3141 assert!(mon.marking().done.contains("check"));
3142 assert!(mon.is_complete());
3143 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 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 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 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 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 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 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 assert!(!trace.children[0].holds, "ptp_date missing");
3369 assert!(!trace.children[1].holds);
3370 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 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 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 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 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 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 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 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 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}