app-kit 0.0.1

Application and durable workflow composition for ai-kit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
use std::collections::{BTreeMap, BTreeSet};
use std::panic::{AssertUnwindSafe, catch_unwind};

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use crate::AppError;
use crate::workflow::definition::{
    ChildInitializer, CompiledDefinition, JsonBoundary, MapDeclaration, PromptPart, Reducer,
    RouteMode, Step, ValueExpr,
};
use crate::workflow::run::{
    ActionPosition, AttemptIdentity, CheckpointPhaseRecord, CheckpointRecord,
    ChildMembershipRecord, ChildTask, FailureCategory, FrontierRecord, MAX_CHILD_DEPTH, RunRecord,
};
use crate::workflow::{
    ActionOutcome, ConditionBackend, ExecutionEvent, StateTyping, WorkflowId, WorkflowState,
};

mod expression;
mod state;

pub(crate) const MAX_FRONTIER: usize = 4_096;
pub(crate) const MAX_RUNTIME_BYTES: usize = 1_048_576;
const MAX_SUPERSTEPS: u64 = 1_000_000;
const MAX_MAP_ITEMS: usize = 4_096;

pub(crate) struct ExecutionEngine<'a, T: StateTyping, C: ConditionBackend> {
    definition: &'a CompiledDefinition,
    typing: &'a T,
    conditions: &'a [C],
}

#[derive(Clone, Deserialize, PartialEq, Serialize)]
pub(crate) struct StagedActivationRecord {
    pub(crate) node: String,
    pub(crate) lineage: String,
    pub(crate) outcome: StagedOutcomeRecord,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) children: Option<(u64, Vec<ChildMembershipRecord>)>,
}

#[derive(Clone, Deserialize, PartialEq, Serialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub(crate) enum StagedOutcomeRecord {
    Complete {
        changes: Vec<StateChangeRecord>,
        result: Map<String, Value>,
    },
    Deferred,
    Failed {
        category: FailureCategory,
        message: String,
    },
}

#[derive(Clone, Deserialize, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub(crate) enum StateChangeRecord {
    Assign { target: String, value: Value },
    Reinsert { target: String, value: Value },
    Remove { target: String },
}

pub(crate) enum BspDecision {
    Activate(Vec<FrontierRecord>),
    AwaitControls,
    AdmitChildren {
        sequence: u64,
        children: Vec<RunRecord>,
    },
    ExecuteChildren {
        sequence: u64,
        children: Vec<RunRecord>,
    },
    Stage(Vec<StagedActivationRecord>),
    Barrier {
        state: Map<String, Value>,
        frontier: Vec<FrontierRecord>,
        settled_joins: BTreeMap<String, usize>,
        superstep: u64,
        outcomes: Vec<ActionOutcome>,
        sources: Vec<FrontierRecord>,
    },
    Routed {
        frontier: Vec<FrontierRecord>,
    },
    Inputs {
        node: String,
        lineage: String,
        required: Vec<String>,
    },
    Interaction {
        node: String,
        lineage: String,
        message: String,
    },
    Agent(AgentRequest),
    Descendants {
        node: String,
        lineage: String,
        inputs: Vec<ChildTask>,
        runtime_inputs: Vec<Map<String, Value>>,
    },
    Sleep {
        node: String,
        lineage: String,
        delay_millis: u64,
    },
    Succeeded,
    Failed {
        category: FailureCategory,
        message: String,
        observation: Option<ActionPosition>,
    },
}

impl BspDecision {
    pub(crate) fn pending_node(&self, halt_before: &[String]) -> Option<&str> {
        match self {
            Self::Activate(selected) => selected
                .iter()
                .find(|activation| halt_before.iter().any(|node| node == &activation.node))
                .map(|activation| activation.node.as_str()),
            Self::AwaitControls
            | Self::AdmitChildren { .. }
            | Self::ExecuteChildren { .. }
            | Self::Stage(_)
            | Self::Barrier { .. }
            | Self::Routed { .. }
            | Self::Inputs { .. }
            | Self::Interaction { .. }
            | Self::Agent(_)
            | Self::Descendants { .. }
            | Self::Sleep { .. }
            | Self::Succeeded
            | Self::Failed { .. } => None,
        }
    }

    fn failed(category: FailureCategory, message: String) -> Self {
        Self::Failed {
            category,
            message,
            observation: None,
        }
    }

