rhei-cli 0.3.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
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
/// Snapshot cache maintenance commands.
#[derive(Subcommand, Debug)]
enum SnapshotCommand {
    /// List cached snapshot generations
    List {
        /// Path to a plan file or workspace root; defaults to the current directory
        #[arg(long, value_name = "RHEI_PLAN", default_value = ".", add = ArgValueCompleter::new(complete_rhei_plan_path))]
        plan: PathBuf,
        /// Filter by task id
        #[arg(long, value_name = "ID", add = ArgValueCompleter::new(complete_task_id))]
        task: Option<String>,
        /// Filter by snapshot name; use _state for auto-emitted snapshots
        #[arg(long, value_name = "SNAPSHOT")]
        name: Option<String>,
        /// Filter by emitting state
        #[arg(long, value_name = "STATE", add = ArgValueCompleter::new(complete_state_name))]
        state: Option<String>,
        /// Filter by emission origin
        #[arg(long, value_enum, default_value = "orchestrator")]
        produced_by: SnapshotProducedByFilter,
        /// Show only snapshots that no longer resolve in the current plan/state machine
        #[arg(long)]
        orphaned: bool,
        /// Output format
        #[arg(long, value_enum, default_value = "text")]
        format: SnapshotListFormat,
    },
    /// Show one snapshot manifest and transcript preview
    Show {
        /// Snapshot reference
        #[arg(value_name = "REF")]
        reference: String,
        /// Path to a plan file or workspace root; defaults to the current directory
        #[arg(long, value_name = "RHEI_PLAN", default_value = ".", add = ArgValueCompleter::new(complete_rhei_plan_path))]
        plan: PathBuf,
    },
    /// Delete cached snapshot generations by policy
    Gc {
        /// Path to a plan file or workspace root; defaults to the current directory
        #[arg(long, value_name = "RHEI_PLAN", default_value = ".", add = ArgValueCompleter::new(complete_rhei_plan_path))]
        plan: PathBuf,
        /// Filter by task id
        #[arg(long, value_name = "ID", add = ArgValueCompleter::new(complete_task_id))]
        task: Option<String>,
        /// Filter by snapshot name
        #[arg(long, value_name = "SNAPSHOT")]
        name: Option<String>,
        /// Delete only generations older than this duration (for example 7d or 4h)
        #[arg(long, value_name = "DURATION")]
        older_than: Option<String>,
        /// Keep the newest N generations per snapshot identity
        #[arg(long, value_name = "N")]
        keep_generations: Option<usize>,
        /// Include operator-produced generations in retention and deletion decisions
        #[arg(long)]
        include_operator: bool,
        /// Delete only snapshots that no longer resolve in the current plan/state machine
        #[arg(long)]
        orphaned: bool,
        /// Print what would be deleted without removing files
        #[arg(long)]
        dry_run: bool,
        /// Bypass the live-run interlock
        #[arg(long)]
        force: bool,
    },
    /// Continue interactively from a cached snapshot
    Continue {
        /// Snapshot reference
        #[arg(value_name = "REF")]
        reference: String,
        /// Path to a plan file or workspace root; defaults to the current directory
        #[arg(long, value_name = "RHEI_PLAN", default_value = ".", add = ArgValueCompleter::new(complete_rhei_plan_path))]
        plan: PathBuf,
        /// Select a target slug when the reference is ambiguous
        #[arg(long, value_name = "SLUG")]
        target: Option<String>,
        /// Continue from a specific generation
        #[arg(long, value_name = "N")]
        generation: Option<u64>,
        /// Do not capture the resulting operator transcript
        #[arg(long)]
        no_capture: bool,
    },
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum SnapshotProducedByFilter {
    Orchestrator,
    Operator,
    All,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum SnapshotListFormat {
    Text,
    Json,
}

/// Output formats supported by the [`Render`](Commands::Render) subcommand.
#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
enum RenderFormat {
    Json,
    Github,
    Progress,
}

/// Supported AI coding agents for skill installation.
#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
enum Agent {
    ClaudeCode,
    Cursor,
    Windsurf,
    Copilot,
    Kilocode,
    Pi,
    Codex,
    Antigravity,
    All,
}

/// Shells supported by the completion generator.
#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
enum CompletionShell {
    Bash,
    Zsh,
    Fish,
    #[value(name = "powershell")]
    PowerShell,
    Elvish,
}

impl CompletionShell {
    fn as_str(self) -> &'static str {
        match self {
            CompletionShell::Bash => "bash",
            CompletionShell::Zsh => "zsh",
            CompletionShell::Fish => "fish",
            CompletionShell::PowerShell => "powershell",
            CompletionShell::Elvish => "elvish",
        }
    }
}

/// Program entry point.
///
/// Delegates to fallible command logic so tests can exercise it directly.
/// Wrap diagnostics at word boundaries but never *inside* a word.
///
/// miette's defaults offer a break opportunity at every hyphen and every `/`,
/// and split an overlong token outright. All three land mid-path on the
/// filesystem diagnostics this CLI prints constantly, and a path broken across
/// lines cannot be copied, clicked, or grepped. Treating only spaces as break
/// points keeps prose wrapping while a long path overflows the wrap column
/// intact, where the terminal soft-wraps it.
fn install_diagnostic_handler() {
    let _ = miette::set_hook(Box::new(|_| {
        Box::new(
            miette::MietteHandlerOpts::new()
                .break_words(false)
                .word_separator(textwrap::WordSeparator::AsciiSpace)
                .word_splitter(textwrap::WordSplitter::NoHyphenation)
                .build(),
        )
    }));
}

/// True when `rhei` was invoked with no arguments at all.
///
/// Distinguishes the orientation case from a subcommand-level usage error;
/// see the call site in [`main`].
fn is_bare_invocation() -> bool {
    std::env::args_os().count() <= 1
}

/// Conventional status for a process that stopped because a pipe consumer
/// closed early: `128 + SIGPIPE`, the same value the shell reports for
/// `yes | head`.
const EXIT_BROKEN_PIPE: i32 = 141;

/// Leave quietly when there is no longer anywhere to print, instead of
/// surfacing an internal error.
///
/// Rust ignores `SIGPIPE` before `main`, so a closed stdout comes back as an
/// `EPIPE` write error and `println!` panics on it — `rhei list | head` exited
/// 101 with a stack trace. This intercepts exactly that panic and exits the way
/// a Unix filter killed by the signal does.
///
/// A terminal that goes away is the same situation with a different errno: a
/// `rhei run` whose window is closed writes `EIO` to the dead pty from then on,
/// and the end-of-run console summary panicked on it — then panicked *again*
/// from the report guard's own `println!` while unwinding, which is a double
/// panic and aborts. A run that ended is not a run that crashed.
///
/// Restoring `SIGPIPE` to `SIG_DFL` process-wide would be the shorter fix and
/// is the wrong one: this CLI writes to pipes it owns — a callback
/// subprocess's stdin, an agent's — and there the write returning `EPIPE` is
/// how a child that exited early gets *reported*. Under `SIG_DFL` those writes
/// killed `rhei` mid-diagnostic instead, so a transition that should have
/// failed with an explanation failed with empty stderr.
// §FS-rhei-usage.2 §FS-rhei-run.3.2 §FS-rhei-run-tui.1.8
fn install_quiet_broken_pipe_exit() {
    // Before any output can be lost, because the question cannot be asked
    // afterwards. §FS-rhei-run.3.2
    record_startup_terminals();
    let previous = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        if is_lost_output_panic(info) {
            // `exit` runs no destructor: the shutdown guard never gets its
            // turn, so the hook is the last code that can end the groups.
            // §FS-rhei-run.3.2
            terminate_all_live_groups();
            // An interrupted run still names its signal: losing the terminal is
            // how the interruption arrived, not a second outcome.
            // §FS-rhei-run.3.2
            let code = interrupt_exit_code().unwrap_or(EXIT_BROKEN_PIPE);
            // The run really is ending, so its registry entry must go with it —
            // otherwise a reader that lost its pipe leaves a run listed as live
            // forever. §FS-rhei-run-headless.2
            finalize_run_descriptor(code);
            std::process::exit(code);
        }
        previous(info);
    }));
}

