runifold-workflow 0.8.2

Durable workflow and Agent orchestration runtime for Runifold
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
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
use std::{future::Future, pin::Pin, sync::Arc};

use runifold_core::{CapabilitySet, ChildEvent, EventId, RunContext, RunEventKind};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use thiserror::Error;

use crate::checkpoint::WorkflowCheckpointCursor;
use crate::execution::{
    check_lifecycle, record_domain, save_checkpoint, validate_exact_usage, validate_usage_floor,
};
use crate::workflow::WorkflowNode;
use crate::{
    StepId, WorkflowCheckpointPhase, WorkflowCheckpointState, WorkflowError, WorkflowResumePolicy,
    WorkflowStep,
};

const MAX_REVIEW_REASON_BYTES: usize = 4_096;
const MAX_REVIEW_FEEDBACK_BYTES: usize = 1_048_576;

/// Bounded repair policy for one reviewable workflow step.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct WorkflowRemediationPolicy {
    max_repairs: u32,
}

impl WorkflowRemediationPolicy {
    /// Creates a policy allowing at most `max_repairs` additional generations.
    pub const fn new(max_repairs: u32) -> Self {
        Self { max_repairs }
    }

    /// Returns the number of additional generations allowed after the first.
    pub const fn max_repairs(self) -> u32 {
        self.max_repairs
    }
}

/// Canonical request presented to an application-owned output reviewer.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct WorkflowReviewRequest {
    /// Stable workflow node under review.
    pub step: StepId,
    /// One-based generation attempt.
    pub attempt: u32,
    /// Original value supplied to the repairable node.
    pub original_input: Value,
    /// Candidate produced by the current generation attempt.
    pub candidate: Value,
}

/// Application-owned decision over one generated candidate.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum WorkflowReviewVerdict {
    /// Accept the candidate as the node's stable output.
    Approve,
    /// Generate another candidate with structured reviewer feedback.
    Repair {
        /// Application-defined findings or repair instructions.
        feedback: Value,
    },
    /// Permanently reject the candidate.
    Reject {
        /// Bounded operator-facing explanation.
        reason: String,
    },
}

impl WorkflowReviewVerdict {
    /// Creates an approval decision.
    pub const fn approve() -> Self {
        Self::Approve
    }

    /// Creates a repair decision with application-defined feedback.
    ///
    /// # Errors
    ///
    /// Rejects feedback whose canonical JSON representation exceeds 1 MiB.
    pub fn repair(feedback: Value) -> Result<Self, WorkflowReviewError> {
        validate_feedback(&feedback)?;
        Ok(Self::Repair { feedback })
    }

    /// Creates a permanent rejection with a safe explanation.
    ///
    /// # Errors
    ///
    /// Rejects blank explanations and values above 4 KiB.
    pub fn reject(reason: impl Into<String>) -> Result<Self, WorkflowReviewError> {
        let reason = reason.into();
        validate_reason(&reason)?;
        Ok(Self::Reject { reason })
    }

    fn validate(&self) -> Result<(), WorkflowReviewError> {
        match self {
            Self::Approve => Ok(()),
            Self::Repair { feedback } => validate_feedback(feedback),
            Self::Reject { reason } => validate_reason(reason),
        }
    }
}

/// Failure returned by an application-owned output reviewer.
#[derive(Clone, Debug, Error, Eq, PartialEq)]
#[non_exhaustive]
pub enum WorkflowReviewError {
    /// Reviewer feedback exceeded the durable checkpoint limit.
    #[error("workflow review feedback exceeds the 1 MiB durable limit")]
    FeedbackTooLarge,
    /// A rejection reason was blank or exceeded its durable limit.
    #[error("workflow review rejection reason must contain 1..=4096 bytes")]
    InvalidRejectionReason,
    /// The reviewer could not evaluate the candidate.
    #[error("workflow review failed: {0}")]
    Execution(String),
}

/// Boxed asynchronous reviewer result.
#[cfg(not(target_arch = "wasm32"))]
pub type WorkflowReviewFuture<'a> =
    Pin<Box<dyn Future<Output = Result<WorkflowReviewVerdict, WorkflowReviewError>> + Send + 'a>>;

/// Boxed asynchronous reviewer result on single-threaded WASM.
#[cfg(target_arch = "wasm32")]
pub type WorkflowReviewFuture<'a> =
    Pin<Box<dyn Future<Output = Result<WorkflowReviewVerdict, WorkflowReviewError>> + 'a>>;

/// Provider-neutral review boundary for a repairable workflow step.
pub trait WorkflowReviewer: Send + Sync {
    /// Reviews one candidate without owning remediation or retry policy.
    fn review<'a>(
        &'a self,
        request: WorkflowReviewRequest,
        run: &'a RunContext,
    ) -> WorkflowReviewFuture<'a>;
}

