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
use crate::workflow_snapshot::ActivityStatus;
use crate::{
LoopIterationStatus, LoopNode, LoopStatus, RunSnapshotDTO, WorkflowDefinition, WorkflowNode,
};
use super::topology::{
activity_state, body_topological_order, dependency_is_succeeded, loop_gate_activity_id,
loop_work_activity_id, node_depends, node_human_gate,
};
use super::{AdvanceDecision, OrchestratorAction};
/// Extract wait-resolution metadata from a gate activity for populating
/// `FinishLoopIteration` payload fields.
fn extract_wait_resolution_meta(
snapshot: &RunSnapshotDTO,
gate_activity_id: &str,
) -> (Option<String>, Option<String>, Option<String>, Option<bool>) {
let Some(activity) = snapshot
.activities
.iter()
.find(|a| a.activity_id == gate_activity_id)
else {
return (None, None, None, None);
};
let Some(latest) = activity.attempts.last() else {
return (None, None, None, None);
};
let Some(wait) = latest.wait.as_ref() else {
return (None, None, None, None);
};
let Some(resolution) = wait.resolution.as_ref() else {
return (None, None, None, None);
};
let timed_out = match resolution.kind.as_str() {
"deadlineExceeded" => Some(true),
_ => Some(false),
};
(
resolution.event_id.clone(),
resolution.by.clone(),
resolution.comment.clone(),
timed_out,
)
}
/// Decide the state-transition actions for a loop node.
///
/// Checks whether the loop should start, dispatch body nodes for the running
/// iteration, or transition to the next / final state.
pub(super) fn decide_loop_advancement(
snapshot: &RunSnapshotDTO,
def: &WorkflowDefinition,
loop_id: &str,
loop_node: &LoopNode,
) -> AdvanceDecision {
let run_id = &snapshot.run.run_id;
let loop_state = snapshot.loops.as_ref().and_then(|loops| loops.get(loop_id));
match loop_state {
None => {
// Loop hasn't started → StartLoop + StartLoopIteration(1)
AdvanceDecision {
actions: vec![
OrchestratorAction::StartLoop {
node_id: loop_id.to_string(),
max_iterations: loop_node.max_iterations,
},
OrchestratorAction::StartLoopIteration {
node_id: loop_id.to_string(),
iteration: 1,
},
],
is_succeeded: false,
is_failed: false,
}
}
Some(ls) => match ls.status {
LoopStatus::Running => {
// Find the currently-running iteration.
let running = ls
.iterations
.iter()
.find(|it| matches!(it.status, LoopIterationStatus::Running));
match running {
Some(iter) => process_loop_iteration_body(
snapshot,
def,
run_id,
loop_id,
loop_node,
iter.iteration,
),
None => {
// No running iteration but loop is Running — safety:
// if the last iteration was just finished (rejected), a
// new StartLoopIteration was already emitted. Fallback
// to checking whether we should start the next.
let last_iter = ls.iteration;
if last_iter < loop_node.max_iterations {
AdvanceDecision {
actions: vec![OrchestratorAction::StartLoopIteration {
node_id: loop_id.to_string(),
iteration: last_iter + 1,
}],
is_succeeded: false,
is_failed: false,
}
} else {
AdvanceDecision {
actions: vec![],
is_succeeded: false,
is_failed: false,
}
}
}
}
}
LoopStatus::Succeeded => AdvanceDecision {
actions: vec![],
is_succeeded: true,
is_failed: false,
},
LoopStatus::Failed | LoopStatus::Cancelled => AdvanceDecision {
actions: vec![],
is_succeeded: false,
is_failed: true,
},
},
}
}
/// Process the body nodes of a single loop iteration.
///
/// Walks body nodes in topological order. Returns the first actionable
/// decision: dispatch gate/work, finish the iteration, or finish the loop.
fn process_loop_iteration_body(
snapshot: &RunSnapshotDTO,
def: &WorkflowDefinition,
run_id: &str,
loop_id: &str,
loop_node: &LoopNode,
iteration: u64,
) -> AdvanceDecision {
let body_order = body_topological_order(def, &loop_node.body);
let terminate_node_id = &loop_node.terminate.node;
for node_id in &body_order {
let Some(node) = def.nodes.get(node_id) else {
continue;
};
// Check if this node's intra-body depends are met.
let deps_ok = node_depends(node).iter().all(|dep| {
if loop_node.body.contains(dep) {
// Intra-body dependency → check loop-scoped work activity.
let work_id = loop_work_activity_id(run_id, loop_id, iteration, dep);
activity_state(snapshot, &work_id)
.map(|a| a.status == ActivityStatus::Succeeded)
.unwrap_or(false)
} else {
// External dependency → check globally.
dependency_is_succeeded(snapshot, dep)
}
});
if !deps_ok {
return AdvanceDecision {
actions: vec![],
is_succeeded: false,
is_failed: false,
};
}
let is_terminate = node_id == terminate_node_id;
if is_terminate {
// ── Terminate / decision node ──
match node {
WorkflowNode::Decision(decision_node) => {
let gate_cfg = match decision_node.base.human_gate.as_ref() {
Some(cfg) => cfg,
None => {
// Decision node without humanGate — shouldn't happen
// per validation, but skip silently.
continue;
}
};
let gate_id = loop_gate_activity_id(run_id, loop_id, iteration, node_id);
let Some(gate) = activity_state(snapshot, &gate_id) else {
return AdvanceDecision {
actions: vec![OrchestratorAction::DispatchGate {
node_id: node_id.clone(),
activity_id: gate_id,
human_gate: gate_cfg.clone(),
}],
is_succeeded: false,
is_failed: false,
};
};
match gate.status {
ActivityStatus::Succeeded => {
// Approved → iteration + loop succeeded.
let loop_output = loop_node.output.as_ref().and_then(|out| {
let source_work_id =
loop_work_activity_id(run_id, loop_id, iteration, &out.from);
snapshot.outputs.get(&source_work_id).cloned()
});
let (wait_resolved_event_id, by, comment, timed_out) =
extract_wait_resolution_meta(snapshot, &gate_id);
return AdvanceDecision {
actions: vec![
OrchestratorAction::FinishLoopIteration {
node_id: loop_id.to_string(),
iteration,
resolution: "approved".to_string(),
decision_activity_id: Some(gate_id),
wait_resolved_event_id,
by,
comment,
timed_out,
},
OrchestratorAction::FinishLoop {
node_id: loop_id.to_string(),
final_iteration: iteration,
resolution: "approved".to_string(),
output_ref: loop_output,
error_code: None,
error_class: None,
},
],
is_succeeded: false,
is_failed: false,
};
}
ActivityStatus::Failed | ActivityStatus::TimedOut => {
// Rejected/timed-out → next iteration or loop failed.
if iteration >= loop_node.max_iterations {
// Max iterations reached → loop failed.
let (wait_resolved_event_id, by, comment, timed_out) =
extract_wait_resolution_meta(snapshot, &gate_id);
return AdvanceDecision {
actions: vec![
OrchestratorAction::FinishLoopIteration {
node_id: loop_id.to_string(),
iteration,
resolution: "rejected".to_string(),
decision_activity_id: Some(gate_id),
wait_resolved_event_id,
by,
comment,
timed_out,
},
OrchestratorAction::FinishLoop {
node_id: loop_id.to_string(),
final_iteration: iteration,
resolution: "failed".to_string(),
output_ref: None,
error_code: Some("MaxIterationsReached".to_string()),
error_class: Some("fatal".to_string()),
},
],
is_succeeded: false,
is_failed: false,
};
}
// Start next iteration.
let (wait_resolved_event_id, by, comment, timed_out) =
extract_wait_resolution_meta(snapshot, &gate_id);
return AdvanceDecision {
actions: vec![
OrchestratorAction::FinishLoopIteration {
node_id: loop_id.to_string(),
iteration,
resolution: "rejected".to_string(),
decision_activity_id: Some(gate_id),
wait_resolved_event_id,
by,
comment,
timed_out,
},
OrchestratorAction::StartLoopIteration {
node_id: loop_id.to_string(),
iteration: iteration + 1,
},
],
is_succeeded: false,
is_failed: false,
};
}
_ => {
// Gate is in progress (Waiting, etc.).
return AdvanceDecision {
actions: vec![],
is_succeeded: false,
is_failed: false,
};
}
}
}
_ => {
// Terminate node must be Decision type. Skip for now
// (full validation in Task 8.3).
continue;
}
}
} else {
// ── Regular body node (subagent / hostExecutor) ──
// Process gate if required.
if let Some(human_gate) = node_human_gate(node) {
let gate_id = loop_gate_activity_id(run_id, loop_id, iteration, node_id);
let Some(gate) = activity_state(snapshot, &gate_id) else {
return AdvanceDecision {
actions: vec![OrchestratorAction::DispatchGate {
node_id: node_id.clone(),
activity_id: gate_id,
human_gate: human_gate.clone(),
}],
is_succeeded: false,
is_failed: false,
};
};
match gate.status {
ActivityStatus::Failed | ActivityStatus::TimedOut => {
// Gate failed → body node failed → loop failed.
return AdvanceDecision {
actions: vec![
OrchestratorAction::FinishLoopIteration {
node_id: loop_id.to_string(),
iteration,
resolution: "failed".to_string(),
decision_activity_id: None,
wait_resolved_event_id: None,
by: None,
comment: None,
timed_out: None,
},
OrchestratorAction::FinishLoop {
node_id: loop_id.to_string(),
final_iteration: iteration,
resolution: "failed".to_string(),
output_ref: None,
error_code: Some("BodyNodeGateFailed".to_string()),
error_class: Some("fatal".to_string()),
},
],
is_succeeded: false,
is_failed: false,
};
}
ActivityStatus::Succeeded => {
// Gate passed, proceed to work.
}
_ => {
return AdvanceDecision {
actions: vec![],
is_succeeded: false,
is_failed: false,
};
}
}
}
// Dispatch / check work activity.
let work_id = loop_work_activity_id(run_id, loop_id, iteration, node_id);
let Some(work) = activity_state(snapshot, &work_id) else {
return AdvanceDecision {
actions: vec![OrchestratorAction::DispatchWork {
node_id: node_id.clone(),
activity_id: work_id,
node: node.clone(),
}],
is_succeeded: false,
is_failed: false,
};
};
match work.status {
ActivityStatus::Succeeded => {
// Body node done → continue to next.
continue;
}
ActivityStatus::Failed | ActivityStatus::TimedOut => {
// Body node failed → loop failed.
return AdvanceDecision {
actions: vec![
OrchestratorAction::FinishLoopIteration {
node_id: loop_id.to_string(),
iteration,
resolution: "failed".to_string(),
decision_activity_id: None,
wait_resolved_event_id: None,
by: None,
comment: None,
timed_out: None,
},
OrchestratorAction::FinishLoop {
node_id: loop_id.to_string(),
final_iteration: iteration,
resolution: "failed".to_string(),
output_ref: None,
error_code: Some("BodyNodeFailed".to_string()),
error_class: Some("fatal".to_string()),
},
],
is_succeeded: false,
is_failed: false,
};
}
_ => {
// Work in progress.
return AdvanceDecision {
actions: vec![],
is_succeeded: false,
is_failed: false,
};
}
}
}
}
// All body nodes done — nothing actionable right now.
AdvanceDecision {
actions: vec![],
is_succeeded: false,
is_failed: false,
}
}