    fn limit(message: &str) -> Self {
        Self::failed(FailureCategory::Limit, message.to_owned())
    }

    fn descendants(
        activation: &FrontierRecord,
        child_depth: u8,
        resolved: impl ExactSizeIterator<Item = Result<(ChildTask, Map<String, Value>), AppError>>,
    ) -> Result<Self, AppError> {
        if resolved.len() > 0 && child_depth >= MAX_CHILD_DEPTH {
            return Ok(Self::limit("child workflow depth bound exhausted"));
        }
        let mut inputs = Vec::with_capacity(resolved.len());
        let mut runtime_inputs = Vec::with_capacity(resolved.len());
        let mut input_bytes = 2_usize;
        let mut runtime_bytes = 2_usize;
        let mut task_bytes = 2_usize;
        for input in resolved {
            let (input, runtime) = input?;
            JsonBoundary::validate_inputs(&runtime)?;
            let encoded = serde_json::to_vec(&runtime).map_err(|_| {
                AppError::InvalidInput("child runtime input encoding failed".into())
            })?;
            let Some(next_bytes) = runtime_bytes
                .checked_add(usize::from(!runtime_inputs.is_empty()))
                .and_then(|bytes| bytes.checked_add(encoded.len()))
                .filter(|bytes| *bytes <= MAX_RUNTIME_BYTES)
            else {
                return Ok(Self::limit("child runtime input byte bound exhausted"));
            };
            runtime_bytes = next_bytes;
            runtime_inputs.push(runtime);
            let encoded = serde_json::to_vec(&input.input)
                .map_err(|_| AppError::InvalidInput("child input encoding failed".into()))?;
            let Some(next_bytes) = input_bytes
                .checked_add(usize::from(!inputs.is_empty()))
                .and_then(|bytes| bytes.checked_add(encoded.len()))
                .filter(|bytes| *bytes <= MAX_RUNTIME_BYTES)
            else {
                return Ok(Self::limit("child input byte bound exhausted"));
            };
            input_bytes = next_bytes;
            let encoded = serde_json::to_vec(&input)
                .map_err(|_| AppError::InvalidInput("child task encoding failed".into()))?;
            let Some(next_bytes) = task_bytes
                .checked_add(usize::from(!inputs.is_empty()))
                .and_then(|bytes| bytes.checked_add(encoded.len()))
                .filter(|bytes| *bytes <= crate::storage::MAX_RECORD_BYTES)
            else {
                return Ok(Self::limit(
                    "child task metadata exceeds the durable record bound",
                ));
            };
            task_bytes = next_bytes;
            inputs.push(input);
        }
        Ok(Self::Descendants {
            node: activation.node.clone(),
            lineage: activation.lineage.clone(),
            inputs,
            runtime_inputs,
        })
    }
}

pub(crate) struct AgentRequest {
    node: String,
    lineage: String,
    attempt_identity: Option<AttemptIdentity>,
    agent: String,
    prompt: String,
    stream: bool,
    partials: Option<tokio::sync::mpsc::Sender<ExecutionEvent>>,
    structured_schema: Option<Value>,
    text_target: Option<String>,
    structured_target: Option<String>,
}

#[derive(Eq, Ord, PartialEq, PartialOrd)]
enum RouteIdentity {
    Lineage(String),
    Join(usize),
}

struct RoutedFrontier<'definition, C: ConditionBackend> {
    definition: &'definition CompiledDefinition,
    conditions: &'definition [C],
    entries: BTreeMap<(String, RouteIdentity), FrontierRecord>,
}

impl<'a, T: StateTyping, C: ConditionBackend> ExecutionEngine<'a, T, C> {
    pub(crate) fn new(
        definition: &'a CompiledDefinition,
        typing: &'a T,
        conditions: &'a [C],
    ) -> Self {
        Self {
            definition,
            typing,
            conditions,
        }
    }