/// Structured input supplied to the second and later generation attempts.
///
/// `input` is a model-ready textual prompt, so an [`crate::AgentStep`] can
/// consume this value directly. Custom steps can instead inspect the complete
/// original input, previous candidate, feedback, and attempt fields.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct WorkflowRepairInput {
    /// Model-ready prompt containing trusted runtime repair context.
    pub input: String,
    /// Original value supplied to the repairable node.
    pub original_input: Value,
    /// Candidate rejected by the preceding review.
    pub previous_candidate: Value,
    /// Application-defined reviewer findings or repair instructions.
    pub feedback: Value,
    /// One-based generation attempt receiving this input.
    pub attempt: u32,
}

impl WorkflowRepairInput {
    fn new(
        original_input: Value,
        previous_candidate: Value,
        feedback: Value,
        attempt: u32,
    ) -> Self {
        let original_prompt = model_prompt(&original_input);
        let model_candidate = model_visible_candidate(&previous_candidate);
        let instruction = json!({
            "attempt": attempt,
            "previous_candidate": model_candidate,
            "feedback": feedback,
            "instruction": "Produce a corrected candidate that addresses the reviewer feedback. Do not claim the previous candidate was accepted.",
        });
        let input = format!(
            "{original_prompt}\n<runifold_workflow_repair trust=\"runtime\">{instruction}</runifold_workflow_repair>"
        );
        Self {
            input,
            original_input,
            previous_candidate,
            feedback,
            attempt,
        }
    }
}

/// Durable substate of one repairable workflow node.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "state", rename_all = "snake_case")]
#[non_exhaustive]
pub enum WorkflowRemediationCheckpoint {
    /// The next generation input is durable and has not started.
    GenerationReady {
        /// Canonical input for the pending generation.
        input: Value,
    },
    /// A generation may have partially executed.
    GenerationInFlight {
        /// Canonical input supplied to the generation attempt.
        input: Value,
    },
    /// A generated candidate is durable and has not entered review.
    ReviewReady {
        /// Durable candidate awaiting review.
        candidate: Value,
    },
    /// Review of a durable candidate may have partially executed.
    ReviewInFlight {
        /// Durable candidate supplied to the reviewer.
        candidate: Value,
    },
    /// Review accepted a durable candidate before the outer node commit.
    Approved {
        /// Accepted output awaiting the outer node commit.
        output: Value,
    },
    /// Review permanently rejected a candidate.
    Rejected {
        /// Candidate rejected by the reviewer.
        candidate: Value,
        /// Safe reviewer explanation.
        reason: String,
    },
    /// The configured repair limit was exhausted.
    Exhausted {
        /// Last generated candidate.
        candidate: Value,
        /// Feedback that would have required another generation.
        feedback: Value,
    },
}

pub(crate) struct RepairableNode {
    pub(crate) generator: Arc<dyn WorkflowStep>,
    pub(crate) reviewer: Arc<dyn WorkflowReviewer>,
    pub(crate) reviewer_capabilities: CapabilitySet,
    pub(crate) policy: WorkflowRemediationPolicy,
}

pub(crate) fn prepare_remediation_resume(
    state: &mut WorkflowCheckpointState,
    run: &RunContext,
    policy: WorkflowResumePolicy,
) -> Result<(), WorkflowError> {
    let WorkflowCheckpointPhase::Remediating {
        step,
        attempt,
        original_input,
        checkpoint,
    } = state.phase.clone()
    else {
        return Err(WorkflowError::CheckpointIdentityMismatch);
    };
    match checkpoint {
        WorkflowRemediationCheckpoint::GenerationInFlight { input } => {
            require_retry_authority(&step, policy)?;
            validate_usage_floor(state.usage, run.budget().usage())?;
            state.usage = run.budget().usage();
            state.phase = WorkflowCheckpointPhase::Remediating {
                step,
                attempt,
                original_input,
                checkpoint: WorkflowRemediationCheckpoint::GenerationReady { input },
            };
        }
        WorkflowRemediationCheckpoint::ReviewInFlight { candidate } => {
            require_retry_authority(&step, policy)?;
            validate_usage_floor(state.usage, run.budget().usage())?;
            state.usage = run.budget().usage();
            state.phase = WorkflowCheckpointPhase::Remediating {
                step,
                attempt,
                original_input,
                checkpoint: WorkflowRemediationCheckpoint::ReviewReady { candidate },
            };
        }
        WorkflowRemediationCheckpoint::Rejected { reason, .. } => {
            validate_exact_usage(state.usage, run.budget().usage())?;
            return Err(WorkflowError::RemediationRejected {
                step,
                attempts: attempt,
                reason,
            });
        }
        WorkflowRemediationCheckpoint::Exhausted { .. } => {
            validate_exact_usage(state.usage, run.budget().usage())?;
            return Err(WorkflowError::RemediationExhausted {
                step,
                attempts: attempt,
            });
        }
        WorkflowRemediationCheckpoint::GenerationReady { .. }
        | WorkflowRemediationCheckpoint::ReviewReady { .. }
        | WorkflowRemediationCheckpoint::Approved { .. } => {
            validate_exact_usage(state.usage, run.budget().usage())?;
        }
    }
    Ok(())
}