/// `EPIPE`, by `strerror`'s message and by errno. Both forms because the
/// message follows the locale, while the `(os error N)` suffix the standard
/// library appends does not — either one identifies the errno on its own.
const BROKEN_PIPE_MARKERS: [&str; 2] = ["Broken pipe", "(os error 32)"];

/// `EIO`, in the same two forms.
const IO_ERROR_MARKERS: [&str; 2] = ["Input/output error", "(os error 5)"];

/// Which of the process's own output streams a print failed on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LostStream {
    Stdout,
    Stderr,
}

/// The stream a standard-library "failed printing to …" panic names, or `None`
/// for a panic that is about something else entirely.
fn printing_failure_stream(message: &str) -> Option<LostStream> {
    let rest = message.strip_prefix("failed printing to ")?;
    if rest.starts_with("stdout") {
        Some(LostStream::Stdout)
    } else if rest.starts_with("stderr") {
        Some(LostStream::Stderr)
    } else {
        None
    }
}

/// Whether stdout and stderr were terminals when the process started, asked
/// once and remembered.
///
/// It has to be once, and it has to be then. `isatty` on a pty whose master
/// has closed does not answer "yes, a terminal that has gone away" — the
/// hangup swaps the slave's file operations out and the `TCGETS` behind
/// `isatty` fails with `EIO` like every other ioctl on it, so the stream reads
/// as *not a terminal* from exactly the moment the guard below needs it to
/// read as one. Asked at startup the answer is the true one, and it cannot
/// change afterwards: a redirected stdout does not become a terminal, and a
/// terminal that goes away was still a terminal.
// §FS-rhei-run.3.2: a lost console ends the run quietly.
static STARTUP_TERMINALS: std::sync::OnceLock<(bool, bool)> = std::sync::OnceLock::new();