    pub(crate) fn advance(&self, checkpoint: &CheckpointRecord) -> Result<BspDecision, AppError> {
        if let CheckpointPhaseRecord::Routing { sources } = &checkpoint.phase {
            return self.route_committed(checkpoint, sources);
        }
        if checkpoint.superstep >= MAX_SUPERSTEPS {
            return Ok(BspDecision::limit("workflow superstep bound exhausted"));
        }
        if checkpoint.frontier.is_empty()
            && checkpoint.staged.is_empty()
            && checkpoint.controls.is_empty()
        {
            return Ok(BspDecision::Succeeded);
        }
        if checkpoint.frontier.len() > MAX_FRONTIER {
            return Ok(BspDecision::limit("workflow frontier bound exhausted"));
        }

        let staged_keys = checkpoint
            .staged
            .iter()
            .map(|staged| (staged.node.as_str(), staged.lineage.as_str()))
            .collect::<BTreeSet<_>>();
        let mut ready = checkpoint
            .frontier
            .iter()
            .filter(|activation| {
                !staged_keys.contains(&(activation.node.as_str(), activation.lineage.as_str()))
                    && checkpoint
                        .control_for(&activation.node, &activation.lineage)
                        .is_none()
            })
            .collect::<Vec<_>>();
        ready
            .sort_by(|left, right| (&left.node, &left.lineage).cmp(&(&right.node, &right.lineage)));
        let mut selected = Vec::new();
        for activation in ready {
            if checkpoint.loses_join_first(self.definition, &activation.node, &activation.lineage) {
                selected.push(activation.clone());
                continue;
            }
            let Some(node) = self.definition.node(&activation.node) else {
                return Ok(BspDecision::failed(
                    FailureCategory::Execution,
                    "workflow frontier references an unknown node".to_owned(),
                ));
            };
            match node.step() {
                Step::JoinAll {} | Step::JoinFirst {} => {
                    if checkpoint.activation_ready(self.definition, activation) {
                        selected.push(activation.clone());
                    }
                }
                Step::Action { .. }
                | Step::State { .. }
                | Step::Input { .. }
                | Step::Agent { .. }
                | Step::Child { .. }
                | Step::Map(_)
                | Step::Pipeline { .. }
                | Step::Sleep { .. } => selected.push(activation.clone()),
            }
        }
        if !selected.is_empty() {
            return Ok(BspDecision::Activate(selected));
        }
        if !checkpoint.controls.is_empty() {
            return Ok(BspDecision::AwaitControls);
        }
        if !checkpoint.staged.is_empty() {
            return self.publish_staged(checkpoint);
        }
        Ok(BspDecision::failed(
            FailureCategory::Execution,
            "workflow frontier cannot make progress".to_owned(),
        ))
    }

    pub(crate) fn activate(
        &self,
        checkpoint: &CheckpointRecord,
        activation: &FrontierRecord,
        child_depth: u8,
        resolve: impl FnMut(WorkflowId, Option<String>) -> Result<(WorkflowId, String), AppError>,
    ) -> Result<BspDecision, AppError> {
        if checkpoint.loses_join_first(self.definition, &activation.node, &activation.lineage) {
            return Ok(BspDecision::Stage(vec![StagedActivationRecord {
                node: activation.node.clone(),
                lineage: activation.lineage.clone(),
                outcome: StagedOutcomeRecord::Deferred,
                children: None,
            }]));
        }
        let node = self
            .definition
            .node(&activation.node)
            .ok_or_else(|| AppError::Integration("selected workflow node is unavailable".into()))?;
        match node.step() {
            Step::Action { .. } => Err(AppError::Integration(
                "caller activation requires its local source owner".into(),
            )),
            Step::JoinAll {} | Step::JoinFirst {} => {
                Ok(BspDecision::Stage(vec![StagedActivationRecord::complete(
                    activation.node.clone(),
                    activation.lineage.clone(),
                    Vec::new(),
                    Map::new(),
                )]))
            }
            Step::State { mutations } => {
                Ok(BspDecision::Stage(vec![StagedActivationRecord::mutate(
                    activation.node.clone(),
                    activation.lineage.clone(),
                    mutations,
                    &checkpoint.state,
                    self.typing,
                    self.conditions,
                )]))
            }
            Step::Input { .. }
            | Step::Agent { .. }
            | Step::Child { .. }
            | Step::Map(_)
            | Step::Pipeline { .. }
            | Step::Sleep { .. } => {
                let mut decision = match catch_unwind(AssertUnwindSafe(|| {
                    self.prepare_control(checkpoint, activation, child_depth, resolve)
                })) {
                    Ok(Ok(decision)) => decision,
                    Ok(Err(error)) => BspDecision::failed(
                        FailureCategory::Evaluation,
                        match error {
                            AppError::InvalidInput(message) => message,
                            _ => "workflow evaluation failed".into(),
                        },
                    ),
                    Err(_) => BspDecision::failed(
                        FailureCategory::Execution,
                        "workflow callback panicked".into(),
                    ),
                };
                if let BspDecision::Failed { observation, .. } = &mut decision {
                    *observation = Some(checkpoint.proposed_position(
                        self.definition,
                        &activation.node,
                        &activation.lineage,
                        &[],
                    )?);
                }
                Ok(decision)
            }
        }
    }