fn require_retry_authority(
    step: &StepId,
    policy: WorkflowResumePolicy,
) -> Result<(), WorkflowError> {
    if policy == WorkflowResumePolicy::RejectAmbiguous {
        Err(WorkflowError::AmbiguousCheckpoint { step: step.clone() })
    } else {
        Ok(())
    }
}

pub(crate) async fn execute_repairable_node(
    workflow: &str,
    node: &WorkflowNode,
    repairable: &RepairableNode,
    state: &mut WorkflowCheckpointState,
    run: &RunContext,
    caused_by: Option<EventId>,
    checkpoint: &mut Option<&mut WorkflowCheckpointCursor>,
) -> Result<Value, WorkflowError> {
    let (mut attempt, original_input, mut remediation) = remediation_state(node, state)?;
    loop {
        check_lifecycle(run)?;
        let context = RemediationAttemptContext {
            workflow,
            node,
            repairable,
            run,
            caused_by,
            attempt,
            original_input: &original_input,
        };
        match remediation {
            WorkflowRemediationCheckpoint::GenerationReady { input } => {
                remediation = generate_candidate(&context, state, checkpoint, input).await?;
            }
            WorkflowRemediationCheckpoint::ReviewReady { candidate } => {
                match review_candidate(&context, state, checkpoint, candidate).await? {
                    RemediationAction::Continue {
                        next_attempt,
                        checkpoint,
                    } => {
                        attempt = next_attempt;
                        remediation = checkpoint;
                    }
                    RemediationAction::Complete(output) => return Ok(output),
                }
            }
            WorkflowRemediationCheckpoint::Approved { output } => return Ok(output),
            WorkflowRemediationCheckpoint::Rejected { reason, .. } => {
                return Err(WorkflowError::RemediationRejected {
                    step: node.id.clone(),
                    attempts: attempt,
                    reason,
                });
            }
            WorkflowRemediationCheckpoint::Exhausted { .. } => {
                return Err(WorkflowError::RemediationExhausted {
                    step: node.id.clone(),
                    attempts: attempt,
                });
            }
            WorkflowRemediationCheckpoint::GenerationInFlight { .. }
            | WorkflowRemediationCheckpoint::ReviewInFlight { .. } => {
                return Err(WorkflowError::CheckpointIdentityMismatch);
            }
        }
    }
}

enum RemediationAction {
    Continue {
        next_attempt: u32,
        checkpoint: WorkflowRemediationCheckpoint,
    },
    Complete(Value),
}

struct RemediationAttemptContext<'a> {
    workflow: &'a str,
    node: &'a WorkflowNode,
    repairable: &'a RepairableNode,
    run: &'a RunContext,
    caused_by: Option<EventId>,
    attempt: u32,
    original_input: &'a Value,
}

async fn generate_candidate(
    context: &RemediationAttemptContext<'_>,
    state: &mut WorkflowCheckpointState,
    checkpoint: &mut Option<&mut WorkflowCheckpointCursor>,
    input: Value,
) -> Result<WorkflowRemediationCheckpoint, WorkflowError> {
    state.phase = remediation_phase(
        context.node,
        context.attempt,
        context.original_input.clone(),
        WorkflowRemediationCheckpoint::GenerationInFlight {
            input: input.clone(),
        },
    );
    state.usage = context.run.budget().usage();
    save_checkpoint(checkpoint, state).await?;
    let candidate = execute_generation(
        context.workflow,
        context.node,
        context.repairable,
        input,
        context.attempt,
        context.run,
        context.caused_by,
    )
    .await?;
    let remediation = WorkflowRemediationCheckpoint::ReviewReady {
        candidate: candidate.clone(),
    };
    state.phase = remediation_phase(
        context.node,
        context.attempt,
        context.original_input.clone(),
        remediation.clone(),
    );
    state.usage = context.run.budget().usage();
    save_checkpoint(checkpoint, state).await?;
    Ok(remediation)
}

async fn review_candidate(
    context: &RemediationAttemptContext<'_>,
    state: &mut WorkflowCheckpointState,
    checkpoint: &mut Option<&mut WorkflowCheckpointCursor>,
    candidate: Value,
) -> Result<RemediationAction, WorkflowError> {
    state.phase = remediation_phase(
        context.node,
        context.attempt,
        context.original_input.clone(),
        WorkflowRemediationCheckpoint::ReviewInFlight {
            candidate: candidate.clone(),
        },
    );
    state.usage = context.run.budget().usage();
    save_checkpoint(checkpoint, state).await?;
    let verdict = execute_review(
        context.workflow,
        context.node,
        context.repairable,
        WorkflowReviewRequest {
            step: context.node.id.clone(),
            attempt: context.attempt,
            original_input: context.original_input.clone(),
            candidate: candidate.clone(),
        },
        context.run,
        context.caused_by,
    )
    .await?;
    apply_review_verdict(context, state, checkpoint, candidate, verdict).await
}