/// Ask the question while both streams are still whatever they are.
fn record_startup_terminals() -> (bool, bool) {
    *STARTUP_TERMINALS.get_or_init(|| {
        use std::io::IsTerminal as _;
        (std::io::stdout().is_terminal(), std::io::stderr().is_terminal())
    })
}

fn stream_is_terminal(stream: LostStream) -> bool {
    // `get_or_init` and not `get`: a panic on a path that never installed the
    // hook — a unit test, a library caller — still gets a real answer rather
    // than a default that silently changes the verdict.
    let (stdout, stderr) = record_startup_terminals();
    match stream {
        LostStream::Stdout => stdout,
        LostStream::Stderr => stderr,
    }
}

/// Whether a panic is the standard library's "failed printing to stdout" panic
/// for an output that no longer exists, rather than a real bug.
///
/// Matched on the payload text because that is all the standard library
/// exposes: the panic carries no typed error. The message must be that panic,
/// so one that merely mentions a broken pipe in some other context still
/// reports normally.
fn is_lost_output_panic(info: &std::panic::PanicHookInfo<'_>) -> bool {
    let payload = info.payload();
    let message = payload
        .downcast_ref::<String>()
        .map(String::as_str)
        .or_else(|| payload.downcast_ref::<&str>().copied());
    message.is_some_and(message_is_lost_output)
}

fn message_is_lost_output(message: &str) -> bool {
    lost_output_verdict(message, stream_is_terminal)
}