    fn prepare_control(
        &self,
        checkpoint: &CheckpointRecord,
        activation: &FrontierRecord,
        child_depth: u8,
        mut resolve: impl FnMut(WorkflowId, Option<String>) -> Result<(WorkflowId, String), AppError>,
    ) -> Result<BspDecision, AppError> {
        let node = self
            .definition
            .node(&activation.node)
            .ok_or_else(|| AppError::Integration("workflow node is unavailable".into()))?;
        match node.step() {
            Step::Input { message, .. } => Ok(BspDecision::Interaction {
                node: activation.node.clone(),
                lineage: activation.lineage.clone(),
                message: PromptPart::render_all(message, &checkpoint.state)?,
            }),
            Step::Agent { .. } => Ok(BspDecision::Agent(AgentRequest::recover(
                self.definition,
                &checkpoint.state,
                node.id(),
                &activation.lineage,
                None,
            )?)),
            Step::Child {
                input,
                inputs,
                task_key,
                initializer,
                ..
            } => {
                let state = WorkflowState::new(checkpoint.state.clone())?;
                let (selection, history) = node.step().child_selection(0)?;
                let (workflow, revision) = selection.resolve(&state, self.conditions)?;
                let (workflow, revision) = resolve(workflow, revision)?;
                BspDecision::descendants(
                    activation,
                    child_depth,
                    std::iter::once(Ok((
                        ChildTask {
                            workflow,
                            revision,
                            history,
                            task_key: ChildTask::resolve_key(
                                task_key.as_deref(),
                                "0-0".into(),
                                &state,
                                self.conditions,
                            )?,
                            initializer: initializer
                                .as_ref()
                                .map(|value| value.resolve(&state, self.conditions))
                                .transpose()?,
                            input: ValueExpr::evaluate_map(input, &state, self.conditions)?,
                        },
                        ValueExpr::evaluate_map(inputs, &state, self.conditions)?,
                    ))),
                )
            }
            Step::Map(MapDeclaration::Items {
                items,
                input_key,
                index_key,
                input,
                inputs,
                task_key,
                initializer,
                ..
            }) => {
                let state = WorkflowState::new(checkpoint.state.clone())?;
                let Value::Array(values) = items.evaluate(&state, self.conditions)? else {
                    return Ok(BspDecision::failed(
                        FailureCategory::Evaluation,
                        "map expression did not produce an array".into(),
                    ));
                };
                if values.len() > MAX_MAP_ITEMS {
                    return Ok(BspDecision::limit("map item bound exhausted"));
                }
                let (selection, history) = node.step().child_selection(0)?;
                let (workflow, revision) = selection.resolve(&state, self.conditions)?;
                let (workflow, revision) = resolve(workflow, revision)?;
                let base_input = ValueExpr::evaluate_map(input, &state, self.conditions)?;
                let runtime = ValueExpr::evaluate_map(inputs, &state, self.conditions)?;
                let task_key = task_key
                    .as_deref()
                    .map(|value| {
                        ChildTask::resolve_key(Some(value), String::new(), &state, self.conditions)
                    })
                    .transpose()?;
                let initializer = initializer
                    .as_ref()
                    .map(|value| value.resolve(&state, self.conditions))
                    .transpose()?;
                let inputs = values.into_iter().enumerate().map(|(index, value)| {
                    let mut mapped = base_input.clone();
                    mapped.insert(input_key.clone(), value);
                    if let Some(index_key) = index_key {
                        mapped.insert(index_key.clone(), Value::from(index as u64));
                    }
                    Ok((
                        ChildTask {
                            workflow: workflow.clone(),
                            revision: revision.clone(),
                            input: mapped,
                            history,
                            task_key: task_key.clone().unwrap_or_else(|| format!("0-{index}")),
                            initializer: initializer.clone(),
                        },
                        runtime.clone(),
                    ))
                });
                BspDecision::descendants(activation, child_depth, inputs)
            }
            Step::Map(MapDeclaration::Tasks { tasks, .. }) => {
                let state = WorkflowState::new(checkpoint.state.clone())?;
                let Value::Array(values) = tasks.evaluate(&state, self.conditions)? else {
                    return Ok(BspDecision::failed(
                        FailureCategory::Evaluation,
                        "map tasks expression did not produce an array".into(),
                    ));
                };
                if values.len() > MAX_MAP_ITEMS {
                    return Ok(BspDecision::limit("map task bound exhausted"));
                }
                BspDecision::descendants(
                    activation,
                    child_depth,
                    values
                        .into_iter()
                        .map(|value| ChildTask::resolved(value, &mut resolve)),
                )
            }
            Step::Pipeline { children, .. } => {
                let state = WorkflowState::new(checkpoint.state.clone())?;
                BspDecision::descendants(
                    activation,
                    child_depth,
                    children.iter().enumerate().map(|(index, child)| {
                        let (selection, history) = node.step().child_selection(index)?;
                        let (workflow, revision) = selection.resolve(&state, self.conditions)?;
                        let (workflow, revision) = resolve(workflow, revision)?;
                        Ok((
                            ChildTask {
                                workflow,
                                revision,
                                history,
                                task_key: ChildTask::resolve_key(
                                    child.task_key.as_deref(),
                                    format!("{index}-0"),
                                    &state,
                                    self.conditions,
                                )?,
                                initializer: child
                                    .initializer
                                    .as_ref()
                                    .map(|value| value.resolve(&state, self.conditions))
                                    .transpose()?,
                                input: ValueExpr::evaluate_map(
                                    &child.input,
                                    &state,
                                    self.conditions,
                                )?,
                            },
                            ValueExpr::evaluate_map(&child.inputs, &state, self.conditions)?,
                        ))
                    }),
                )
            }
            Step::Sleep { delay_ms, .. } => Ok(BspDecision::Sleep {
                node: activation.node.clone(),
                lineage: activation.lineage.clone(),
                delay_millis: *delay_ms,
            }),
            Step::Action { .. } | Step::State { .. } | Step::JoinAll {} | Step::JoinFirst {} => {
                Err(AppError::Integration(
                    "workflow node has no control preparation".into(),
                ))
            }
        }
    }