async fn apply_review_verdict(
    context: &RemediationAttemptContext<'_>,
    state: &mut WorkflowCheckpointState,
    checkpoint: &mut Option<&mut WorkflowCheckpointCursor>,
    candidate: Value,
    verdict: WorkflowReviewVerdict,
) -> Result<RemediationAction, WorkflowError> {
    match verdict {
        WorkflowReviewVerdict::Approve => {
            state.phase = remediation_phase(
                context.node,
                context.attempt,
                context.original_input.clone(),
                WorkflowRemediationCheckpoint::Approved {
                    output: candidate.clone(),
                },
            );
            state.usage = context.run.budget().usage();
            save_checkpoint(checkpoint, state).await?;
            Ok(RemediationAction::Complete(candidate))
        }
        WorkflowReviewVerdict::Reject { reason } => {
            state.phase = remediation_phase(
                context.node,
                context.attempt,
                context.original_input.clone(),
                WorkflowRemediationCheckpoint::Rejected {
                    candidate,
                    reason: reason.clone(),
                },
            );
            state.usage = context.run.budget().usage();
            save_checkpoint(checkpoint, state).await?;
            Err(WorkflowError::RemediationRejected {
                step: context.node.id.clone(),
                attempts: context.attempt,
                reason,
            })
        }
        WorkflowReviewVerdict::Repair { feedback } => {
            if context.attempt >= context.repairable.policy.max_repairs().saturating_add(1) {
                state.phase = remediation_phase(
                    context.node,
                    context.attempt,
                    context.original_input.clone(),
                    WorkflowRemediationCheckpoint::Exhausted {
                        candidate,
                        feedback,
                    },
                );
                state.usage = context.run.budget().usage();
                save_checkpoint(checkpoint, state).await?;
                return Err(WorkflowError::RemediationExhausted {
                    step: context.node.id.clone(),
                    attempts: context.attempt,
                });
            }
            let next_attempt = context
                .attempt
                .checked_add(1)
                .ok_or(WorkflowError::CheckpointIdentityMismatch)?;
            let repair_input = WorkflowRepairInput::new(
                context.original_input.clone(),
                candidate,
                feedback,
                next_attempt,
            );
            let remediation = WorkflowRemediationCheckpoint::GenerationReady {
                input: serde_json::to_value(repair_input)?,
            };
            state.phase = remediation_phase(
                context.node,
                next_attempt,
                context.original_input.clone(),
                remediation.clone(),
            );
            state.usage = context.run.budget().usage();
            save_checkpoint(checkpoint, state).await?;
            Ok(RemediationAction::Continue {
                next_attempt,
                checkpoint: remediation,
            })
        }
    }
}

fn remediation_state(
    node: &WorkflowNode,
    state: &WorkflowCheckpointState,
) -> Result<(u32, Value, WorkflowRemediationCheckpoint), WorkflowError> {
    match &state.phase {
        WorkflowCheckpointPhase::Ready => Ok((
            1,
            state.value.clone(),
            WorkflowRemediationCheckpoint::GenerationReady {
                input: state.value.clone(),
            },
        )),
        WorkflowCheckpointPhase::Remediating {
            step,
            attempt,
            original_input,
            checkpoint,
        } if *step == node.id => Ok((*attempt, original_input.clone(), checkpoint.clone())),
        _ => Err(WorkflowError::CheckpointIdentityMismatch),
    }
}

fn remediation_phase(
    node: &WorkflowNode,
    attempt: u32,
    original_input: Value,
    checkpoint: WorkflowRemediationCheckpoint,
) -> WorkflowCheckpointPhase {
    WorkflowCheckpointPhase::Remediating {
        step: node.id.clone(),
        attempt,
        original_input,
        checkpoint,
    }
}

async fn execute_generation(
    workflow: &str,
    node: &WorkflowNode,
    repairable: &RepairableNode,
    input: Value,
    attempt: u32,
    run: &RunContext,
    caused_by: Option<EventId>,
) -> Result<Value, WorkflowError> {
    let started = record_domain(
        run,
        "remediation.generation.started",
        json!({
            "workflow": workflow,
            "step": node.id,
            "attempt": attempt,
        }),
        caused_by,
    )?;
    let mut child = run.child(node.capabilities.clone()).map_err(|error| {
        WorkflowError::AuthorityEscalation {
            step: node.id.clone(),
            capability: error.capability,
        }
    })?;
    if let Some(event_id) = started {
        child = child.with_cause(event_id);
    }
    run.record(
        RunEventKind::Child(ChildEvent::Started {
            child_run_id: child.run_id(),
        }),
        started,
    )?;
    match repairable.generator.execute(input, &child).await {
        Ok(output) => {
            run.record(
                RunEventKind::Child(ChildEvent::Completed {
                    child_run_id: child.run_id(),
                }),
                started,
            )?;
            record_domain(
                run,
                "remediation.generation.completed",
                json!({
                    "workflow": workflow,
                    "step": node.id,
                    "attempt": attempt,
                }),
                started,
            )?;
            Ok(output)
        }
        Err(source) => {
            run.record(
                RunEventKind::Child(ChildEvent::Failed {
                    child_run_id: child.run_id(),
                }),
                started,
            )?;
            Err(WorkflowError::Step {
                step: node.id.clone(),
                source: Box::new(source),
            })
        }
    }
}

