rhei-cli 0.2.0

Command-line driver for the Rhei agent runtime.
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
// What a finished parallel agent's exit means for its ticket: whether it met
// the completion condition, which snapshots the outcome emits, and which edge —
// advance, auto-advance, timeout, or exit code — the run fires next.
//
// Its own part because the decision is made from the completion alone: it does
// not touch slots, the channel, or the refill next door, and a ticket that
// stalls here ends its own turn rather than the pass.

// §AR-source-file-size.3 §FS-rhei-run.3 §FS-rhei-agents.3.2

#[allow(clippy::too_many_arguments)]
fn handle_parallel_agent_exit(
    exit: ParallelAgentExit,
    input: &Path,
    machines: &ExecutionMachines,
    settings: &RheiSettings,
    opts: &RunOptions,
    workspace_root: &Path,
    sink: &Arc<dyn rhei_tui::EventSink>,
    active_invocation_counts: &HashMap<String, usize>,
    progress: &mut AgentPassProgress<'_>,
) -> MietteResult<()> {
    use rhei_tui::MessageLevel;
    macro_rules! run_message { ($level:expr, $($arg:tt)*) => {{ emit_run_message(sink, $level, format!($($arg)*)); }}; }
    macro_rules! run_info { ($($arg:tt)*) => { run_message!(MessageLevel::Info, $($arg)*); }; }
    macro_rules! run_warn { ($($arg:tt)*) => { run_message!(MessageLevel::Warn, $($arg)*); }; }
    macro_rules! run_error { ($($arg:tt)*) => { run_message!(MessageLevel::Error, $($arg)*); }; }

    let ParallelAgentExit {
        task_id_str,
        state_name,
        resolved,
        log,
        snapshot_preload,
        visit_count,
        accounting_recorded,
        outcome,
    } = exit;
    let AgentSpawnOutcome { status, timed_out, timeout_secs, .. } = outcome;
    // The completed ticket's own machine drives its post-exit
    // handling; callbacks resolve inside each helper from the
    // same set. §DA-per-rhei-state-machines
    let machine = machines.for_task_str(&task_id_str);
    *progress.agents_spawned += 1;
    let target_id = parse_task_id(&task_id_str);
    let reloaded = load_plan(input)?;
    if accounting_recorded {
        if let Err(err) =
            regenerate_accounting_indexes(workspace_root, &reloaded.rhei)
        {
            run_warn!(
                "  warning: failed to update accounting rollups: {}",
                err
            );
        }
    }
    let task_after = find_task_by_id(&reloaded.rhei.tasks, &target_id);
    let mut missing_required_outputs = Vec::new();
    let mut snapshot_completion_for_emit = None;
    let mut failure_selected_to_state = None;
    // Hoisted out of the block below so the pending-invocation
    // check can ask the same question about the same edge.
    // §FS-rhei-agents.3.2
    let mut selected_to: Option<String> = None;
    if let (Some(task_for_snapshot), Some(state_def)) =
        (task_after, machine.states.get(state_name.as_str()))
    {
        // §FS-rhei-agents.3.2: the completion condition is
        // exit 0 + declared outputs + the terminal result
        // when the edge this exit selects is terminal.
        selected_to = selected_forward_transition(
            &reloaded.rhei,
            machine,
            task_for_snapshot,
        );
        let outputs_ok = status.success()
            && state_outputs_exist_for_resolved_invocation(
                workspace_root,
                task_for_snapshot,
                &state_name,
                &state_name,
                machine,
                reloaded.rhei.metadata.as_ref(),
                state_def,
                &resolved,
            )
            && missing_terminal_result_output(
                &reloaded.task_root(&task_id_str, workspace_root),
                machine,
                task_for_snapshot,
                selected_to.as_deref(),
                // A fanned-out invocation answers for its
                // own fragment. §FS-rhei-states.3.3
                ResultInvocation {
                    state: &state_name,
                    visit_count,
                    identity: fanout_result_identity(
                        Some(state_def),
                        resolved.target.as_ref(),
                        resolved.model.as_deref(),
                    )
                    .as_deref(),
                },
            )
            .is_none();
        if status.success() && !outputs_ok {
            missing_required_outputs =
                collect_missing_required_outputs_for_resolved_invocation(
                    workspace_root,
                    &reloaded.task_root(&task_id_str, workspace_root),
                    machine,
                    reloaded.rhei.metadata.as_ref(),
                    task_for_snapshot,
                    &state_name,
                    selected_to.as_deref(),
                    &resolved,
                );
        }
        let snapshot_completion = if timed_out {
            SnapshotCompletion::Timeout
        } else if outputs_ok {
            SnapshotCompletion::Success
        } else {
            SnapshotCompletion::Failure
        };
        failure_selected_to_state = if timed_out {
            find_timeout_transition(machine, &state_name)
        } else if !status.success() {
            find_program_exit_transition(
                machine,
                reloaded.rhei.metadata.as_ref(),
                task_for_snapshot,
                &state_name,
                status.code().unwrap_or(-1),
            )?
        } else {
            None
        };
        if !status.success() {
            if let Err(err) = emit_snapshots_after_agent_exit(
                workspace_root,
                machine,
                settings,
                task_for_snapshot,
                &state_name,
                failure_selected_to_state.as_deref(),
                &resolved,
                &log,
                visit_count,
                snapshot_completion,
                &snapshot_preload,
            ) {
                run_error!("  error: {}", err);
                if !opts.continue_on_error() {
                    return Err(err);
                }
            }
        }
        snapshot_completion_for_emit = Some(snapshot_completion);
    }
    let state_after = task_after.map(|t| t.state.as_str()).unwrap_or("unknown");
    if normalized_state_name(state_after, machine)
        != normalized_state_name(&state_name, machine)
    {
        if status.success() {
            if let (Some(task_for_snapshot), Some(snapshot_completion)) =
                (task_after, snapshot_completion_for_emit)
            {
                if let Err(err) = emit_snapshots_after_agent_exit(
                    workspace_root,
                    machine,
                    settings,
                    task_for_snapshot,
                    &state_name,
                    Some(state_after),
                    &resolved,
                    &log,
                    visit_count,
                    snapshot_completion,
                    &snapshot_preload,
                ) {
                    run_error!("  error: {}", err);
                    if !opts.continue_on_error() {
                        return Err(err);
                    }
                }
            }
        }
        run_info!(
            "  Task {} advanced: '{}' -> '{}'",
            task_id_str,
            state_name,
            state_after
        );
        *progress.advanced_any = true;
    } else if status.success() {
        // Every exit falls through to the refill below: a
        // `continue` left the freed slot idle all pass.
        // §FS-rhei-run.3
        'exit_zero: {
            if !missing_required_outputs.is_empty() {
                if let (
                    Some(task_for_snapshot),
                    Some(snapshot_completion),
                ) = (task_after, snapshot_completion_for_emit)
                {
                    if let Err(err) = emit_snapshots_after_agent_exit(
                        workspace_root,
                        machine,
                        settings,
                        task_for_snapshot,
                        &state_name,
                        None,
                        &resolved,
                        &log,
                        visit_count,
                        snapshot_completion,
                        &snapshot_preload,
                    ) {
                        run_error!("  error: {}", err);
                        if !opts.continue_on_error() {
                            return Err(err);
                        }
                    }
                }
                emit_exit_zero_missing_required_outputs_warning(
                    "agent",
                    &task_id_str,
                    &state_name,
                    &missing_required_outputs,
                    sink,
                );
                progress.stalled_tasks.insert(task_id_str.clone());
                break 'exit_zero;
            }
            // A sibling invocation is still running: the
            // state is not finished, and advancing now
            // strands it. §FS-rhei-states.3.3
            let sibling_in_flight =
                active_invocation_counts.contains_key(&task_id_str);
            let pending_more = sibling_in_flight
                || reloaded
                    .rhei
                    .tasks
                    .iter()
                    .find(|t| t.id == target_id)
                    .and_then(|task| {
                        machine.states.get(state_name.as_str()).map(
                            |state_def| {
                                task_has_pending_agent_invocations(
                                    workspace_root,
                                    &reloaded
                                        .task_root(&task_id_str, workspace_root),
                                    task,
                                    &state_name,
                                    task.state.as_str(),
                                    machine,
                                    reloaded.rhei.metadata.as_ref(),
                                    state_def,
                                    settings,
                                    selected_to.as_deref(),
                                )
                            },
                        )
                    })
                    .transpose()?
                    .unwrap_or(false);
            if pending_more {
                if let (
                    Some(task_for_snapshot),
                    Some(snapshot_completion),
                ) = (task_after, snapshot_completion_for_emit)
                {
                    if let Err(err) = emit_snapshots_after_agent_exit(
                        workspace_root,
                        machine,
                        settings,
                        task_for_snapshot,
                        &state_name,
                        None,
                        &resolved,
                        &log,
                        visit_count,
                        snapshot_completion,
                        &snapshot_preload,
                    ) {
                        run_error!("  error: {}", err);
                        if !opts.continue_on_error() {
                            return Err(err);
                        }
                    }
                }
                break 'exit_zero;
            }
            let auto_advance_result =
                if let Some(snapshot_completion) = snapshot_completion_for_emit {
                    let mut emit_before_transition =
                        |task_for_snapshot: &rhei_core::ast::Task,
                         to_state: &str|
                         -> MietteResult<()> {
                            emit_snapshots_after_agent_exit(
                                workspace_root,
                                machine,
                                settings,
                                task_for_snapshot,
                                &state_name,
                                Some(to_state),
                                &resolved,
                                &log,
                                visit_count,
                                snapshot_completion,
                                &snapshot_preload,
                            )
                        };
                    try_auto_advance_task(
                        input,
                        machines,
                        &task_id_str,
                        &state_name,
                        opts.no_callbacks(),
                        Some(&mut emit_before_transition),
                    )
                } else {
                    try_auto_advance_task(
                        input,
                        machines,
                        &task_id_str,
                        &state_name,
                        opts.no_callbacks(),
                        None,
                    )
                };
            match auto_advance_result {
                Ok(Some(to_state)) => {
                    run_info!(
                        "  Task {} auto-advanced: '{}' -> '{}'",
                        task_id_str,
                        state_name,
                        to_state
                    );
                    *progress.advanced_any = true;
                }
                Ok(None) => {
                    if let Some(task) =
                        find_task_by_id(&reloaded.rhei.tasks, &target_id)
                    {
                        if let Some(snapshot_completion) =
                            snapshot_completion_for_emit
                        {
                            if let Err(err) = emit_snapshots_after_agent_exit(
                                workspace_root,
                                machine,
                                settings,
                                task,
                                &state_name,
                                None,
                                &resolved,
                                &log,
                                visit_count,
                                snapshot_completion,
                                &snapshot_preload,
                            ) {
                                run_error!("  error: {}", err);
                                if !opts.continue_on_error() {
                                    return Err(err);
                                }
                            }
                        }
                        emit_exit_zero_warnings(
                            workspace_root,
                            &reloaded.task_root(&task_id_str, workspace_root),
                            machine,
                            reloaded.rhei.metadata.as_ref(),
                            task,
                            &task_id_str,
                            &state_name,
                            selected_forward_transition(
                                &reloaded.rhei,
                                machine,
                                task,
                            )
                            .as_deref(),
                            sink,
                        );
                        progress.stalled_tasks.insert(task_id_str.clone());
                    } else {
                        run_warn!(
                            "  warning: agent exited 0 but task {} did not advance from '{}'",
                            task_id_str, state_name
                        );
                    }
                }
                Err(err) => {
                    run_warn!(
                        "  warning: agent exited 0 but task {} could not auto-advance from '{}': {}",
                        task_id_str, state_name, err
                    );
                    // Did not move: without this the refill
                    // re-spawns it, and the error repeats.
                    // §FS-rhei-run.3
                    progress.stalled_tasks.insert(task_id_str.clone());
                }
            }
        }
    } else if timed_out {
        run_warn!(
            "  agent timed out for task {} in '{}'",
            task_id_str,
            state_name
        );
        if let Some(to_state) = failure_selected_to_state.as_deref() {
            match fire_selected_timeout_transition(
                input,
                machines,
                &task_id_str,
                &state_name,
                to_state,
                timeout_secs,
                opts.no_callbacks(),
            ) {
                TimeoutTransitionOutcome::Fired => *progress.advanced_any = true,
                // Did not move: the pool must not re-spawn
                // it from the live ready set this pass.
                // §FS-rhei-run.3
                TimeoutTransitionOutcome::NoRule
                | TimeoutTransitionOutcome::Failed => {
                    progress.stalled_tasks.insert(task_id_str.clone());
                }
            }
        } else {
            {
                run_warn!(
                    "  warning: agent for task {} timed out from '{}' but no timeout transition is declared; task remains in state",
                    task_id_str, state_name
                );
                // §FS-rhei-run.3: a ticket that timed out
                // with nowhere to go would time out again,
                // once per free slot, for the whole pass.
                progress.stalled_tasks.insert(task_id_str.clone());
            }
        }
    } else {
        let code = status.code().unwrap_or(-1);
        run_error!(
            "  error: agent exited with code {} for task {}",
            code,
            task_id_str
        );
        if let Some(to_state) = failure_selected_to_state.as_deref() {
            match fire_agent_exit_transition(
                input,
                machines,
                &task_id_str,
                &state_name,
                to_state,
                code,
                opts.no_callbacks(),
            ) {
                TimeoutTransitionOutcome::Fired => *progress.advanced_any = true,
                // §FS-rhei-run.3: the exit routed nowhere,
                // so the ticket is still ready and would be
                // re-spawned into every slot that frees up.
                TimeoutTransitionOutcome::NoRule
                | TimeoutTransitionOutcome::Failed => {
                    progress.stalled_tasks.insert(task_id_str.clone());
                }
            }
        } else if !opts.continue_on_error() {
            return Err(miette!(
                help = run_report_help(),
                "agent exited with code {code} for Task {task_id_str}. \
                 Use --continue-on-error to skip failures."
            ));
        } else {
            // `--continue-on-error` skips the failure; it
            // must not turn it into an unbounded respawn
            // loop within the pass. §FS-rhei-run.3
            progress.stalled_tasks.insert(task_id_str.clone());
        }
    }

    Ok(())
}