rhei-cli 0.1.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
/// Flags that control standalone execution behavior for `rhei run`.
#[derive(Args, Clone, Debug, Default)]
#[command(next_help_heading = "Standalone Execution")]
struct StandaloneExecutionFlags {
    /// Show what transitions would be made without executing them
    #[arg(long)]
    dry_run: bool,
    /// Skip execution of on_leave/on_enter callbacks
    #[arg(long)]
    no_callbacks: bool,
    /// Continue to the next task when an agent exits non-zero
    #[arg(long)]
    continue_on_error: bool,
    /// Maximum number of agents to run concurrently (0 = unlimited)
    #[arg(long, default_value_t = 1, add = ArgValueCompleter::new(complete_parallel))]
    parallel: usize,
    /// Narrow to the named rhei (repeatable; one id per flag). A rhei id
    /// is its file stem or directory name; default is the whole project
    #[arg(long = "rhei", value_name = "RHEI_ID", add = ArgValueCompleter::new(complete_rhei_id))]
    rhei: Vec<String>,
    /// Force TUI mode even when stdout is not detected as a TTY
    #[arg(long, conflicts_with = "no_tui")]
    tui: bool,
    /// Force plain stdout output even when stdout is a TTY
    #[arg(long)]
    no_tui: bool,
    /// Serve a loopback browser dashboard for this run
    #[arg(long, conflicts_with = "no_dashboard")]
    dashboard: bool,
    /// Disable the loopback browser dashboard
    #[arg(long)]
    no_dashboard: bool,
}

/// Flags that control agent-specific behavior for `rhei run`.
#[derive(Args, Clone, Debug, Default)]
#[command(next_help_heading = "Agent Execution")]
struct AgentExecutionFlags {
    /// Disable agent spawning; use callback-only advancement
    #[arg(long)]
    no_agent: bool,
    /// Override the agent for this run
    #[arg(long, value_name = "AGENT", add = ArgValueCompleter::new(complete_agent_name))]
    agent: Option<String>,
    /// Override the agent mode (named flag set) for this run
    #[arg(long, value_name = "MODE", add = ArgValueCompleter::new(complete_agent_mode))]
    agent_mode: Option<String>,
    /// Override the model for this run
    #[arg(long, value_name = "MODEL", add = ArgValueCompleter::new(complete_model_name))]
    model: Option<String>,
}

/// Flags that control program-specific behavior for `rhei run`.
#[derive(Args, Clone, Debug, Default)]
#[command(next_help_heading = "Program Execution")]
struct ProgramExecutionFlags {
    /// Disable program spawning; use callback-only advancement for program states
    #[arg(long)]
    no_program: bool,
    /// Override the program timeout for this run
    #[arg(long, value_name = "DURATION", add = ArgValueCompleter::new(complete_duration))]
    program_timeout: Option<String>,
}

/// Flags that control snapshot inheritance overrides for `rhei run`.
///
/// §FS-rhei-run.2.3 §FS-rhei-snapshot-operations.2: Snapshot run flags.
#[derive(Args, Clone, Debug, Default)]
#[command(next_help_heading = "Snapshots")]
struct SnapshotExecutionFlags {
    /// Override the concrete source snapshot selected by an authored
    /// `snapshot.inherit:` after that state's constraints are applied.
    #[arg(long, value_name = "REF")]
    from_snapshot: Option<String>,
    /// Explicitly bypass authored source-selection and compatibility
    /// constraints for an ad-hoc debug run. Requires `--from-snapshot`.
    #[arg(long, requires = "from_snapshot")]
    override_inherit: bool,
    /// Select the task for an ambiguous snapshot override.
    #[arg(long = "task", value_name = "TASK_ID", add = ArgValueCompleter::new(complete_task_id))]
    snapshot_task: Option<String>,
    /// Select the fanout target for an ambiguous snapshot override.
    #[arg(long = "target", value_name = "SLUG")]
    snapshot_target: Option<String>,
}

/// Options for the `run` command.
struct RunOptions {
    standalone: StandaloneExecutionFlags,
    agent: AgentExecutionFlags,
    program: ProgramExecutionFlags,
    snapshot: SnapshotExecutionFlags,
}