async fn execute_review(
    workflow: &str,
    node: &WorkflowNode,
    repairable: &RepairableNode,
    request: WorkflowReviewRequest,
    run: &RunContext,
    caused_by: Option<EventId>,
) -> Result<WorkflowReviewVerdict, WorkflowError> {
    let attempt = request.attempt;
    let started = record_domain(
        run,
        "remediation.review.started",
        json!({
            "workflow": workflow,
            "step": node.id,
            "attempt": attempt,
        }),
        caused_by,
    )?;
    let mut child = run
        .child(repairable.reviewer_capabilities.clone())
        .map_err(|error| WorkflowError::AuthorityEscalation {
            step: node.id.clone(),
            capability: error.capability,
        })?;
    if let Some(event_id) = started {
        child = child.with_cause(event_id);
    }
    run.record(
        RunEventKind::Child(ChildEvent::Started {
            child_run_id: child.run_id(),
        }),
        started,
    )?;
    let verdict = repairable
        .reviewer
        .review(request, &child)
        .await
        .and_then(|verdict| {
            verdict.validate()?;
            Ok(verdict)
        });
    match verdict {
        Ok(verdict) => {
            run.record(
                RunEventKind::Child(ChildEvent::Completed {
                    child_run_id: child.run_id(),
                }),
                started,
            )?;
            record_domain(
                run,
                "remediation.review.completed",
                json!({
                    "workflow": workflow,
                    "step": node.id,
                    "attempt": attempt,
                    "verdict": match &verdict {
                        WorkflowReviewVerdict::Approve => "approve",
                        WorkflowReviewVerdict::Repair { .. } => "repair",
                        WorkflowReviewVerdict::Reject { .. } => "reject",
                    },
                }),
                started,
            )?;
            Ok(verdict)
        }
        Err(source) => {
            run.record(
                RunEventKind::Child(ChildEvent::Failed {
                    child_run_id: child.run_id(),
                }),
                started,
            )?;
            Err(WorkflowError::Review {
                step: node.id.clone(),
                source,
            })
        }
    }
}

fn model_prompt(input: &Value) -> String {
    match input {
        Value::String(prompt) => prompt.clone(),
        Value::Object(object) => object
            .get("input")
            .and_then(Value::as_str)
            .map_or_else(|| input.to_string(), ToOwned::to_owned),
        _ => input.to_string(),
    }
}

fn model_visible_candidate(candidate: &Value) -> Value {
    candidate
        .as_object()
        .and_then(|object| object.get("input"))
        .and_then(Value::as_str)
        .map_or_else(|| candidate.clone(), |text| Value::String(text.to_owned()))
}

fn validate_feedback(feedback: &Value) -> Result<(), WorkflowReviewError> {
    if serde_json::to_vec(feedback).is_ok_and(|encoded| encoded.len() <= MAX_REVIEW_FEEDBACK_BYTES)
    {
        Ok(())
    } else {
        Err(WorkflowReviewError::FeedbackTooLarge)
    }
}

