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
// Running this pass's programs one after another, the way a run with a single
// worker does it: spawn each, wait for it, and route the ticket on the exit
// code, the outputs it owes, or the timeout it hit.
//
// Its own part because a program in the worker pool is spawned and completed by
// the parts next door; only the single-worker path runs one inline and owns the
// whole of it, from the slot events to the transition it fires.
// §AR-source-file-size.3 §FS-rhei-run.3
/// Runs every program work item this pass claimed, in order.
///
/// An interrupt stops the loop where it is: the programs not yet started stay
/// unstarted, and the ones that ran keep the state they were worked in.
// §FS-rhei-run.3.2
#[allow(clippy::too_many_arguments)]
fn run_sequential_program_work_items(
program_tasks: &[(String, String, String, ResolvedProgram)],
plan_title: &str,
input: &Path,
machines: &ExecutionMachines,
opts: &RunOptions,
workspace_root: &Path,
runtime_dir: &Path,
sink: &Arc<dyn rhei_tui::EventSink>,
progress: &mut AgentPassProgress<'_>,
) -> MietteResult<()> {
use rhei_tui::{MessageLevel, RunEvent};
use std::time::{Instant as TuiInstant, SystemTime};
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)*); }; }
for (task_id_str, _current_state_raw, current_state, resolved) in program_tasks {
// The pass collected every ready program before the interrupt;
// the ones not yet started stay unstarted. §FS-rhei-run.3.2
if interrupt_requested() {
break;
}
let loaded = load_plan(input)?;
let target_id = parse_task_id(task_id_str);
let machine = machines.for_task_str(task_id_str);
let callback_paths = machines.callbacks_for_str(task_id_str);
let task = find_task_by_id(&loaded.rhei.tasks, &target_id);
let Some(task) = task else { continue };
// §FS-rhei-panta.6.2: programs run against the owning rhei's root.
let task_workspace_root = loaded.task_root(task_id_str, workspace_root);
let render_context = RuntimeTemplateContext {
workspace_root: &task_workspace_root,
task_roots: Some(&loaded.task_roots),
plan_tasks: Some(&loaded.rhei.tasks),
checkout_root: &task_workspace_root,
plan_path: &callback_paths.plan_path,
state_machine_path: callback_paths.state_machine_path.as_deref(),
plan_title,
task,
state_name: current_state,
current_state_raw: task.state.as_str(),
machine,
metadata: loaded.rhei.metadata.as_ref(),
target: None,
model: None,
model_provider: None,
model_name: None,
agent: None,
agent_mode: None,
tooling: None,
memory: None,
};
let log = program_log_path(runtime_dir, task_id_str, current_state);
run_info!("\nSpawning program for Task {}: {}", task_id_str, task.title);
run_info!(" Log: {}", log.display());
let started_at = std::time::Instant::now();
let started_wall = std::time::SystemTime::now();
sink.emit(RunEvent::SlotAssigned {
slot: 0,
task: task_id_str.clone(),
from: task.state.as_str().to_string(),
to: current_state.clone(),
agent: None,
template_context: None,
log_path: log.clone(),
started_at,
wall_clock: started_wall,
});
let spawn_result =
spawn_and_wait_program(resolved, &render_context, &log, sink);
let duration_ms = started_at.elapsed().as_millis() as u64;
let finished_wall = SystemTime::now();
let (outcome, exit_code) = slot_outcome(&spawn_result);
sink.emit(RunEvent::SlotReleased {
slot: 0,
task: task_id_str.clone(),
from: task.state.as_str().to_string(),
to: current_state.clone(),
log_path: log.clone(),
outcome,
finished_at: TuiInstant::now(),
wall_clock: finished_wall,
exit_code,
duration_ms,
});
match spawn_result {
// §FS-rhei-run.3.2: interrupted, so no transition fires.
Ok(program_outcome) if program_outcome.interrupted => {
*progress.programs_spawned += 1;
run_warn!(
"{}",
interrupted_task_warning(task_id_str, current_state, Some(&log))
);
}
Ok(program_outcome) => {
*progress.programs_spawned += 1;
let mut reloaded = load_plan(input)?;
let task_after = find_task_by_id(&reloaded.rhei.tasks, &target_id);
let mut state_after =
task_after.map(|t| t.state.as_str()).unwrap_or("unknown").to_string();
if normalized_state_name(&state_after, machine)
!= normalized_state_name(current_state, machine)
{
run_info!(
" Task {} advanced: '{}' -> '{}'",
task_id_str,
current_state,
state_after
);
*progress.advanced_any = true;
continue;
}
if program_outcome.timed_out {
match fire_timeout_transition(
input,
machines,
task_id_str,
current_state,
program_outcome.timeout_secs,
opts.no_callbacks(),
) {
TimeoutTransitionOutcome::Fired => {}
TimeoutTransitionOutcome::NoRule => {
run_warn!(
" warning: program for task {} timed out from '{}' but no timeout transition is declared; task remains in state",
task_id_str,
current_state
);
}
TimeoutTransitionOutcome::Failed => {}
}
reloaded = load_plan(input)?;
state_after = reloaded
.rhei
.tasks
.iter()
.find(|t| t.id == target_id)
.map(|t| t.state.as_str())
.unwrap_or("unknown")
.to_string();
if normalized_state_name(&state_after, machine)
!= normalized_state_name(current_state, machine)
{
run_info!(
" Task {} advanced: '{}' -> '{}'",
task_id_str,
current_state,
state_after
);
*progress.advanced_any = true;
continue;
}
// Timed out and did not move: out of this pass.
// §FS-rhei-run.3
progress.stalled_tasks.insert(task_id_str.clone());
continue;
}
let exit_code = program_outcome.status.code().unwrap_or(-1);
if let Some(to_state) = find_program_exit_transition(
machine,
loaded.rhei.metadata.as_ref(),
task,
current_state,
exit_code,
)? {
if exit_code == 0 && to_state != *current_state {
let missing_required_outputs = collect_missing_required_outputs(
workspace_root,
&reloaded.task_root(task_id_str, workspace_root),
machine,
reloaded.rhei.metadata.as_ref(),
task_after.unwrap_or(task),
current_state,
Some(to_state.as_str()),
);
if !missing_required_outputs.is_empty() {
// A program is a worker: its stall reaches
// the report as the artifacts it owes.
// §FS-rhei-run-report.3.1
emit_exit_zero_missing_required_outputs_warning(
"program",
task_id_str,
current_state,
&missing_required_outputs,
sink,
);
progress.stalled_tasks.insert(task_id_str.clone());
continue;
}
}
if record_poll_self_loop_if_needed(
&loaded,
input,
machine,
task,
current_state,
&to_state,
)? {
run_info!(
" Task {} poll self-loop scheduled next attempt from '{}'",
task_id_str,
current_state
);
*progress.advanced_any = true;
continue;
}
let route = loaded.task_route(task_id_str, input);
let effective_to = execute_system_program_exit_transition(
TransitionFiles {
task_file: &route.task_file,
metadata_file: &route.metadata_file,
metadata_id: &route.metadata_id,
artifact_root: &route.execution_root,
artifact_id: task_id_str,
},
callback_paths,
machine,
&route.local_id,
current_state,
&to_state,
exit_code,
opts.no_callbacks(),
)?;
run_info!(
" Task {} advanced: '{}' -> '{}'",
task_id_str,
current_state,
effective_to
);
*progress.advanced_any = true;
} else if program_outcome.status.success() {
run_warn!(
" warning: program exited 0 but task {} did not advance from '{}'",
task_id_str,
current_state
);
progress.stalled_tasks.insert(task_id_str.clone());
} else {
run_error!(
" error: program exited with code {} for task {}",
exit_code,
task_id_str
);
if !opts.continue_on_error() {
return Err(miette!(
help = program_state_failed_help(),
"program exited with code {} for Task {}. Use --continue-on-error to skip failures.",
exit_code,
task_id_str
));
}
progress.stalled_tasks.insert(task_id_str.clone());
}
}
Err(err) => {
run_error!(" error: {}", err);
if !opts.continue_on_error() {
return Err(err);
}
progress.stalled_tasks.insert(task_id_str.clone());
}
}
}
Ok(())
}