/// The decision itself, over the panic message and a way to ask whether the
/// stream it names is a terminal, so it can be tested — a `PanicHookInfo` is
/// not constructible outside a real panic, and a test cannot close the
/// harness's own stdout.
///
/// `EPIPE` always means the reader is gone. `EIO` means it only on a terminal,
/// where it is how a closed pty reports the session hanging up; on a redirected
/// stdout it is a real write failure — a full device, a dropped network mount —
/// and treating that as "the output is gone" would kill every in-flight agent
/// and exit `141` without a word about what actually went wrong.
///
/// `is_terminal` therefore answers for the stream as it was at startup, never
/// as it is now: see [`STARTUP_TERMINALS`] for why asking now inverts the
/// answer in the one case this exists for.
fn lost_output_verdict(message: &str, is_terminal: impl Fn(LostStream) -> bool) -> bool {
    let Some(stream) = printing_failure_stream(message) else {
        return false;
    };
    if BROKEN_PIPE_MARKERS.iter().any(|marker| message.contains(marker)) {
        return true;
    }
    IO_ERROR_MARKERS.iter().any(|marker| message.contains(marker)) && is_terminal(stream)
}

pub fn run() {
    install_quiet_broken_pipe_exit();
    install_diagnostic_handler();
    CompleteEnv::with_factory(cli_command).bin(invoked_bin_name()).complete();

    let cli = match Cli::try_parse() {
        Ok(cli) => cli,
        // A bare `rhei` is a request for orientation, so answer it with the
        // root help on stdout and a success exit. Every *other* missing
        // subcommand — `rhei snapshot`, say — is a usage error about that
        // subcommand: let clap render its own contextual help to stderr with
        // the conventional exit code, or a script cannot tell the two apart.
        Err(err)
            if is_bare_invocation()
                && matches!(
                    err.kind(),
                    ErrorKind::MissingSubcommand
                        | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
                ) =>
        {
            let mut cmd = cli_command();
            if let Err(io_err) = cmd.print_help() {
                eprintln!("failed to write CLI help: {io_err}");
                std::process::exit(1);
            }
            println!();
            return;
        }
        Err(err) => err.exit(),
    };

    let json_mode = command_wants_json(&cli.command);

    if let Err(err) = dispatch(cli) {
        if json_mode {
            emit_json_error(&err);
        } else {
            eprintln!("{err:?}");
        }
        // A run that a signal ended reports the signal, not a generic failure:
        // whatever error it surfaced on the way out is a consequence of the
        // interruption. §FS-rhei-run.3.2
        let code = interrupt_exit_code().unwrap_or(1);
        finalize_run_descriptor(code);
        std::process::exit(code);
    }
    // Checked after `dispatch` so every guard has run and the report is
    // written: `128 + signal` is what a shell reports for a process the signal
    // killed, and `rhei run` was asked to stop by one. §FS-rhei-run.3.2
    if let Some(code) = interrupt_exit_code() {
        finalize_run_descriptor(code);
        std::process::exit(code);
    }
    // The exit code is only knowable here, which is why the descriptor's
    // terminal status is stamped from the exit path rather than from a guard
    // that cannot see it. §FS-rhei-run-headless.2
    finalize_run_descriptor(0);
}

/// Returns true when the invoked command's output format is JSON. In that
/// case, errors are rendered as a single-line JSON object on stderr instead
/// of the default miette text, so machine consumers don't have to parse two
/// shapes.
fn command_wants_json(command: &Commands) -> bool {
    match command {
        Commands::Next { json, .. } => *json,
        Commands::States { json, .. } => *json,
        Commands::List { json, .. } => *json,
        Commands::Snapshot { command: SnapshotCommand::List { format, .. }, .. } => {
            matches!(format, SnapshotListFormat::Json)
        }
        Commands::Templates { json, .. } => *json,
        Commands::Cost { json, .. } => *json,
        Commands::Runs { json } => *json,
        // `attach --json` streams records on stdout, so a failure must not
        // print miette prose beside them. §FS-rhei-run-json.1
        Commands::Attach { json, .. } => *json,
        Commands::Run { standalone, .. } => standalone.json,
        Commands::Render { format, .. } => matches!(format, RenderFormat::Json),
        _ => false,
    }
}