    pub(crate) fn stage_after_control(
        &self,
        node: &str,
        lineage: &str,
        contributions: Vec<(String, Value)>,
        result: Map<String, Value>,
    ) -> Result<StagedActivationRecord, AppError> {
        for (_, value) in &contributions {
            crate::workflow::definition::JsonBoundary::validate(value)?;
        }
        crate::workflow::definition::JsonBoundary::validate_size(&result)?;
        let staged = StagedActivationRecord::complete(
            node.to_owned(),
            lineage.to_owned(),
            contributions
                .into_iter()
                .map(|(target, value)| StateChangeRecord::Assign { target, value })
                .collect(),
            result,
        );
        if serde_json::to_vec(&staged).is_ok_and(|encoded| encoded.len() <= MAX_RUNTIME_BYTES) {
            Ok(staged)
        } else {
            Err(AppError::InvalidInput(
                "workflow stage exceeds its private bound".to_owned(),
            ))
        }
    }

    fn settle_staged(
        &self,
        checkpoint: &CheckpointRecord,
    ) -> Result<Map<String, Value>, (FailureCategory, String)> {
        if let Some(failure) = checkpoint
            .selected_staged(self.definition)
            .find_map(|activation| {
                let StagedOutcomeRecord::Failed { category, message } = &activation.outcome else {
                    return None;
                };
                Some((*category, message.clone()))
            })
        {
            return Err(failure);
        }
        let failure = |category| (category, "workflow state reduction failed".to_owned());
        let state = StateChangeRecord::apply_all(
            checkpoint.selected_staged(self.definition),
            &checkpoint.state,
            self.definition,
        )
        .map_err(|error| {
            failure(if matches!(error, AppError::Integration(_)) {
                FailureCategory::Execution
            } else {
                FailureCategory::State
            })
        })?;
        self.definition
            .validate_state(&state)
            .map_err(|_| failure(FailureCategory::State))?;
        let state = WorkflowState::new(state).map_err(|_| failure(FailureCategory::State))?;
        state
            .validate_typing(self.typing)
            .map_err(|_| failure(FailureCategory::State))?;
        Ok(state.values)
    }