impl RunOptions {
    fn dry_run(&self) -> bool {
        self.standalone.dry_run
    }

    fn no_callbacks(&self) -> bool {
        self.standalone.no_callbacks
    }

    fn continue_on_error(&self) -> bool {
        self.standalone.continue_on_error
    }

    fn parallel(&self) -> usize {
        self.standalone.parallel
    }

    /// Rhei ids this invocation is narrowed to; empty means the whole project.
    /// §FS-rhei-panta.6
    fn rhei_scope(&self) -> &[String] {
        &self.standalone.rhei
    }

    /// Adopt the scope implied by the resolved target — the rhei a member-plan
    /// path pointed at — when `--rhei` did not already set one. §FS-rhei-panta.6
    fn narrow_to(&mut self, scope: Vec<String>) {
        self.standalone.rhei = scope;
    }

    fn frontend_kind(&self) -> rhei_tui::FrontendKind {
        if self.standalone.tui {
            rhei_tui::FrontendKind::Tui
        } else if self.standalone.no_tui {
            rhei_tui::FrontendKind::Stdout
        } else {
            rhei_tui::FrontendKind::Auto
        }
    }

    fn dashboard_enabled(&self, frontend_is_tui: bool) -> bool {
        if self.standalone.dashboard {
            true
        } else if self.standalone.no_dashboard {
            false
        } else {
            frontend_is_tui
        }
    }

    fn no_agent(&self) -> bool {
        self.agent.no_agent
    }

    fn agent_override(&self) -> Option<&str> {
        self.agent.agent.as_deref()
    }

    fn agent_mode_override(&self) -> Option<&str> {
        self.agent.agent_mode.as_deref()
    }

    fn model_override(&self) -> Option<&str> {
        self.agent.model.as_deref()
    }

    fn no_program(&self) -> bool {
        self.program.no_program
    }

    fn program_timeout_override(&self) -> Option<&str> {
        self.program.program_timeout.as_deref()
    }

    fn snapshot_override_ref(&self) -> Option<&str> {
        self.snapshot.from_snapshot.as_deref()
    }

    fn override_inherit(&self) -> bool {
        self.snapshot.override_inherit
    }

    fn snapshot_task_selector(&self) -> Option<&str> {
        self.snapshot.snapshot_task.as_deref()
    }

    fn snapshot_target_selector(&self) -> Option<&str> {
        self.snapshot.snapshot_target.as_deref()
    }
}

struct ActiveRunFrontend {
    sink: Arc<dyn rhei_tui::EventSink>,
    /// True when an interactive TUI is the active frontend. The run loop uses
    /// this to keep itself alive while a human gate is pending, so the operator
    /// can resolve the gate in the UI and have the run continue (§FS-rhei-run-tui.1.5.5).
    is_tui: bool,
    dashboard: Option<Arc<rhei_tui::DashboardSink>>,
    /// Accumulates per-task driver/duration for the end-of-run console summary.
    /// §FS-rhei-run-report.3
    summary: Arc<SummarySink>,
    /// The intervene registry, present only when the dashboard is live. The run
    /// loop registers each running agent's stdin here so `/intervene` can reach
    /// it. AR §7.
    intervene: Option<Arc<RunInterveneSink>>,
    _frontend: Option<rhei_tui::Frontend>,
}

struct RunGateTransitionSink {
    input: PathBuf,
    machines: ExecutionMachines,
    no_callbacks: bool,
}

impl RunGateTransitionSink {
    fn new(input: PathBuf, machines: ExecutionMachines, no_callbacks: bool) -> Self {
        Self { input, machines, no_callbacks }
    }
}

impl rhei_tui::GateTransitionSink for RunGateTransitionSink {
    fn transition_gate(
        &self,
        task_id: &str,
        from: &str,
        to: &str,
        result: Option<&str>,
    ) -> Result<String, String> {
        // A gate decision lands on one ticket: its own machine and callback
        // base execute the human transition. §DA-per-rhei-state-machines
        transition_dashboard_gate(
            &self.input,
            self.machines.for_task_str(task_id),
            self.machines.callbacks_for_str(task_id),
            task_id,
            from,
            to,
            result,
            self.no_callbacks,
        )
        .map_err(|err| err.to_string())
    }
}