fn emit_json_error(err: &miette::Report) {
    // §FS-rhei-errors.5: machine consumers get the same next action as humans.
    let mut error = serde_json::json!({ "message": err.to_string() });
    if let Some(help) = err.help() {
        error["help"] = serde_json::Value::String(help.to_string());
    }
    let payload = serde_json::json!({ "error": error });
    let serialized = serde_json::to_string(&payload)
        .unwrap_or_else(|_| format!("{{\"error\":{{\"message\":{:?}}}}}", err.to_string()));
    eprintln!("{serialized}");
}

/// Dispatch the parsed CLI command.
fn dispatch(cli: Cli) -> MietteResult<()> {
    // `--state-machine` is accepted both before the subcommand and on the
    // subcommands that read one; the subcommand copy wins when both appear.
    let before_subcommand = cli.state_machine;
    match cli.command {
        Commands::Init { dir, here, title, no_agents, force } => {
            init_command(dir.as_deref(), title.as_deref(), no_agents, force, here)
        }
        Commands::New { options } => new_command(&options),
        Commands::Validate { watch, input, state_machine } => {
            // §FS-rhei-validate.1.1: validation never narrows — a member rhei
            // validates the project it cannot resolve without.
            let target = resolve_plan_target(input)?;
            report_validation_widened(&target);
            validate_command(target.path(), state_machine.or(before_subcommand).as_deref(), watch)
        }
        Commands::Render { input, format, pretty, no_color, no_metadata, no_content, state_machine } => {
            let target = resolve_plan_target(input)?;
            render_command(
                target.path(),
                &target.scope_with(&[]),
                state_machine.or(before_subcommand).as_deref(),
                format,
                pretty,
                no_color,
                no_metadata,
                no_content,
            )
        }
        Commands::States { input, rhei, json, state_machine } => {
            states_command(input, state_machine.or(before_subcommand).as_deref(), &rhei, json)
        }
        Commands::List {
            input,
            rhei,
            state,
            assignee,
            no_assignee,
            kind,
            has_prior,
            parent,
            root,
            contains,
            terminal,
            non_terminal,
            ready,
            blocked,
            limit,
            json,
            state_machine,
        } => {
            let target = resolve_plan_target(input)?;
            let rhei = target.scope_with(&rhei);
            list_command(
            target.path(),
            state_machine.or(before_subcommand).as_deref(),
            ListFilters {
                rhei,
                states: state,
                assignee,
                no_assignee,
                kind,
                has_prior,
                parent,
                root,
                contains,
                terminal,
                non_terminal,
                ready,
                blocked,
                limit,
            },
            json,
            )
        }
        Commands::Transition { input, task, from, to, result, no_callbacks, state_machine } => {
            let (input, task) = split_transition_ticket_target(input, task)?;
            let target = resolve_plan_target(input)?;
            transition_command(
                target.path(),
                &target.scope_with(&[]),
                state_machine.or(before_subcommand).as_deref(),
                &task,
                &from,
                &to,
                result.as_deref(),
                no_callbacks,
            )
        }
        Commands::Run { input, standalone, agent, program, snapshot, state_machine } => {
            let target = resolve_plan_target(input)?;
            let mut opts: RunOptions = (standalone, agent, program, snapshot).into();
            opts.narrow_to(target.scope_with(opts.rhei_scope()));
            run_command(target.path(), state_machine.or(before_subcommand).as_deref(), opts)
        }
        // `rhei cost` reads accounting artifacts under the target's own runtime
        // root and resolves no dependency graph, so it stays on the path it was
        // given rather than widening to the enclosing project.
        Commands::Cost { input, task, json, by } => {
            cost_command(resolve_plan_target(input)?.path(), task.as_deref(), json, by)
        }
        Commands::Attach { run, json, since, wait } => {
            attach_command(run.as_deref(), json, since, wait)
        }
        Commands::Runs { json } => runs_command(json),
        Commands::Stop { run, kill, wait } => stop_command(run.as_deref(), kill, wait),
        Commands::Intervene { plan, task, slot, message } => {
            intervene_command(&plan, &task, slot, &message)
        }
        Commands::Viz { input, output, open, state_machine } => {
            let target = resolve_plan_target(input)?;
            viz_command(
                target.path(),
                &target.scope_with(&[]),
                state_machine.or(before_subcommand).as_deref(),
                output.as_deref(),
                open,
            )
        }
        Commands::Snapshot { command, state_machine } => snapshot_command(command, state_machine.or(before_subcommand).as_deref()),
        Commands::Templates { template, json, source } => {
            templates::templates_command(json, &source, template.as_deref())
        }
        Commands::Instantiate {
            template,
            set_values,
            set_files,
            values,
            output,
            execute,
            dry_run,
            keep_on_error,
            list_inputs,
            input_args,
        } => templates::instantiate_command(
            template.as_deref(),
            &input_args,
            &instantiate_execute_args_from_env(),
            &set_values,
            &set_files,
            &values,
            output.as_deref(),
            execute,
            dry_run,
            keep_on_error,
            list_inputs,
        ),
        Commands::Next { input, task, json, no_callbacks, peek, rhei, state_machine } => {
            let target = resolve_plan_target(input)?;
            next_command(
                target.path(),
                state_machine.or(before_subcommand).as_deref(),
                task.as_deref(),
                json,
                no_callbacks,
                peek,
                &target.scope_with(&rhei),
            )
        }
        Commands::Complete { input, task, result, no_callbacks, state_machine } => {
            let (input, task) = split_complete_ticket_target(input, task)?;
            let target = resolve_plan_target(input)?;
            complete_command(
                target.path(),
                &target.scope_with(&[]),
                state_machine.or(before_subcommand).as_deref(),
                &task,
                &result,
                no_callbacks,
            )
        }
        Commands::Release { input, task, all, rhei, dry_run, state_machine } => {
            let (input, task) = split_ticket_target(input, task)?;
            let target = resolve_plan_target(input)?;
            release_command(
                target.path(),
                state_machine.or(before_subcommand).as_deref(),
                task.as_deref(),
                all,
                &target.scope_with(&rhei),
                dry_run,
            )
        }
        Commands::Reset { input, rhei, dry_run, yes, state_machine } => {
            // §FS-rhei-panta.6: reset destroys runtime state, so it is the one
            // plan-taking command that never infers an omitted target.
            let Some(input) = input else {
                return Err(miette!(
help = "preview it first: rhei reset <plan-or-project> --dry-run",

                    "`rhei reset` rewrites every in-scope ticket to the initial state \
                     and deletes runtime artifacts, so it never infers its target. \
                     Name the plan or project explicitly: `rhei reset <plan-or-project>`"
                ));
            };
            // Reset never *infers* a target, but an explicit member rhei still
            // loads through its project and narrows to itself. §FS-rhei-panta.6
            let target = resolve_plan_target(Some(input))?;
            reset_command(
                target.path(),
                state_machine.or(before_subcommand).as_deref(),
                &target.scope_with(&rhei),
                dry_run,
                yes,
            )
        }
        Commands::Version => {
            print_versions();
            Ok(())
        }
        Commands::InstallSkills { agent, local, link, uninstall, dry_run, skills } => {
            install_skills_command(agent, local, link, uninstall, dry_run, &skills)
        }
        Commands::Completions { shell, install, user: _, system, output, dry_run } => {
            completions_command(shell, install, system, output.as_deref(), dry_run)
        }
    }
}