    fn publish_staged(&self, checkpoint: &CheckpointRecord) -> Result<BspDecision, AppError> {
        let completed_keys = checkpoint
            .staged
            .iter()
            .map(|entry| (entry.node.as_str(), entry.lineage.as_str()))
            .collect::<BTreeSet<_>>();
        let frontier = checkpoint
            .frontier
            .iter()
            .filter(|existing| {
                !completed_keys.contains(&(existing.node.as_str(), existing.lineage.as_str()))
            })
            .cloned()
            .collect();
        let state = match catch_unwind(AssertUnwindSafe(|| self.settle_staged(checkpoint)))
            .unwrap_or_else(|_| {
                Err((
                    FailureCategory::Execution,
                    "workflow callback panicked".into(),
                ))
            }) {
            Ok(state) => state,
            Err((category, message)) => {
                let failed = checkpoint
                    .selected_staged(self.definition)
                    .find(|activation| {
                        matches!(&activation.outcome, StagedOutcomeRecord::Failed { .. })
                    })
                    .or_else(|| {
                        checkpoint
                            .selected_staged(self.definition)
                            .find(|activation| {
                                matches!(&activation.outcome, StagedOutcomeRecord::Complete { .. })
                            })
                    });
                let observation = failed
                    .map(|activation| {
                        checkpoint.proposed_position(
                            self.definition,
                            &activation.node,
                            &activation.lineage,
                            &[],
                        )
                    })
                    .transpose()?;
                return Ok(BspDecision::Failed {
                    category,
                    message,
                    observation,
                });
            }
        };
        let mut settled_joins = checkpoint.settled_joins.clone();
        let mut outcomes = Vec::new();
        let mut sources = Vec::new();
        let first_ordinal = checkpoint.next_action_ordinal()?;
        for activation in checkpoint.selected_staged(self.definition) {
            let StagedOutcomeRecord::Complete { result, .. } = &activation.outcome else {
                continue;
            };
            if self.definition.is_join_first(&activation.node) {
                let node = &activation.node;
                let visit = self.definition.join_visit(node, &activation.lineage);
                settled_joins.insert(node.clone(), visit);
            }
            let source = checkpoint
                .frontier
                .iter()
                .find(|source| {
                    source.node == activation.node && source.lineage == activation.lineage
                })
                .ok_or_else(|| {
                    AppError::Integration("completed activation source is unavailable".to_owned())
                })?;
            sources.push(source.clone());
            let ordinal = first_ordinal
                .checked_add(outcomes.len() as u64)
                .ok_or_else(|| AppError::Conflict("run action ordinal is exhausted".to_owned()))?;
            outcomes.push(ActionOutcome {
                node: activation.node.clone(),
                ordinal,
                result: result.clone(),
            });
        }
        Ok(BspDecision::Barrier {
            state,
            frontier,
            settled_joins,
            superstep: self.next_superstep(checkpoint)?,
            outcomes,
            sources,
        })
    }

    fn route_committed(
        &self,
        checkpoint: &CheckpointRecord,
        sources: &[FrontierRecord],
    ) -> Result<BspDecision, AppError> {
        let mut routed = RoutedFrontier::new(self.definition, self.conditions);
        let state = WorkflowState::new(checkpoint.state.clone())?;
        for remaining in &checkpoint.frontier {
            routed.insert(remaining.clone())?;
        }
        for source in sources {
            if !routed.route(&source.node, &source.lineage, &state)? {
                return Ok(BspDecision::limit("workflow lineage byte bound exhausted"));
            }
        }
        Ok(BspDecision::Routed {
            frontier: routed.finish(),
        })
    }

    fn next_superstep(&self, checkpoint: &CheckpointRecord) -> Result<u64, AppError> {
        checkpoint
            .superstep
            .checked_add(1)
            .filter(|next| *next <= MAX_SUPERSTEPS)
            .ok_or_else(|| AppError::Conflict("workflow superstep bound exhausted".to_owned()))
    }
}