impl ActiveRunFrontend {
    fn announce_dashboard(&self) {
        if let Some(dashboard) = &self.dashboard {
            self.sink.emit(rhei_tui::RunEvent::RunLink {
                label: "Dashboard".to_string(),
                url: dashboard.url().to_string(),
            });
        }
    }

    fn write_frozen_dashboard(&self) {
        let Some(dashboard) = &self.dashboard else {
            return;
        };
        match dashboard.write_frozen_dashboard() {
            Ok(path) => self.sink.emit(rhei_tui::RunEvent::Message {
                level: rhei_tui::MessageLevel::Info,
                text: format!("Final dashboard: {}", path.display()),
            }),
            Err(err) => self.sink.emit(rhei_tui::RunEvent::Message {
                level: rhei_tui::MessageLevel::Warn,
                text: format!("warning: could not write final dashboard: {err}"),
            }),
        }
    }
}

fn start_run_frontend(
    workspace_root: &Path,
    plan_input: &Path,
    machines: &ExecutionMachines,
    opts: &RunOptions,
    parallel: u16,
    total_tasks: usize,
) -> ActiveRunFrontend {
    if opts.dry_run() {
        return ActiveRunFrontend {
            sink: Arc::new(rhei_tui::StdoutSink::new()),
            is_tui: false,
            dashboard: None,
            summary: Arc::new(SummarySink::new()),
            intervene: None,
            _frontend: None,
        };
    }

    // The loader re-reads the plan and builds the full `VizModel` via `rhei-viz`,
    // so the TUI render thread and dashboard share one run model and the same
    // intervene/gate boundaries; neither parses plans itself. §FS-rhei-run-tui.1.5
    let plan_path = plan_input.to_path_buf();
    let loader_machines = machines.set.clone();
    let loader: rhei_tui::PlanLoader =
        Arc::new(move || load_plan_for_dashboard(&plan_path, &loader_machines));
    // AR §7: the intervene registry the run loop registers agents into.
    let registry = Arc::new(RunInterveneSink::new(workspace_root.join("runtime")));
    let gate = Arc::new(RunGateTransitionSink::new(
        plan_input.to_path_buf(),
        machines.clone(),
        opts.no_callbacks(),
    ));

    let tui_context = rhei_tui::TuiContext {
        workspace: workspace_root.to_path_buf(),
        plan_loader: Some(loader.clone()),
        intervene: Some(registry.clone() as Arc<dyn rhei_tui::InterveneSink>),
        gate: Some(gate.clone() as Arc<dyn rhei_tui::GateTransitionSink>),
    };
    let frontend = rhei_tui::select_frontend(
        workspace_root,
        opts.frontend_kind(),
        parallel,
        total_tasks,
        tui_context,
    );

    let dashboard = if opts.dashboard_enabled(frontend.is_tui) {
        match rhei_tui::DashboardSink::start_with_plan_intervene_and_gate(
            workspace_root.to_path_buf(),
            parallel,
            total_tasks,
            Some(loader.clone()),
            Some(registry.clone() as Arc<dyn rhei_tui::InterveneSink>),
            Some(gate.clone() as Arc<dyn rhei_tui::GateTransitionSink>),
        ) {
            Ok(sink) => Some(Arc::new(sink)),
            Err(err) => {
                frontend.sink.emit(rhei_tui::RunEvent::Message {
                    level: rhei_tui::MessageLevel::Warn,
                    text: format!("warning: could not start dashboard: {err}"),
                });
                None
            }
        }
    } else {
        None
    };

    // The run loop registers running agents' stdin into the registry so both the
    // TUI composer and the dashboard `/intervene` can reach them. Wire it
    // whenever a live surface is present.
    let intervene: Option<Arc<RunInterveneSink>> =
        (frontend.is_tui || dashboard.is_some()).then(|| registry.clone());

    // The summary sink is always teed in so the end-of-run console summary can
    // render per-task driver/duration regardless of dashboard state.
    // §FS-rhei-run-report.3
    let summary = Arc::new(SummarySink::new());
    let mut inner: Vec<Arc<dyn rhei_tui::EventSink>> = vec![frontend.sink.clone(), summary.clone()];
    if let Some(dashboard) = &dashboard {
        inner.push(dashboard.clone());
    }
    let sink: Arc<dyn rhei_tui::EventSink> = Arc::new(rhei_tui::Tee::new(inner));

    let is_tui = frontend.is_tui;
    ActiveRunFrontend { sink, is_tui, dashboard, summary, intervene, _frontend: Some(frontend) }
}