fn validate_reason(reason: &str) -> Result<(), WorkflowReviewError> {
    if reason.trim().is_empty() || reason.len() > MAX_REVIEW_REASON_BYTES {
        Err(WorkflowReviewError::InvalidRejectionReason)
    } else {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{
        Arc, Mutex,
        atomic::{AtomicBool, AtomicUsize, Ordering},
    };

    use futures_executor::block_on;
    use runifold_core::{
        Budget, BudgetTracker, CapabilitySet, Checkpoint, CheckpointError, CheckpointErrorKind,
        CheckpointId, CheckpointStore, InMemoryCheckpointStore, RunContext,
    };
    use serde_json::{Value, json};

    use super::{
        WorkflowRemediationCheckpoint, WorkflowRemediationPolicy, WorkflowRepairInput,
        WorkflowReviewError, WorkflowReviewFuture, WorkflowReviewRequest, WorkflowReviewVerdict,
        WorkflowReviewer,
    };
    use crate::{
        Workflow, WorkflowCheckpoint, WorkflowCheckpointPhase, WorkflowCheckpointRevision,
        WorkflowError, WorkflowForkCommand, WorkflowForkPolicy, WorkflowResumePolicy, WorkflowStep,
        WorkflowStepFuture,
    };

    struct CountingGenerator {
        calls: Arc<AtomicUsize>,
        inputs: Arc<Mutex<Vec<Value>>>,
    }

    impl WorkflowStep for CountingGenerator {
        fn execute<'a>(&'a self, input: Value, _run: &'a RunContext) -> WorkflowStepFuture<'a> {
            let attempt = self.calls.fetch_add(1, Ordering::SeqCst) + 1;
            self.inputs
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(input);
            Box::pin(async move { Ok(Value::String(format!("candidate-{attempt}"))) })
        }
    }

    struct RepairOnceReviewer {
        calls: Arc<AtomicUsize>,
        requests: Arc<Mutex<Vec<WorkflowReviewRequest>>>,
    }

    impl WorkflowReviewer for RepairOnceReviewer {
        fn review<'a>(
            &'a self,
            request: WorkflowReviewRequest,
            _run: &'a RunContext,
        ) -> WorkflowReviewFuture<'a> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            let attempt = request.attempt;
            self.requests
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(request);
            Box::pin(async move {
                if attempt == 1 {
                    WorkflowReviewVerdict::repair(json!({
                        "code": "unsafe_claim",
                        "instruction": "remove the unsupported guarantee",
                    }))
                } else {
                    Ok(WorkflowReviewVerdict::approve())
                }
            })
        }
    }

    struct ApproveReviewer {
        calls: Arc<AtomicUsize>,
    }

    impl WorkflowReviewer for ApproveReviewer {
        fn review<'a>(
            &'a self,
            _request: WorkflowReviewRequest,
            _run: &'a RunContext,
        ) -> WorkflowReviewFuture<'a> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            Box::pin(async { Ok(WorkflowReviewVerdict::approve()) })
        }
    }

    struct AlwaysRepairReviewer {
        calls: Arc<AtomicUsize>,
    }

    impl WorkflowReviewer for AlwaysRepairReviewer {
        fn review<'a>(
            &'a self,
            request: WorkflowReviewRequest,
            _run: &'a RunContext,
        ) -> WorkflowReviewFuture<'a> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            Box::pin(
                async move { WorkflowReviewVerdict::repair(json!({"attempt": request.attempt})) },
            )
        }
    }

    struct RejectReviewer;

    impl WorkflowReviewer for RejectReviewer {
        fn review<'a>(
            &'a self,
            _request: WorkflowReviewRequest,
            _run: &'a RunContext,
        ) -> WorkflowReviewFuture<'a> {
            Box::pin(async { WorkflowReviewVerdict::reject("policy denied the candidate") })
        }
    }

    struct FailRevisionOnceStore {
        inner: InMemoryCheckpointStore,
        revision: u64,
        failed: AtomicBool,
    }

    impl FailRevisionOnceStore {
        fn new(revision: u64) -> Self {
            Self {
                inner: InMemoryCheckpointStore::new(),
                revision,
                failed: AtomicBool::new(false),
            }
        }
    }

    impl CheckpointStore for FailRevisionOnceStore {
        fn load(&self, id: CheckpointId) -> Result<Checkpoint, CheckpointError> {
            self.inner.load(id)
        }

        fn compare_and_swap(
            &self,
            checkpoint: &Checkpoint,
            expected_revision: Option<u64>,
        ) -> Result<(), CheckpointError> {
            if checkpoint.revision == self.revision && !self.failed.swap(true, Ordering::SeqCst) {
                return Err(CheckpointError::new(
                    CheckpointErrorKind::Storage,
                    "injected remediation checkpoint interruption",
                ));
            }
            self.inner.compare_and_swap(checkpoint, expected_revision)
        }
    }

    #[test]
    fn repairable_step_approves_the_first_candidate() {
        let generator_calls = Arc::new(AtomicUsize::new(0));
        let reviewer_calls = Arc::new(AtomicUsize::new(0));
        let workflow = workflow(
            generator_calls.clone(),
            Arc::new(Mutex::new(Vec::new())),
            ApproveReviewer {
                calls: reviewer_calls.clone(),
            },
            WorkflowRemediationPolicy::new(2),
        );
        let run = root_run();

        let outcome = block_on(workflow.run("write a claim", &run)).unwrap();

        assert_eq!(outcome.output, json!("candidate-1"));
        assert_eq!(generator_calls.load(Ordering::SeqCst), 1);
        assert_eq!(reviewer_calls.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn repair_feedback_is_injected_and_the_new_candidate_is_reviewed() {
        let generator_calls = Arc::new(AtomicUsize::new(0));
        let reviewer_calls = Arc::new(AtomicUsize::new(0));
        let inputs = Arc::new(Mutex::new(Vec::new()));
        let requests = Arc::new(Mutex::new(Vec::new()));
        let workflow = workflow(
            generator_calls.clone(),
            inputs.clone(),
            RepairOnceReviewer {
                calls: reviewer_calls.clone(),
                requests: requests.clone(),
            },
            WorkflowRemediationPolicy::new(2),
        );
        let run = root_run();

        let outcome = block_on(workflow.run("write a claim", &run)).unwrap();

        assert_eq!(outcome.output, json!("candidate-2"));
        assert_eq!(generator_calls.load(Ordering::SeqCst), 2);
        assert_eq!(reviewer_calls.load(Ordering::SeqCst), 2);
        let inputs = inputs
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert_eq!(inputs[0], json!("write a claim"));
        let repair: WorkflowRepairInput = serde_json::from_value(inputs[1].clone()).unwrap();
        assert_eq!(repair.attempt, 2);
        assert_eq!(repair.original_input, json!("write a claim"));
        assert_eq!(repair.previous_candidate, json!("candidate-1"));
        assert_eq!(repair.feedback["code"], "unsafe_claim");
        assert!(repair.input.contains("runifold_workflow_repair"));
        let requests = requests
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert_eq!(requests[0].attempt, 1);
        assert_eq!(requests[1].attempt, 2);
    }

    #[test]
    fn exhausted_remediation_is_durable_and_does_not_run_again_on_resume() {
        let generator_calls = Arc::new(AtomicUsize::new(0));
        let reviewer_calls = Arc::new(AtomicUsize::new(0));
        let workflow = workflow(
            generator_calls.clone(),
            Arc::new(Mutex::new(Vec::new())),
            AlwaysRepairReviewer {
                calls: reviewer_calls.clone(),
            },
            WorkflowRemediationPolicy::new(1),
        );
        let store = Arc::new(InMemoryCheckpointStore::new());
        let checkpoint = WorkflowCheckpoint::new(store);
        let run = root_run();

        let error =
            block_on(workflow.run_checkpointed("write a claim", &run, &checkpoint)).unwrap_err();

        assert!(matches!(
            error,
            WorkflowError::RemediationExhausted { attempts: 2, .. }
        ));
        let (_, state) = checkpoint.load().unwrap();
        assert!(matches!(
            state.phase,
            WorkflowCheckpointPhase::Remediating {
                attempt: 2,
                checkpoint: WorkflowRemediationCheckpoint::Exhausted { .. },
                ..
            }
        ));
        let resumed =
            block_on(workflow.resume(&checkpoint, &run, WorkflowResumePolicy::RejectAmbiguous))
                .unwrap_err();
        assert!(matches!(
            resumed,
            WorkflowError::RemediationExhausted { attempts: 2, .. }
        ));
        assert_eq!(generator_calls.load(Ordering::SeqCst), 2);
        assert_eq!(reviewer_calls.load(Ordering::SeqCst), 2);
    }

    #[test]
    fn durable_review_ready_resume_does_not_repeat_generation() {
        let generator_calls = Arc::new(AtomicUsize::new(0));
        let reviewer_calls = Arc::new(AtomicUsize::new(0));
        let workflow = workflow(
            generator_calls.clone(),
            Arc::new(Mutex::new(Vec::new())),
            ApproveReviewer {
                calls: reviewer_calls.clone(),
            },
            WorkflowRemediationPolicy::new(1),
        );
        let store = Arc::new(FailRevisionOnceStore::new(3));
        let checkpoint = WorkflowCheckpoint::new(store);
        let run = root_run();

        let first =
            block_on(workflow.run_checkpointed("write a claim", &run, &checkpoint)).unwrap_err();
        assert!(matches!(first, WorkflowError::Checkpoint(_)));
        assert_eq!(generator_calls.load(Ordering::SeqCst), 1);
        assert_eq!(reviewer_calls.load(Ordering::SeqCst), 0);

        let outcome =
            block_on(workflow.resume(&checkpoint, &run, WorkflowResumePolicy::RejectAmbiguous))
                .unwrap();

        assert_eq!(outcome.output, json!("candidate-1"));
        assert_eq!(generator_calls.load(Ordering::SeqCst), 1);
        assert_eq!(reviewer_calls.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn in_flight_generation_requires_explicit_retry_authority() {
        let generator_calls = Arc::new(AtomicUsize::new(0));
        let reviewer_calls = Arc::new(AtomicUsize::new(0));
        let workflow = workflow(
            generator_calls.clone(),
            Arc::new(Mutex::new(Vec::new())),
            ApproveReviewer {
                calls: reviewer_calls.clone(),
            },
            WorkflowRemediationPolicy::new(1),
        );
        let store = Arc::new(FailRevisionOnceStore::new(2));
        let checkpoint = WorkflowCheckpoint::new(store);
        let run = root_run();

        let first =
            block_on(workflow.run_checkpointed("write a claim", &run, &checkpoint)).unwrap_err();
        assert!(matches!(first, WorkflowError::Checkpoint(_)));
        let rejected =
            block_on(workflow.resume(&checkpoint, &run, WorkflowResumePolicy::RejectAmbiguous))
                .unwrap_err();
        assert!(matches!(
            rejected,
            WorkflowError::AmbiguousCheckpoint { .. }
        ));
        let (envelope, _) = checkpoint.load().unwrap();
        let rejected_fork = WorkflowForkCommand::new(
            checkpoint.id(),
            envelope.revision,
            WorkflowForkPolicy::RejectAmbiguous,
        )
        .prepare_checkpoint(envelope.clone())
        .unwrap_err();
        assert_eq!(rejected_fork.kind, CheckpointErrorKind::Conflict);
        let retryable_fork = WorkflowForkCommand::new(
            checkpoint.id(),
            envelope.revision,
            WorkflowForkPolicy::RetryInterruptedStep,
        )
        .prepare_checkpoint(envelope)
        .unwrap();
        let revision = WorkflowCheckpointRevision::from_checkpoint(retryable_fork).unwrap();
        assert!(matches!(
            revision.state.phase,
            WorkflowCheckpointPhase::Remediating {
                checkpoint: WorkflowRemediationCheckpoint::GenerationReady { .. },
                ..
            }
        ));

        let outcome = block_on(workflow.resume(
            &checkpoint,
            &run,
            WorkflowResumePolicy::RetryInterruptedStep,
        ))
        .unwrap();

        assert_eq!(outcome.output, json!("candidate-2"));
        assert_eq!(generator_calls.load(Ordering::SeqCst), 2);
        assert_eq!(reviewer_calls.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn in_flight_review_requires_explicit_retry_without_repeating_generation() {
        let generator_calls = Arc::new(AtomicUsize::new(0));
        let reviewer_calls = Arc::new(AtomicUsize::new(0));
        let workflow = workflow(
            generator_calls.clone(),
            Arc::new(Mutex::new(Vec::new())),
            ApproveReviewer {
                calls: reviewer_calls.clone(),
            },
            WorkflowRemediationPolicy::new(1),
        );
        let store = Arc::new(FailRevisionOnceStore::new(4));
        let checkpoint = WorkflowCheckpoint::new(store);
        let run = root_run();

        let first =
            block_on(workflow.run_checkpointed("write a claim", &run, &checkpoint)).unwrap_err();
        assert!(matches!(first, WorkflowError::Checkpoint(_)));
        assert_eq!(generator_calls.load(Ordering::SeqCst), 1);
        assert_eq!(reviewer_calls.load(Ordering::SeqCst), 1);
        let rejected =
            block_on(workflow.resume(&checkpoint, &run, WorkflowResumePolicy::RejectAmbiguous))
                .unwrap_err();
        assert!(matches!(
            rejected,
            WorkflowError::AmbiguousCheckpoint { .. }
        ));

        let outcome = block_on(workflow.resume(
            &checkpoint,
            &run,
            WorkflowResumePolicy::RetryInterruptedStep,
        ))
        .unwrap();

        assert_eq!(outcome.output, json!("candidate-1"));
        assert_eq!(generator_calls.load(Ordering::SeqCst), 1);
        assert_eq!(reviewer_calls.load(Ordering::SeqCst), 2);
    }

    #[test]
    fn reviewer_rejection_is_a_stable_typed_failure() {
        let workflow = workflow(
            Arc::new(AtomicUsize::new(0)),
            Arc::new(Mutex::new(Vec::new())),
            RejectReviewer,
            WorkflowRemediationPolicy::new(3),
        );

        let error = block_on(workflow.run("write a claim", &root_run())).unwrap_err();

        assert!(matches!(
            error,
            WorkflowError::RemediationRejected {
                attempts: 1,
                reason,
                ..
            } if reason == "policy denied the candidate"
        ));
    }

    #[test]
    fn review_payloads_are_bounded_before_checkpointing() {
        assert!(WorkflowReviewVerdict::reject(" ").is_err());
        assert!(
            WorkflowReviewVerdict::repair(Value::String(
                "x".repeat(super::MAX_REVIEW_FEEDBACK_BYTES)
            ))
            .is_err()
        );
        assert_eq!(
            WorkflowReviewVerdict::reject("x".repeat(super::MAX_REVIEW_REASON_BYTES + 1))
                .unwrap_err(),
            WorkflowReviewError::InvalidRejectionReason
        );
    }

    #[test]
    fn model_repair_prompt_projects_agent_candidate_text_without_full_outcome() {
        let repair = WorkflowRepairInput::new(
            json!("original prompt"),
            json!({
                "input": "visible candidate",
                "outcome": {"provider_metadata": "not-model-visible"},
            }),
            json!({"instruction": "fix it"}),
            2,
        );

        assert!(repair.input.contains("visible candidate"));
        assert!(!repair.input.contains("not-model-visible"));
        assert_eq!(
            repair.previous_candidate["outcome"]["provider_metadata"],
            "not-model-visible"
        );
    }

    fn workflow<R>(
        generator_calls: Arc<AtomicUsize>,
        inputs: Arc<Mutex<Vec<Value>>>,
        reviewer: R,
        policy: WorkflowRemediationPolicy,
    ) -> Workflow
    where
        R: WorkflowReviewer + 'static,
    {
        Workflow::builder("reviewed-generation")
            .repairable_step(
                "draft",
                CountingGenerator {
                    calls: generator_calls,
                    inputs,
                },
                reviewer,
                policy,
                CapabilitySet::new(),
                CapabilitySet::new(),
            )
            .build()
            .unwrap()
    }

    fn root_run() -> RunContext {
        RunContext::root(BudgetTracker::new(Budget::default()), CapabilitySet::new())
    }
}