impl AgentRequest {
    pub(crate) fn recover(
        definition: &CompiledDefinition,
        state: &Map<String, Value>,
        node: &str,
        lineage: &str,
        attempt_identity: Option<AttemptIdentity>,
    ) -> Result<Self, AppError> {
        let Some(Step::Agent {
            agent,
            prompt,
            stream,
            structured_schema,
            text_target,
            structured_target,
            ..
        }) = definition.node(node).map(|node| node.step())
        else {
            return Err(AppError::Integration(
                "agent control definition is unavailable".to_owned(),
            ));
        };
        Ok(Self {
            node: node.to_owned(),
            lineage: lineage.to_owned(),
            attempt_identity,
            agent: agent.clone(),
            prompt: PromptPart::render_all(prompt, state)?,
            stream: *stream,
            partials: None,
            structured_schema: structured_schema.clone(),
            text_target: text_target.clone(),
            structured_target: structured_target.clone(),
        })
    }

    pub(crate) fn node(&self) -> &str {
        &self.node
    }

    pub(crate) fn lineage(&self) -> &str {
        &self.lineage
    }

    pub(crate) fn attempt_identity(&self) -> Option<&AttemptIdentity> {
        self.attempt_identity.as_ref()
    }

    pub(crate) fn agent(&self) -> &str {
        &self.agent
    }

    pub(crate) fn prompt(&self) -> &str {
        &self.prompt
    }

    pub(crate) fn is_streaming(&self) -> bool {
        self.stream
    }

    pub(crate) fn observe_partials(&mut self, sender: tokio::sync::mpsc::Sender<ExecutionEvent>) {
        self.partials = Some(sender);
    }

    pub(crate) fn take_partials(&mut self) -> Option<tokio::sync::mpsc::Sender<ExecutionEvent>> {
        self.partials.take()
    }

    pub(crate) fn structured_schema(&self) -> Option<&Value> {
        self.structured_schema.as_ref()
    }

    pub(crate) fn text_target(&self) -> Option<&str> {
        self.text_target.as_deref()
    }

    pub(crate) fn structured_target(&self) -> Option<&str> {
        self.structured_target.as_deref()
    }
}

impl StagedActivationRecord {
    pub(crate) fn complete(
        node: String,
        lineage: String,
        changes: Vec<StateChangeRecord>,
        result: Map<String, Value>,
    ) -> Self {
        Self {
            node,
            lineage,
            outcome: StagedOutcomeRecord::Complete { changes, result },
            children: None,
        }
    }

    pub(crate) fn failed(
        node: String,
        lineage: String,
        category: FailureCategory,
        message: String,
    ) -> Self {
        Self {
            node,
            lineage,
            outcome: StagedOutcomeRecord::Failed { category, message },
            children: None,
        }
    }

    fn changes(&self) -> &[StateChangeRecord] {
        match &self.outcome {
            StagedOutcomeRecord::Complete { changes, .. } => changes,
            StagedOutcomeRecord::Deferred | StagedOutcomeRecord::Failed { .. } => &[],
        }
    }

    fn reducer(&self, target: &str, definition: &CompiledDefinition) -> Option<Reducer> {
        match definition.node(&self.node).map(|node| node.step()) {
            Some(Step::Pipeline { reductions, .. }) if reductions.is_empty() => {
                definition.reducer(target)
            }
            Some(step) if step.child_plan().is_some() => step
                .child_plan()?
                .1
                .iter()
                .find(|reduction| reduction.target() == target)
                .map(|reduction| reduction.reducer()),
            _ => definition.reducer(target),
        }
    }
}

impl<'definition, C: ConditionBackend> RoutedFrontier<'definition, C> {
    fn new(definition: &'definition CompiledDefinition, conditions: &'definition [C]) -> Self {
        Self {
            definition,
            conditions,
            entries: BTreeMap::new(),
        }
    }

    fn route(
        &mut self,
        source: &str,
        lineage: &str,
        state: &WorkflowState,
    ) -> Result<bool, AppError> {
        let route = self.definition.route(source).ok_or_else(|| {
            AppError::Integration("compiled workflow route is missing".to_owned())
        })?;
        for branch in route.branches() {
            let selected = branch.condition().map_or(Ok(true), |condition| {
                condition.evaluate(state, self.conditions)
            })?;
            if !selected {
                continue;
            }
            if let Some(target) = branch.target().node() {
                if lineage
                    .len()
                    .checked_add(target.len())
                    .and_then(|bytes| bytes.checked_add(1))
                    .is_none_or(|bytes| bytes > MAX_RUNTIME_BYTES)
                {
                    return Ok(false);
                }
                self.insert(FrontierRecord {
                    node: target.to_owned(),
                    arrived: true,
                    lineage: format!("{lineage}/{target}"),
                })?;
            }
            if matches!(route.mode(), RouteMode::First) {
                break;
            }
        }
        Ok(true)
    }