#[allow(clippy::too_many_arguments)]
fn transition_dashboard_gate(
    input: &Path,
    machine: &rhei_validator::StateMachine,
    callback_paths: &CallbackPaths,
    task_id_str: &str,
    from: &str,
    to: &str,
    result: Option<&str>,
    no_callbacks: bool,
) -> MietteResult<String> {
    let loaded = load_plan(input)?;
    let task = find_task_by_id_str(&loaded.rhei.tasks, task_id_str)
        .ok_or_else(|| {
            miette!(
                help = format!(
                    "list the task ids in this plan with: rhei list {}",
                    shell_quote(&input.display().to_string())
                ),
                "task '{}' not found in the plan",
                task_id_str
            )
        })?;
    let current_state = normalized_state_name(task.state.as_str(), machine);
    if current_state != from {
        return Err(miette!(
            help = format!(
                "someone moved the task since you looked. Re-read its current state with: \
                 rhei list {}",
                shell_quote(&input.display().to_string())
            ),
            "conflict: Task {} is in state '{}', expected '{}'",
            task_id_str,
            task.state,
            from
        ));
    }
    if !machine.states.get(&current_state).map(|def| def.gating).unwrap_or(false) {
        return Err(miette!(
            help = "only human-gate states are released this way. Advance a non-gating state \
                    with `rhei transition` or let `rhei run` drive it. See which states gate \
                    with: rhei states",
            "Task {} is in state '{}', which is not a gating state",
            task_id_str,
            current_state
        ));
    }
    let explicit_transition =
        machine.transitions().iter().any(|rule| rule.from.0 == from && rule.to.0 == to);
    if !explicit_transition {
        return Err(miette!(
            help = format!(
                "the state machine declares no '{from}' -> '{to}' edge. List the edges \
                 leaving '{from}' with: rhei states"
            ),
            "transition from '{}' to '{}' is not an explicit human-gate transition",
            from,
            to
        ));
    }

    // The operator's account rides the move, as `transition --result` does; blank
    // is none, and the shared path refuses a terminal release with none.
    // §FS-rhei-viz.5.1 §FS-rhei-run.3 §FS-rhei-states.3.3
    let result = result.map(str::trim).filter(|message| !message.is_empty());
    let route = loaded.task_route(task_id_str, input);
    execute_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,
        from,
        to,
        result,
        no_callbacks,
    )
}

/// Re-read the plan from disk and build the dashboard's [`VizModel`] via
/// `rhei-viz` (flatten the resolved machine, derive plan state, classify).
/// Called on every `/snapshot` request, so failures must be non-fatal — return
/// `None` and let the dashboard fall back to the last good model. AR §5.2.
fn load_plan_for_dashboard(
    plan_path: &Path,
    machines: &rhei_validator::MachineSet,
) -> Option<rhei_viz_model::VizModel> {
    let loaded = load_plan(plan_path).ok()?;
    // Any directory input — workspace or Panta project — is its own execution
    // root; per-task roots route each ticket's history to its owning rhei,
    // which is where a project run writes its ledgers. §AR-rhei-panta.5
    let default_root = execution_workspace_root(plan_path);
    Some(rhei_viz::build_set_with_history_roots(
        &loaded.rhei,
        machines,
        &default_root,
        &loaded.task_roots,
    ))
}

impl
    From<(
        StandaloneExecutionFlags,
        AgentExecutionFlags,
        ProgramExecutionFlags,
        SnapshotExecutionFlags,
    )> for RunOptions
{
    fn from(
        (standalone, agent, program, snapshot): (
            StandaloneExecutionFlags,
            AgentExecutionFlags,
            ProgramExecutionFlags,
            SnapshotExecutionFlags,
        ),
    ) -> Self {
        Self { standalone, agent, program, snapshot }
    }
}