    fn insert(&mut self, entry: FrontierRecord) -> Result<(), AppError> {
        let identity = match self.definition.node(&entry.node).map(|node| node.step()) {
            Some(Step::JoinAll {} | Step::JoinFirst {}) => {
                RouteIdentity::Join(self.definition.join_visit(&entry.node, &entry.lineage))
            }
            _ => RouteIdentity::Lineage(entry.lineage.clone()),
        };
        let key = (entry.node.clone(), identity);
        if let Some(existing) = self.entries.get_mut(&key) {
            existing.arrived |= entry.arrived;
            if entry.lineage < existing.lineage {
                existing.lineage = entry.lineage;
            }
        } else {
            self.entries.insert(key, entry);
        }
        if self.entries.len() > MAX_FRONTIER {
            return Err(AppError::InvalidInput(
                "workflow frontier exceeds the private bound".to_owned(),
            ));
        }
        Ok(())
    }

    fn finish(self) -> Vec<FrontierRecord> {
        self.entries.into_values().collect()
    }
}

impl ChildTask {
    fn resolve_key<C: ConditionBackend>(
        value: Option<&ValueExpr>,
        default: String,
        state: &WorkflowState,
        conditions: &[C],
    ) -> Result<String, AppError> {
        match value {
            Some(value) => match value.evaluate(state, conditions)? {
                Value::String(key) => Ok(key),
                _ => Err(AppError::InvalidInput(
                    "child task key must be a string".into(),
                )),
            },
            None => Ok(default),
        }
    }

    fn resolved(
        value: Value,
        resolve: &mut impl FnMut(WorkflowId, Option<String>) -> Result<(WorkflowId, String), AppError>,
    ) -> Result<(Self, Map<String, Value>), AppError> {
        let Value::Object(mut fields) = value else {
            return Err(AppError::InvalidInput(
                "resolved child task must be an object".into(),
            ));
        };
        let task_key = match fields.remove("task_key") {
            Some(Value::String(key)) => key,
            _ => {
                return Err(AppError::InvalidInput(
                    "resolved child task requires a string task_key".into(),
                ));
            }
        };
        let workflow = match fields.remove("workflow") {
            Some(Value::String(workflow)) => workflow.parse()?,
            _ => {
                return Err(AppError::InvalidInput(
                    "resolved child task requires a workflow string".into(),
                ));
            }
        };
        let revision = match fields.remove("revision") {
            Some(Value::String(revision)) => Some(revision),
            None => None,
            _ => {
                return Err(AppError::InvalidInput(
                    "resolved child task revision must be a string".into(),
                ));
            }
        };
        let (workflow, revision) = resolve(workflow, revision)?;
        let input = match fields.remove("input") {
            Some(Value::Object(input)) => input,
            _ => {
                return Err(AppError::InvalidInput(
                    "resolved child task requires object input".into(),
                ));
            }
        };
        let inputs = match fields.remove("inputs") {
            Some(Value::Object(inputs)) => inputs,
            None => Map::new(),
            _ => {
                return Err(AppError::InvalidInput(
                    "resolved child task inputs must be an object".into(),
                ));
            }
        };
        let history = match fields.remove("history") {
            Some(value) => serde_json::from_value(value).map_err(|_| {
                AppError::InvalidInput("resolved child task history is invalid".into())
            })?,
            None => Default::default(),
        };
        let initializer = fields
            .remove("initializer")
            .map(|value| {
                serde_json::from_value::<ChildInitializer<Value>>(value).map_err(|_| {
                    AppError::InvalidInput("resolved child initializer is invalid".into())
                })
            })
            .transpose()?;
        if let Some(initializer) = &initializer {
            initializer.validate()?;
        }
        if !fields.is_empty() {
            return Err(AppError::InvalidInput(
                "resolved child task contains unknown fields".into(),
            ));
        }
        Ok((
            Self {
                workflow,
                revision,
                task_key,
                input,
                history,
                initializer,
            },
            inputs,
        ))
    }
}