Skip to main content

astrs_cli/
cli.rs

1//! The `astrs` clap derive tree (blueprint §17): the full verb set, with
2//! a real argument schema on every subcommand — so `--help`, argument
3//! validation and shell completion (`astrs completion`) describe the whole
4//! surface, including the handful of verbs whose implementation belongs to
5//! a later wave and which report
6//! [`crate::error::CliError::NotImplementedYet`] when invoked (see
7//! [`crate::command::stub`]).
8//!
9//! `--json` and `--color` are global flags (available on, and inherited
10//! by, every subcommand — blueprint §17: "All output has `--json` for
11//! scripting") rather than repeated on each leaf args struct.
12
13use std::path::PathBuf;
14
15use clap::{Args, Parser, Subcommand, ValueEnum};
16
17use crate::command::completion::CompletionShell;
18use crate::command::graph::GraphFormat;
19use crate::command::new::{NewKind, NewLang};
20
21/// When to colorize human-readable output with plain ANSI SGR codes.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, ValueEnum)]
23#[value(rename_all = "lower")]
24pub enum ColorMode {
25    /// Colorize only when the output sink is a terminal.
26    #[default]
27    Auto,
28    /// Always colorize.
29    Always,
30    /// Never colorize.
31    Never,
32}
33
34/// The `astrs` command line: run, build, monitor, migrate and bridge
35/// robotic dataflows (blueprint §17).
36#[derive(Debug, Parser)]
37#[command(name = "astrs", version, about, long_about = None)]
38pub struct Cli {
39    /// Emit machine-readable JSON instead of human-readable text, on
40    /// every subcommand that produces a report.
41    #[arg(long, global = true)]
42    pub json: bool,
43    /// When to colorize human-readable output.
44    #[arg(long, global = true, value_enum, default_value_t = ColorMode::Auto)]
45    pub color: ColorMode,
46    /// The verb to run.
47    #[command(subcommand)]
48    pub command: Command,
49}
50
51/// The full `astrs` verb set (blueprint §17).
52#[derive(Debug, Subcommand)]
53pub enum Command {
54    // ---- Lifecycle ----------------------------------------------------
55    /// Run a dataflow in single-process mode (embeds an in-process
56    /// daemon; no coordinator).
57    Run(RunArgs),
58    /// Start a dataflow cluster (coordinator + daemons already running).
59    Up(UpArgs),
60    /// Tear down a running dataflow cluster.
61    Down(DownArgs),
62    /// Build every node in a manifest (resolves `git:` sources via the
63    /// system `git` binary, then runs each node's `build:` command).
64    Build(BuildArgs),
65    /// Start a dataflow on an already-running cluster.
66    Start(StartArgs),
67    /// Stop a running dataflow, leaving the cluster up.
68    Stop(StopArgs),
69    /// Stop then restart a running dataflow.
70    Restart(RestartArgs),
71    /// Stop a dataflow and release every resource it held.
72    Destroy(DestroyArgs),
73    /// Reclaim the resources of dataflows that have already finished.
74    Clean(CleanArgs),
75
76    // ---- Monitoring -----------------------------------------------------
77    /// List known dataflows.
78    List(ListArgs),
79    /// Tail (or dump) a dataflow's logs.
80    Logs(LogsArgs),
81    /// Launch the live TUI monitor.
82    Top(TopArgs),
83    /// Inspect a running topic.
84    #[command(subcommand)]
85    Topic(TopicCommand),
86    /// Show a dataflow's (or node's) current status.
87    Status(StatusArgs),
88    /// Print a causal (HLC-ordered) event trace.
89    Trace(TraceArgs),
90
91    // ---- Graph ops ------------------------------------------------------
92    /// Parse, expand and type-check a manifest, reporting every
93    /// diagnostic found.
94    Validate(ValidateCliArgs),
95    /// Print a manifest with every `module:`-sourced node flattened.
96    Expand(ExpandCliArgs),
97    /// Visualize a manifest's dataflow graph.
98    Graph(GraphCliArgs),
99    /// Add, remove or replace a node in a running dataflow.
100    #[command(subcommand)]
101    Node(NodeCommand),
102    /// Get, set, list or delete a running dataflow's parameters.
103    #[command(subcommand)]
104    Param(ParamCommand),
105
106    // ---- Data -----------------------------------------------------------
107    /// Start or stop recording a dataflow's outputs to a `.arec` file.
108    #[command(subcommand)]
109    Record(RecordCommand),
110    /// Replay a `.arec` recording as live sources.
111    Replay(ReplayArgs),
112    /// Convert or inspect a rosbag2 (`.db3`/`.mcap`) file.
113    #[command(subcommand)]
114    Bag(BagCommand),
115
116    // ---- ROS 2 ------------------------------------------------------------
117    /// ROS 2 interop diagnostics.
118    #[command(subcommand)]
119    Ros2(Ros2Command),
120
121    // ---- Dev --------------------------------------------------------------
122    /// Scaffold a new node, operator, or graph manifest.
123    #[command(subcommand)]
124    New(NewCommand),
125    /// Migrate a manifest from another dataflow framework.
126    #[command(subcommand)]
127    Migrate(MigrateCommand),
128    /// Check the local environment for AstRS-readiness.
129    Doctor(DoctorCliArgs),
130    /// Generate a shell completion script.
131    Completion(CompletionCliArgs),
132    /// Emit the manifest JSON schema.
133    Schema(SchemaCliArgs),
134    /// Mint a scoped cluster credential from the root token (blueprint §16,
135    /// §22).
136    #[command(subcommand)]
137    Token(TokenCommand),
138    /// Manage the local AstRS package index (blueprint §22): update,
139    /// search, inspect, or scaffold one for self-hosting.
140    #[command(subcommand)]
141    Hub(HubCommand),
142
143    // ---- Hidden internals -------------------------------------------------
144    /// (internal) Run the per-machine daemon process.
145    #[command(hide = true)]
146    Daemon(DaemonArgs),
147    /// (internal) Run the cluster coordinator process.
148    #[command(hide = true)]
149    Coordinator(CoordinatorArgs),
150    /// (internal) Run an operator-hosting runtime process.
151    #[command(hide = true)]
152    Runtime(RuntimeArgs),
153}
154
155// =========================================================================
156// Lifecycle
157// =========================================================================
158
159/// Where a client verb finds the coordinator, and how it authenticates —
160/// flattened into every verb that talks to one so the four flags are
161/// spelled, parsed and documented exactly once (blueprint §16, §24.2).
162#[derive(Debug, Args, Clone, Default)]
163pub struct ConnectArgs {
164    /// The coordinator address (`host[:port]`, or a bare port); defaults to
165    /// `ASTRS_COORDINATOR_ADDR`, then loopback on `ASTRS_COORDINATOR_PORT`
166    /// (7407).
167    #[arg(long)]
168    pub coordinator: Option<String>,
169    /// The 64-hex cluster token (§16). Prefer `--token-file`: an argument
170    /// is visible in `ps`.
171    #[arg(long)]
172    pub token: Option<String>,
173    /// Read the cluster token from this file instead of
174    /// `<working-dir>/.astrs-token`.
175    #[arg(long)]
176    pub token_file: Option<PathBuf>,
177    /// The directory holding `.astrs-token`; defaults to the process's
178    /// current directory (§16).
179    #[arg(long)]
180    pub working_dir: Option<PathBuf>,
181}
182
183/// `astrs run` arguments.
184#[derive(Debug, Args)]
185pub struct RunArgs {
186    /// The manifest to run.
187    pub manifest: PathBuf,
188    /// Drive the timer wheel from a recorded HLC stream instead of the
189    /// wall clock, for byte-identical replay (blueprint §14). Needs
190    /// `--from-recording`; refused with
191    /// [`crate::error::CliError::DeterministicNeedsRecording`] without it.
192    #[arg(long)]
193    pub deterministic: bool,
194    /// The `.arec` recording `--deterministic` replays as its clock source.
195    /// Every node the recording produced for is stood down (`path:
196    /// dynamic`) and fed from it instead of spawned.
197    #[arg(long, value_name = "PATH")]
198    pub from_recording: Option<PathBuf>,
199    /// Paces `--deterministic`'s wall-clock walk through the recording:
200    /// `1.0` reproduces the original spacing, `2.0` halves it. Omit to
201    /// replay as fast as the loop can — pacing never changes which
202    /// messages are delivered or their stamps, only how long the run takes.
203    #[arg(long, value_name = "FACTOR")]
204    pub speed: Option<f64>,
205    /// Exit once every node with a finite input set has finished, whatever
206    /// the manifest's own `exit_when_nodes_finish:` says.
207    #[arg(long)]
208    pub exit_when_nodes_finish: bool,
209    /// Skip the manifest's `build:` lines and go straight to spawning.
210    #[arg(long)]
211    pub skip_build: bool,
212    /// Hide streamed node output below this level
213    /// (`trace|debug|info|warn|error`).
214    #[arg(long, value_name = "LEVEL")]
215    pub level: Option<String>,
216    /// The directory node paths, `build:` lines and relative `env:` values
217    /// resolve against; defaults to the manifest's own directory.
218    #[arg(long)]
219    pub working_dir: Option<PathBuf>,
220    /// Where the embedded daemon puts its socket and captured logs;
221    /// defaults to `$ASTRS_RUNTIME_DIR`/`$XDG_RUNTIME_DIR/astrs`.
222    #[arg(long)]
223    pub runtime_dir: Option<PathBuf>,
224    /// Stop the whole graph after this many seconds, however it is doing.
225    #[arg(long, value_name = "SECONDS")]
226    pub timeout: Option<f64>,
227    /// How long a stopping node has to finish before `SIGTERM` (§12).
228    #[arg(long, value_name = "SECONDS")]
229    pub grace: Option<f64>,
230}
231
232/// `astrs up` arguments.
233///
234/// Brings up the *cluster* — a coordinator and this machine's daemon — not
235/// a dataflow; `astrs start` runs dataflows on it (blueprint §17).
236#[derive(Debug, Args)]
237pub struct UpArgs {
238    /// How to reach (and authenticate to) the coordinator.
239    #[command(flatten)]
240    pub connect: ConnectArgs,
241    /// The port the coordinator should listen on; `0` binds a free one.
242    #[arg(long)]
243    pub port: Option<u16>,
244    /// Where pidfiles and sockets live; defaults to
245    /// `$ASTRS_RUNTIME_DIR`/`$XDG_RUNTIME_DIR/astrs` (§24.2).
246    #[arg(long)]
247    pub runtime_dir: Option<PathBuf>,
248    /// Delete the coordinator's parameter/state store before starting, so
249    /// the cluster comes up with nothing remembered (§4.2).
250    #[arg(long)]
251    pub recreate_store: bool,
252    /// Start the coordinator only, leaving this machine without a daemon.
253    #[arg(long)]
254    pub no_daemon: bool,
255}
256
257/// `astrs down` arguments.
258#[derive(Debug, Args)]
259pub struct DownArgs {
260    /// How to reach (and authenticate to) the coordinator.
261    #[command(flatten)]
262    pub connect: ConnectArgs,
263    /// Where the pidfiles to read live (§24.2).
264    #[arg(long)]
265    pub runtime_dir: Option<PathBuf>,
266    /// Tear the cluster down even while dataflows are still running.
267    #[arg(long)]
268    pub force: bool,
269}
270
271/// `astrs build` arguments.
272#[derive(Debug, Args)]
273pub struct BuildArgs {
274    /// The manifest whose nodes should be built.
275    pub manifest: PathBuf,
276    /// Append `--release` to every `build:` line — the common
277    /// `cargo build` case. A build line that does not accept the flag will
278    /// fail, so spell the profile out in the manifest when in doubt.
279    #[arg(long)]
280    pub release: bool,
281    /// Only build this one node id (default: every node).
282    #[arg(long)]
283    pub node: Option<String>,
284    /// The directory `build:` lines run in; defaults to the manifest's own
285    /// directory.
286    #[arg(long)]
287    pub working_dir: Option<PathBuf>,
288    /// Where per-node build logs are written; defaults to
289    /// `$ASTRS_RUNTIME_DIR`/`$XDG_RUNTIME_DIR/astrs` (§24.2).
290    #[arg(long)]
291    pub runtime_dir: Option<PathBuf>,
292}
293
294/// `astrs start` arguments.
295#[derive(Debug, Args)]
296pub struct StartArgs {
297    /// The manifest to start on the already-running cluster.
298    pub manifest: PathBuf,
299    /// How to reach (and authenticate to) the coordinator.
300    #[command(flatten)]
301    pub connect: ConnectArgs,
302    /// A name for the run, for `astrs list` and `astrs stop <name>`.
303    #[arg(long)]
304    pub name: Option<String>,
305    /// Override where nodes run (§8.3 `deploy.machine`), repeatable.
306    ///
307    /// `--machine robot-1` places every node the manifest left unplaced;
308    /// `--machine planner=robot-2` pins one node, overriding whatever the
309    /// manifest said about it.
310    #[arg(long = "machine", value_name = "[NODE=]MACHINE")]
311    pub machines: Vec<String>,
312    /// Stream the dataflow's logs until it finishes, then exit with its
313    /// severity — rather than returning as soon as it is started.
314    #[arg(long)]
315    pub attach: bool,
316    /// Hide streamed output below this level, with `--attach`.
317    #[arg(long, value_name = "LEVEL")]
318    pub level: Option<String>,
319}
320
321/// `astrs stop` arguments.
322#[derive(Debug, Args)]
323pub struct StopArgs {
324    /// The dataflow id (or name) to stop.
325    pub dataflow: String,
326    /// How to reach (and authenticate to) the coordinator.
327    #[command(flatten)]
328    pub connect: ConnectArgs,
329    /// How long nodes get to finish before they are killed (§12).
330    #[arg(long, value_name = "SECONDS")]
331    pub grace: Option<f64>,
332}
333
334/// `astrs restart` arguments.
335#[derive(Debug, Args)]
336pub struct RestartArgs {
337    /// The dataflow id (or name) to restart.
338    pub dataflow: String,
339    /// How to reach (and authenticate to) the coordinator.
340    #[command(flatten)]
341    pub connect: ConnectArgs,
342    /// Re-run the manifest's `build:` lines before starting again.
343    #[arg(long)]
344    pub rebuild: bool,
345}
346
347/// `astrs destroy` arguments.
348#[derive(Debug, Args)]
349pub struct DestroyArgs {
350    /// The dataflow id (or name) to destroy; every dataflow when omitted.
351    pub dataflow: Option<String>,
352    /// How to reach (and authenticate to) the coordinator.
353    #[command(flatten)]
354    pub connect: ConnectArgs,
355    /// Destroy even while dataflows are still running.
356    #[arg(long)]
357    pub force: bool,
358}
359
360/// `astrs clean` arguments.
361#[derive(Debug, Args)]
362pub struct CleanArgs {
363    /// The finished dataflow to clean; every finished one when omitted.
364    pub dataflow: Option<String>,
365    /// How to reach (and authenticate to) the coordinator.
366    #[command(flatten)]
367    pub connect: ConnectArgs,
368    /// Also delete build artefacts.
369    #[arg(long)]
370    pub artifacts: bool,
371    /// Also delete captured logs.
372    #[arg(long)]
373    pub logs: bool,
374}
375
376// =========================================================================
377// Monitoring
378// =========================================================================
379
380/// `astrs list` arguments.
381#[derive(Debug, Args)]
382pub struct ListArgs {
383    /// How to reach (and authenticate to) the coordinator.
384    #[command(flatten)]
385    pub connect: ConnectArgs,
386    /// Include dataflows that have already finished.
387    #[arg(short, long)]
388    pub all: bool,
389}
390
391/// `astrs logs` arguments.
392#[derive(Debug, Args)]
393pub struct LogsArgs {
394    /// The dataflow id (or name) to show logs for; every dataflow if
395    /// omitted.
396    pub dataflow: Option<String>,
397    /// How to reach (and authenticate to) the coordinator.
398    #[command(flatten)]
399    pub connect: ConnectArgs,
400    /// Keep streaming new log records instead of dumping and exiting.
401    #[arg(short, long)]
402    pub follow: bool,
403    /// Only show records at or above this level.
404    #[arg(long)]
405    pub level: Option<String>,
406    /// Only show records from this node id.
407    #[arg(long)]
408    pub node: Option<String>,
409    /// At most this many records in a non-following dump.
410    #[arg(long)]
411    pub limit: Option<u32>,
412}
413
414/// `astrs top` arguments.
415#[derive(Debug, Args)]
416pub struct TopArgs {
417    /// How to reach (and authenticate to) the coordinator. Ignored when
418    /// `--replay` is given — a replay session opens no connection at all.
419    #[command(flatten)]
420    pub connect: ConnectArgs,
421    /// Render an `.arec` recording instead of a live cluster (blueprint
422    /// §14). The coordinator is never dialled in this mode.
423    #[arg(long)]
424    pub replay: Option<PathBuf>,
425}
426
427/// `astrs topic` subcommands.
428#[derive(Debug, Subcommand)]
429pub enum TopicCommand {
430    /// Print every message on a topic as it arrives.
431    Echo(TopicEchoArgs),
432    /// Report a topic's observed message rate.
433    Hz(TopicHzArgs),
434    /// Show a topic's type, publisher(s) and subscriber(s).
435    Info(TopicInfoArgs),
436    /// Publish one message onto a topic.
437    Pub(TopicPubArgs),
438}
439
440/// `astrs topic echo` arguments.
441#[derive(Debug, Args)]
442pub struct TopicEchoArgs {
443    /// The topic to echo, as `node/output`.
444    pub topic: String,
445    /// The dataflow it belongs to; probes the cluster's sole running
446    /// dataflow if omitted.
447    #[arg(long)]
448    pub dataflow: Option<String>,
449    /// Stop after this many messages instead of streaming until
450    /// interrupted (`ros2 topic echo --once` for `--count 1`).
451    #[arg(long)]
452    pub count: Option<u32>,
453    /// How to reach (and authenticate to) the coordinator.
454    #[command(flatten)]
455    pub connect: ConnectArgs,
456}
457
458/// `astrs topic hz` arguments.
459#[derive(Debug, Args)]
460pub struct TopicHzArgs {
461    /// The topic to measure, as `node/output`.
462    pub topic: String,
463    /// The dataflow it belongs to; probes the cluster's sole running
464    /// dataflow if omitted.
465    #[arg(long)]
466    pub dataflow: Option<String>,
467    /// The trailing window the rate is computed over, in seconds.
468    #[arg(long, default_value_t = 5.0)]
469    pub window: f64,
470    /// Stop after this many messages instead of streaming until
471    /// interrupted.
472    #[arg(long)]
473    pub count: Option<u32>,
474    /// How to reach (and authenticate to) the coordinator.
475    #[command(flatten)]
476    pub connect: ConnectArgs,
477}
478
479/// `astrs topic info` arguments.
480#[derive(Debug, Args)]
481pub struct TopicInfoArgs {
482    /// The topic to inspect, as `node/output`.
483    pub topic: String,
484    /// The dataflow it belongs to; probes the cluster's sole running
485    /// dataflow if omitted.
486    #[arg(long)]
487    pub dataflow: Option<String>,
488    /// A manifest on disk to resolve the subscriber list from (the
489    /// coordinator does not yet answer with a running dataflow's graph —
490    /// see this crate's own docs).
491    #[arg(long)]
492    pub manifest: Option<PathBuf>,
493    /// How to reach (and authenticate to) the coordinator.
494    #[command(flatten)]
495    pub connect: ConnectArgs,
496}
497
498/// `astrs topic pub` arguments.
499#[derive(Debug, Args)]
500pub struct TopicPubArgs {
501    /// The topic to publish onto, as `node/output` — the *producer* port a
502    /// `path: dynamic` node in the manifest declares, not a consumer's
503    /// input (this crate's own docs explain why).
504    pub topic: String,
505    /// The message payload, as JSON.
506    pub message: String,
507    /// The dataflow it belongs to; probes the cluster's sole running
508    /// dataflow if omitted.
509    #[arg(long)]
510    pub dataflow: Option<String>,
511    /// Repeat the publish at this rate (Hz) instead of once.
512    #[arg(long)]
513    pub rate: Option<f64>,
514    /// How to reach (and authenticate to) the coordinator.
515    #[command(flatten)]
516    pub connect: ConnectArgs,
517}
518
519/// `astrs status` arguments.
520///
521/// With no dataflow named this probes the local *cluster* — the
522/// coordinator and this machine's daemon — which is what tells `astrs up`
523/// apart from "nothing is running" (blueprint §17).
524#[derive(Debug, Args)]
525pub struct StatusArgs {
526    /// The dataflow id (or name) to show; probes the cluster if omitted.
527    pub dataflow: Option<String>,
528    /// How to reach (and authenticate to) the coordinator.
529    #[command(flatten)]
530    pub connect: ConnectArgs,
531    /// Where the pidfiles to read live (§24.2).
532    #[arg(long)]
533    pub runtime_dir: Option<PathBuf>,
534}
535
536/// `astrs trace` arguments.
537#[derive(Debug, Args)]
538pub struct TraceArgs {
539    /// The dataflow id (or name) to trace; every dataflow if omitted.
540    pub dataflow: Option<String>,
541    /// Only trace events on this node id.
542    #[arg(long)]
543    pub node: Option<String>,
544    /// Stop after this many spans.
545    #[arg(long)]
546    pub limit: Option<u32>,
547    /// How to reach (and authenticate to) the coordinator.
548    #[command(flatten)]
549    pub connect: ConnectArgs,
550}
551
552// =========================================================================
553// Graph ops
554// =========================================================================
555
556/// `astrs validate` arguments.
557#[derive(Debug, Args)]
558pub struct ValidateCliArgs {
559    /// The manifest to validate.
560    pub manifest: PathBuf,
561    /// Prove the graph's obligations — deadlock freedom, queue
562    /// boundedness, rate consistency, latency budgets and type-rule
563    /// consistency (blueprint §15) — through the SMT solver, printing a
564    /// counterexample for any that fails.
565    #[arg(long)]
566    pub prove: bool,
567    /// A verification profile supplying what the manifest cannot state:
568    /// per-node service times and named end-to-end latency budgets. Only
569    /// meaningful with `--prove`; every other obligation is discharged
570    /// from the manifest alone.
571    #[arg(long, value_name = "FILE", requires = "prove")]
572    pub profile: Option<PathBuf>,
573}
574
575/// `astrs expand` arguments.
576#[derive(Debug, Args)]
577pub struct ExpandCliArgs {
578    /// The manifest to expand.
579    pub manifest: PathBuf,
580}
581
582/// `astrs graph` arguments.
583#[derive(Debug, Args)]
584pub struct GraphCliArgs {
585    /// The manifest to visualize.
586    pub manifest: PathBuf,
587    /// The output format.
588    #[arg(long, value_enum, default_value_t = GraphFormatArg::Mermaid)]
589    pub format: GraphFormatArg,
590}
591
592/// The `--format` values `astrs graph` accepts (a thin `clap::ValueEnum`
593/// wrapper over [`GraphFormat`], which has no `clap` dependency of its
594/// own — keeping `astrs-graph`'s presentation-neutral emitters decoupled
595/// from this crate's argument-parsing choices).
596#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
597#[value(rename_all = "lower")]
598pub enum GraphFormatArg {
599    /// Mermaid flowchart source.
600    Mermaid,
601    /// Graphviz DOT source.
602    Dot,
603    /// A self-contained HTML page embedding the mermaid source.
604    Html,
605}
606
607impl From<GraphFormatArg> for GraphFormat {
608    fn from(value: GraphFormatArg) -> Self {
609        match value {
610            GraphFormatArg::Mermaid => Self::Mermaid,
611            GraphFormatArg::Dot => Self::Dot,
612            GraphFormatArg::Html => Self::Html,
613        }
614    }
615}
616
617/// `astrs node` subcommands (blueprint §8, §17 dynamic topology).
618#[derive(Debug, Subcommand)]
619pub enum NodeCommand {
620    /// Add a node to a running dataflow.
621    Add(NodeAddArgs),
622    /// Remove a node from a running dataflow.
623    Remove(NodeRemoveArgs),
624    /// Replace a node in a running dataflow with a new definition.
625    Replace(NodeReplaceArgs),
626    /// Connect (or rewire) one input edge on a live node.
627    Connect(NodeConnectArgs),
628    /// Disconnect one input edge from a live node.
629    Disconnect(NodeDisconnectArgs),
630}
631
632/// `astrs node add` arguments.
633#[derive(Debug, Args)]
634pub struct NodeAddArgs {
635    /// The dataflow id (or name) to add the node to.
636    pub dataflow: String,
637    /// A manifest fragment (a single node's YAML, with no `nodes:`
638    /// wrapper) describing the new node.
639    pub node_manifest: PathBuf,
640    /// How to reach (and authenticate to) the coordinator.
641    #[command(flatten)]
642    pub connect: ConnectArgs,
643    /// Register the node without spawning it yet.
644    #[arg(long)]
645    pub no_start: bool,
646    /// Emit JSON rather than a human line.
647    #[arg(long)]
648    pub json: bool,
649}
650
651/// `astrs node remove` arguments.
652#[derive(Debug, Args)]
653pub struct NodeRemoveArgs {
654    /// The dataflow id (or name) to remove the node from.
655    pub dataflow: String,
656    /// The node id to remove.
657    pub node_id: String,
658    /// How to reach (and authenticate to) the coordinator.
659    #[command(flatten)]
660    pub connect: ConnectArgs,
661    /// How long the node gets to finish before it is killed (§12).
662    #[arg(long, value_name = "SECONDS")]
663    pub grace: Option<f64>,
664    /// Emit JSON rather than a human line.
665    #[arg(long)]
666    pub json: bool,
667}
668
669/// `astrs node replace` arguments.
670#[derive(Debug, Args)]
671pub struct NodeReplaceArgs {
672    /// The dataflow id (or name) whose node should be replaced.
673    pub dataflow: String,
674    /// The node id to replace.
675    pub node_id: String,
676    /// A manifest fragment (a single node's YAML, with no `nodes:`
677    /// wrapper) describing the replacement.
678    pub node_manifest: PathBuf,
679    /// How to reach (and authenticate to) the coordinator.
680    #[command(flatten)]
681    pub connect: ConnectArgs,
682    /// Let the outgoing incarnation drain its inputs before the cutover.
683    ///
684    /// Accepted but not yet enforced server-side: the daemon-side cutover
685    /// (`astrs-daemon`'s dual-run window) always runs regardless — see
686    /// `astrs-coordinator`'s own report for this deviation.
687    #[arg(long)]
688    pub drain: bool,
689    /// Emit JSON rather than a human line.
690    #[arg(long)]
691    pub json: bool,
692}
693
694/// `astrs node connect` arguments.
695#[derive(Debug, Args)]
696pub struct NodeConnectArgs {
697    /// The dataflow id (or name) to edit.
698    pub dataflow: String,
699    /// The node whose input is being connected (or rewired).
700    pub node_id: String,
701    /// The input's name.
702    pub input: String,
703    /// The producer port to read from, as `node/output`.
704    pub source: String,
705    /// How to reach (and authenticate to) the coordinator.
706    #[command(flatten)]
707    pub connect: ConnectArgs,
708    /// How many messages to buffer (default 10, blueprint §24.2).
709    #[arg(long)]
710    pub queue_size: Option<u32>,
711    /// What to do when the queue is full.
712    #[arg(long, value_enum)]
713    pub queue_policy: Option<QueuePolicyArg>,
714    /// Emit JSON rather than a human line.
715    #[arg(long)]
716    pub json: bool,
717}
718
719/// `astrs node disconnect` arguments.
720#[derive(Debug, Args)]
721pub struct NodeDisconnectArgs {
722    /// The dataflow id (or name) to edit.
723    pub dataflow: String,
724    /// The node whose input is being disconnected.
725    pub node_id: String,
726    /// The input's name.
727    pub input: String,
728    /// How to reach (and authenticate to) the coordinator.
729    #[command(flatten)]
730    pub connect: ConnectArgs,
731    /// Emit JSON rather than a human line.
732    #[arg(long)]
733    pub json: bool,
734}
735
736/// The queue eviction policy for a connected input (`astrs node connect
737/// --queue-policy`) — this crate's own copy of
738/// [`astrs_wire::QueuePolicy`] (blueprint §11.2), which sits below `clap`
739/// in the layer stack and so cannot derive [`ValueEnum`] itself.
740#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
741#[value(rename_all = "kebab-case")]
742pub enum QueuePolicyArg {
743    /// Evict the oldest queued message to make room. The default.
744    DropOldest,
745    /// Buffer up to ten times the queue size, then drop with an error.
746    Backpressure,
747}
748
749/// `astrs param` subcommands.
750#[derive(Debug, Subcommand)]
751pub enum ParamCommand {
752    /// Get one parameter's value.
753    Get(ParamGetArgs),
754    /// Set one parameter's value.
755    Set(ParamSetArgs),
756    /// List every parameter (optionally scoped to one node).
757    List(ParamListArgs),
758    /// Delete one parameter.
759    Delete(ParamDeleteArgs),
760}
761
762/// `astrs param get` arguments.
763#[derive(Debug, Args)]
764pub struct ParamGetArgs {
765    /// The dataflow id (or name), or the word `global` for the
766    /// cluster-wide scope.
767    pub dataflow: String,
768    /// The parameter's key.
769    pub key: String,
770    /// How to reach (and authenticate to) the coordinator.
771    #[command(flatten)]
772    pub connect: ConnectArgs,
773    /// Read the node-scoped value instead of the dataflow-scoped one.
774    #[arg(long)]
775    pub node: Option<String>,
776    /// Report only a value set in this exact scope, rather than falling
777    /// back to the dataflow's (and then the cluster's) value.
778    #[arg(long)]
779    pub exact: bool,
780    /// Keep polling and print every value this key transitions to,
781    /// instead of reading it once (there is no push subscription for
782    /// parameters — see `command::param`'s own docs).
783    #[arg(long)]
784    pub watch: bool,
785    /// With `--watch`, stop after this many observed values (the initial
786    /// read counts as one) instead of watching until interrupted.
787    #[arg(long)]
788    pub count: Option<u32>,
789}
790
791/// `astrs param set` arguments.
792#[derive(Debug, Args)]
793pub struct ParamSetArgs {
794    /// The dataflow id (or name), or the word `global` for the
795    /// cluster-wide scope.
796    pub dataflow: String,
797    /// The parameter's key.
798    pub key: String,
799    /// The value, as plain JSON: `30`, `1.5`, `true`, `"left"`, `[1,2,3]`
800    /// — or the tagged form (`{"float": 30}`) to pin a type.
801    pub value: String,
802    /// How to reach (and authenticate to) the coordinator.
803    #[command(flatten)]
804    pub connect: ConnectArgs,
805    /// Set the node-scoped value instead of the dataflow-scoped one.
806    #[arg(long)]
807    pub node: Option<String>,
808    /// Fail rather than overwrite a value that is already set.
809    #[arg(long)]
810    pub create_only: bool,
811}
812
813/// `astrs param list` arguments.
814#[derive(Debug, Args)]
815pub struct ParamListArgs {
816    /// The dataflow id (or name), or the word `global` for the
817    /// cluster-wide scope.
818    pub dataflow: String,
819    /// How to reach (and authenticate to) the coordinator.
820    #[command(flatten)]
821    pub connect: ConnectArgs,
822    /// Only list parameters on this node id.
823    #[arg(long)]
824    pub node: Option<String>,
825    /// Only list keys starting with this prefix.
826    #[arg(long)]
827    pub prefix: Option<String>,
828    /// Include values inherited from parent scopes.
829    #[arg(long)]
830    pub inherited: bool,
831}
832
833/// `astrs param delete` arguments.
834#[derive(Debug, Args)]
835pub struct ParamDeleteArgs {
836    /// The dataflow id (or name), or the word `global` for the
837    /// cluster-wide scope.
838    pub dataflow: String,
839    /// The parameter's key.
840    pub key: String,
841    /// How to reach (and authenticate to) the coordinator.
842    #[command(flatten)]
843    pub connect: ConnectArgs,
844    /// Delete the node-scoped value instead of the dataflow-scoped one.
845    #[arg(long)]
846    pub node: Option<String>,
847}
848
849// =========================================================================
850// Data
851// =========================================================================
852
853/// `astrs record` subcommands.
854#[derive(Debug, Subcommand)]
855pub enum RecordCommand {
856    /// Start recording a dataflow's outputs.
857    Start(RecordStartArgs),
858    /// Stop an in-progress recording.
859    Stop(RecordStopArgs),
860}
861
862/// `astrs record start` arguments.
863#[derive(Debug, Args)]
864pub struct RecordStartArgs {
865    /// How to reach (and authenticate to) the coordinator.
866    #[command(flatten)]
867    pub connect: ConnectArgs,
868    /// The dataflow id (or name) to record.
869    pub dataflow: String,
870    /// The `.arec` file to write.
871    pub output: PathBuf,
872    /// Restrict recording to these `node/output` ports (repeatable);
873    /// every declared output of every node in the dataflow, if none are
874    /// given.
875    #[arg(long = "only")]
876    pub only: Vec<String>,
877    /// Overwrite an already-recording session at the same path rather
878    /// than refusing.
879    #[arg(long)]
880    pub overwrite: bool,
881}
882
883/// `astrs record stop` arguments.
884#[derive(Debug, Args)]
885pub struct RecordStopArgs {
886    /// How to reach (and authenticate to) the coordinator.
887    #[command(flatten)]
888    pub connect: ConnectArgs,
889    /// The dataflow id (or name) whose recording should stop.
890    pub dataflow: String,
891}
892
893/// How `astrs replay`'s generated `astrs-replay-node` instances pace
894/// their re-emitted entries.
895///
896/// Spells the exact same three modes (and the same kebab-case flag
897/// values) as `astrs_replay_node::TimingMode` — kept as this crate's own
898/// type rather than a dependency on that binary's library purely to
899/// parse three fixed strings, matching this codebase's own convention
900/// of small, independently-testable per-module helpers over sharing one
901/// two-line type across a crate boundary.
902#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, ValueEnum)]
903#[value(rename_all = "kebab-case")]
904pub enum ReplayTimingMode {
905    /// No pacing at all.
906    AsFastAsPossible,
907    /// Recorded HLC deltas, scaled by `--speed`.
908    #[default]
909    RealTime,
910    /// A constant period, from `--rate`.
911    FixedRate,
912}
913
914impl ReplayTimingMode {
915    /// The flag spelling `astrs-replay-node --mode` expects.
916    #[must_use]
917    pub const fn as_str(self) -> &'static str {
918        match self {
919            Self::AsFastAsPossible => "as-fast-as-possible",
920            Self::RealTime => "real-time",
921            Self::FixedRate => "fixed-rate",
922        }
923    }
924}
925
926/// `astrs replay` arguments.
927///
928/// Two forms, and exactly one of them must be chosen (blueprint §14):
929///
930/// ```text
931///   astrs replay s.arec --into graph.yml    offline: print the rewritten manifest
932///   astrs replay s.arec perception          live:    cut the running graph over
933/// ```
934#[derive(Debug, Args)]
935pub struct ReplayArgs {
936    /// The `.arec` file to replay.
937    pub input: PathBuf,
938    /// A *running* dataflow to cut over, by id or by name.
939    ///
940    /// Each chosen node is replaced in place by an `astrs-replay-node`
941    /// reading the recording, keeping its id and therefore its edges — the
942    /// live twin of `--into`'s manifest rewrite.
943    pub dataflow: Option<String>,
944    /// The manifest file to rewrite, replacing chosen source nodes with
945    /// `astrs-replay-node` instances in place.
946    ///
947    /// The offline form: the rewritten manifest is printed and nothing is
948    /// started. Mutually exclusive with the positional dataflow.
949    #[arg(long, conflicts_with = "dataflow")]
950    pub into: Option<String>,
951    /// The replay speed multiplier (`1.0` is real-time), passed through
952    /// to `--mode real-time`'s `--speed`.
953    #[arg(long)]
954    pub speed: Option<f64>,
955    /// The timing mode the generated replay node paces entries with.
956    #[arg(long, value_enum, default_value = "real-time")]
957    pub mode: ReplayTimingMode,
958    /// The fixed emission rate, in Hz, for `--mode fixed-rate`.
959    #[arg(long)]
960    pub rate: Option<f64>,
961    /// Restart each generated replay node from the beginning once its
962    /// recording is exhausted.
963    #[arg(long)]
964    pub r#loop: bool,
965    /// Replace only these node ids (repeatable); every node the
966    /// recording covers, if none are given.
967    #[arg(long = "replace")]
968    pub replace: Vec<String>,
969    /// Let each replaced node drain its inputs before it is stopped.
970    ///
971    /// The live form only: the offline form starts nothing, so there is
972    /// nothing to drain.
973    #[arg(long, requires = "dataflow")]
974    pub drain: bool,
975    /// How to reach the coordinator — the live form only.
976    #[command(flatten)]
977    pub connect: ConnectArgs,
978}
979
980/// `astrs bag` subcommands.
981#[derive(Debug, Subcommand)]
982pub enum BagCommand {
983    /// Convert between `.arec` and rosbag2 (`.db3`/`.mcap`).
984    Convert(BagConvertArgs),
985    /// Show a bag file's summary (topics, types, message counts).
986    Info(BagInfoArgs),
987}
988
989/// `astrs bag convert` arguments.
990#[derive(Debug, Args)]
991pub struct BagConvertArgs {
992    /// The input file (`.arec`, `.db3`, or `.mcap` — inferred from the
993    /// extension).
994    pub input: PathBuf,
995    /// The output file (extension selects the target format).
996    pub output: PathBuf,
997}
998
999/// `astrs bag info` arguments.
1000#[derive(Debug, Args)]
1001pub struct BagInfoArgs {
1002    /// The bag file to inspect.
1003    pub input: PathBuf,
1004}
1005
1006// =========================================================================
1007// ROS 2
1008// =========================================================================
1009
1010/// `astrs ros2` subcommands.
1011#[derive(Debug, Subcommand)]
1012pub enum Ros2Command {
1013    /// Probe ROS 2 discovery (RTPS participants, QoS, domain id).
1014    Doctor(Ros2DoctorArgs),
1015    /// List the live ROS 2 topic graph as AstRS's bridge sees it.
1016    Topics(Ros2TopicsArgs),
1017}
1018
1019/// `astrs ros2 doctor` arguments.
1020#[derive(Debug, Args)]
1021pub struct Ros2DoctorArgs {
1022    /// The ROS domain id to probe (defaults to `ROS_DOMAIN_ID`, or `0`).
1023    #[arg(long)]
1024    pub domain_id: Option<u32>,
1025    /// How many milliseconds to listen for participants.
1026    #[arg(long, value_name = "MS")]
1027    pub timeout: Option<u64>,
1028    /// Include hidden (`_`-prefixed) names.
1029    #[arg(long)]
1030    pub hidden: bool,
1031}
1032
1033/// `astrs ros2 topics` arguments.
1034#[derive(Debug, Args)]
1035pub struct Ros2TopicsArgs {
1036    /// The ROS domain id to probe (defaults to `ROS_DOMAIN_ID`, or `0`).
1037    #[arg(long)]
1038    pub domain_id: Option<u32>,
1039    /// How many milliseconds to listen for participants.
1040    #[arg(long, value_name = "MS")]
1041    pub timeout: Option<u64>,
1042    /// Include hidden (`_`-prefixed) names.
1043    #[arg(long)]
1044    pub hidden: bool,
1045}
1046
1047// =========================================================================
1048// Dev
1049// =========================================================================
1050
1051/// `astrs new` subcommands.
1052#[derive(Debug, Subcommand)]
1053pub enum NewCommand {
1054    /// Scaffold a new node crate.
1055    Node(NewNodeArgs),
1056    /// Scaffold a new runtime-hosted operator crate.
1057    Operator(NewOperatorArgs),
1058    /// Scaffold a new dylib-hosted operator crate (a `cdylib`, `dlopen`ed
1059    /// at spawn time -- blueprint §9.3, §22).
1060    OperatorDylib(NewOperatorDylibArgs),
1061    /// Scaffold a new starter graph manifest.
1062    Graph(NewGraphArgs),
1063}
1064
1065/// `astrs new node` arguments.
1066#[derive(Debug, Args)]
1067pub struct NewNodeArgs {
1068    /// The new node's name (also its directory name).
1069    pub name: String,
1070    /// The language to scaffold in.
1071    #[arg(long, value_enum, default_value_t = NewLang::Rust)]
1072    pub lang: NewLang,
1073    /// The directory to scaffold into.
1074    #[arg(long, default_value = ".")]
1075    pub dir: PathBuf,
1076    /// Overwrite files that already exist at the target location.
1077    #[arg(long)]
1078    pub force: bool,
1079}
1080
1081/// `astrs new operator` arguments.
1082#[derive(Debug, Args)]
1083pub struct NewOperatorArgs {
1084    /// The new operator's name (also its directory name).
1085    pub name: String,
1086    /// The language to scaffold in.
1087    #[arg(long, value_enum, default_value_t = NewLang::Rust)]
1088    pub lang: NewLang,
1089    /// The directory to scaffold into.
1090    #[arg(long, default_value = ".")]
1091    pub dir: PathBuf,
1092    /// Overwrite files that already exist at the target location.
1093    #[arg(long)]
1094    pub force: bool,
1095}
1096
1097/// `astrs new operator-dylib` arguments.
1098#[derive(Debug, Args)]
1099pub struct NewOperatorDylibArgs {
1100    /// The new operator's name (also its directory name).
1101    pub name: String,
1102    /// The language to scaffold in.
1103    #[arg(long, value_enum, default_value_t = NewLang::Rust)]
1104    pub lang: NewLang,
1105    /// The directory to scaffold into.
1106    #[arg(long, default_value = ".")]
1107    pub dir: PathBuf,
1108    /// Overwrite files that already exist at the target location.
1109    #[arg(long)]
1110    pub force: bool,
1111}
1112
1113/// `astrs new graph` arguments.
1114#[derive(Debug, Args)]
1115pub struct NewGraphArgs {
1116    /// The new graph's name (its manifest file's stem).
1117    pub name: String,
1118    /// The directory to scaffold into.
1119    #[arg(long, default_value = ".")]
1120    pub dir: PathBuf,
1121    /// Overwrite the target file if it already exists.
1122    #[arg(long)]
1123    pub force: bool,
1124}
1125
1126impl NewCommand {
1127    /// Flatten this sub-subcommand into
1128    /// [`crate::command::new::NewArgs`]'s kind-agnostic shape.
1129    ///
1130    /// `json` is threaded through separately rather than read off any one
1131    /// leaf args struct because it is the global `--json` flag
1132    /// (blueprint §17: "All output has `--json` for scripting"), not
1133    /// something `clap` ever parses onto [`NewNodeArgs`]/
1134    /// [`NewOperatorArgs`]/[`NewOperatorDylibArgs`]/[`NewGraphArgs`]
1135    /// themselves.
1136    #[must_use]
1137    pub fn into_new_args(self, json: bool) -> crate::command::new::NewArgs {
1138        use crate::command::new::NewArgs;
1139        match self {
1140            Self::Node(a) => NewArgs {
1141                kind: NewKind::Node,
1142                name: a.name,
1143                lang: a.lang,
1144                dir: a.dir,
1145                force: a.force,
1146                json,
1147            },
1148            Self::Operator(a) => NewArgs {
1149                kind: NewKind::Operator,
1150                name: a.name,
1151                lang: a.lang,
1152                dir: a.dir,
1153                force: a.force,
1154                json,
1155            },
1156            Self::OperatorDylib(a) => NewArgs {
1157                kind: NewKind::OperatorDylib,
1158                name: a.name,
1159                lang: a.lang,
1160                dir: a.dir,
1161                force: a.force,
1162                json,
1163            },
1164            Self::Graph(a) => NewArgs {
1165                kind: NewKind::Graph,
1166                name: a.name,
1167                lang: NewLang::Rust,
1168                dir: a.dir,
1169                force: a.force,
1170                json,
1171            },
1172        }
1173    }
1174}
1175
1176/// `astrs migrate` subcommands.
1177#[derive(Debug, Subcommand)]
1178pub enum MigrateCommand {
1179    /// Migrate a dora-rs dataflow descriptor.
1180    FromDora(FromDoraCliArgs),
1181    /// Skim a ROS 2 launch file into a bridge manifest scaffold.
1182    FromRos2(FromRos2CliArgs),
1183}
1184
1185/// `astrs migrate from-dora` arguments.
1186#[derive(Debug, Args)]
1187pub struct FromDoraCliArgs {
1188    /// The dora dataflow descriptor to migrate.
1189    pub input: PathBuf,
1190    /// Write the migrated manifest here instead of stdout.
1191    #[arg(long)]
1192    pub output: Option<PathBuf>,
1193}
1194
1195/// `astrs migrate from-ros2` arguments.
1196#[derive(Debug, Args)]
1197pub struct FromRos2CliArgs {
1198    /// The ROS 2 launch file to skim (`.xml`/`.launch.xml`, or `.py` for
1199    /// a best-effort, unverified Python skim -- dispatched by extension).
1200    pub input: PathBuf,
1201    /// Write the migrated manifest here instead of stdout.
1202    #[arg(long)]
1203    pub output: Option<PathBuf>,
1204}
1205
1206/// `astrs doctor` arguments.
1207#[derive(Debug, Args)]
1208pub struct DoctorCliArgs {
1209    /// The coordinator port to probe.
1210    #[arg(long, default_value_t = crate::command::doctor::DEFAULT_COORDINATOR_PORT)]
1211    pub coordinator_port: u16,
1212    /// The local daemon port to probe.
1213    #[arg(long, default_value_t = crate::command::doctor::DEFAULT_DAEMON_PORT)]
1214    pub daemon_port: u16,
1215}
1216
1217/// `astrs completion` arguments.
1218#[derive(Debug, Args)]
1219pub struct CompletionCliArgs {
1220    /// The shell to generate a completion script for.
1221    #[arg(value_enum)]
1222    pub shell: CompletionShell,
1223}
1224
1225/// `astrs schema` arguments.
1226#[derive(Debug, Args)]
1227pub struct SchemaCliArgs {
1228    /// Write the schema to this file instead of stdout.
1229    #[arg(long)]
1230    pub output: Option<PathBuf>,
1231}
1232
1233// =========================================================================
1234// Token scopes (blueprint §16, §22)
1235// =========================================================================
1236
1237/// `astrs token` subcommands.
1238#[derive(Debug, Subcommand)]
1239pub enum TokenCommand {
1240    /// Derive (or reveal) the credential for one scope of the cluster's
1241    /// root token.
1242    Mint(TokenMintArgs),
1243}
1244
1245/// `astrs token mint` arguments.
1246///
1247/// Unlike every other verb group in this file, minting never dials a
1248/// coordinator: it only needs the root secret already on this machine (the
1249/// same `--token`/`--token-file`/`--working-dir` resolution every
1250/// coordinator-facing verb uses, via [`crate::runtime_dir::find_token`]),
1251/// and the scope derivation is a pure function of it
1252/// (`astrs_coordinator::auth::derive_read_token`) — so it takes no
1253/// [`ConnectArgs`].
1254#[derive(Debug, Args)]
1255pub struct TokenMintArgs {
1256    /// The scope to mint a credential for.
1257    #[arg(long, value_enum)]
1258    pub scope: TokenScopeArg,
1259    /// An explicit root token, instead of resolving one (§16). Prefer
1260    /// `--token-file`: an argument is visible in `ps`.
1261    #[arg(long)]
1262    pub token: Option<String>,
1263    /// Read the root token from this file instead of
1264    /// `<working-dir>/.astrs-token`.
1265    #[arg(long)]
1266    pub token_file: Option<PathBuf>,
1267    /// The directory `.astrs-token` is looked up in; defaults to the
1268    /// process's current directory (§16).
1269    #[arg(long)]
1270    pub working_dir: Option<PathBuf>,
1271    /// Write the minted credential to this file (mode `0600`) instead of
1272    /// printing it to stdout.
1273    #[arg(long)]
1274    pub out: Option<PathBuf>,
1275}
1276
1277/// The scope `astrs token mint --scope` accepts — this crate's own copy of
1278/// [`astrs_wire::RequestScope`] (blueprint §16), which sits below `clap` in
1279/// the layer stack and so cannot derive [`ValueEnum`] itself.
1280#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
1281#[value(rename_all = "kebab-case")]
1282pub enum TokenScopeArg {
1283    /// Observes the cluster; cannot start, stop, edit or destroy anything.
1284    Read,
1285    /// Full access — the root token itself (blueprint §16 back-compat: every
1286    /// token minted before 0.2 is this scope).
1287    Mutate,
1288}
1289
1290// =========================================================================
1291// Package hub (blueprint §22)
1292// =========================================================================
1293
1294/// `astrs hub` subcommands.
1295#[derive(Debug, Subcommand)]
1296pub enum HubCommand {
1297    /// Clone (or fast-forward pull) the package index into the local
1298    /// cache.
1299    Update(HubUpdateArgs),
1300    /// List packages in the local index whose name or description matches
1301    /// a term.
1302    Search(HubSearchArgs),
1303    /// Show one package's description and every published version.
1304    Info(HubInfoArgs),
1305    /// Scaffold a valid, self-hostable index repo layout.
1306    Init(HubInitArgs),
1307}
1308
1309/// `astrs hub update` arguments.
1310///
1311/// Like `astrs token mint`, this never dials a coordinator: it clones or
1312/// pulls a git repository directly (blueprint §2.2: the system `git`
1313/// binary, never `git2`/`libgit2`).
1314#[derive(Debug, Args)]
1315pub struct HubUpdateArgs {
1316    /// Use this index URL instead of resolving one from
1317    /// `ASTRS_HUB_INDEX`, the config file, or the built-in default.
1318    #[arg(long)]
1319    pub index: Option<String>,
1320}
1321
1322/// `astrs hub search` arguments.
1323#[derive(Debug, Args)]
1324pub struct HubSearchArgs {
1325    /// Matched case-insensitively against a package's name or
1326    /// description.
1327    pub term: String,
1328}
1329
1330/// `astrs hub info` arguments.
1331#[derive(Debug, Args)]
1332pub struct HubInfoArgs {
1333    /// The package name to show.
1334    pub name: String,
1335}
1336
1337/// `astrs hub init` arguments.
1338#[derive(Debug, Args)]
1339pub struct HubInitArgs {
1340    /// The directory to scaffold the index repo layout into.
1341    pub dir: PathBuf,
1342    /// Scaffold into a directory that already has other files in it.
1343    #[arg(long)]
1344    pub force: bool,
1345}
1346
1347// =========================================================================
1348// Hidden internals
1349// =========================================================================
1350
1351/// `astrs daemon` arguments (internal — spawned by `astrs up`, never run
1352/// by hand in ordinary use).
1353#[derive(Debug, Args)]
1354pub struct DaemonArgs {
1355    /// The coordinator address to register with.
1356    #[arg(long)]
1357    pub coordinator: Option<String>,
1358    /// This daemon's machine name (defaults to the local hostname).
1359    #[arg(long)]
1360    pub machine: Option<String>,
1361    /// The loopback TCP port node processes may dial as a UDS fallback
1362    /// (§4.2); `0` binds a free one, and omitting it opens no TCP port.
1363    #[arg(long)]
1364    pub port: Option<u16>,
1365    /// The TCP port other *daemons* dial for cross-machine data routes
1366    /// (§6.4); `0` binds a free one. Only opened when `--coordinator` is
1367    /// given, because a daemon nobody was told about has opened a hole for
1368    /// nothing.
1369    #[arg(long, default_value_t = astrs_daemon::peer::DEFAULT_PEER_PORT)]
1370    pub peer_port: u16,
1371    /// The interface the peer listener binds; defaults to loopback, exactly
1372    /// as the coordinator's own `--bind` does and for the same §16 reason.
1373    #[arg(long)]
1374    pub peer_bind: Option<String>,
1375    /// A placement label, repeatable: `--label zone=front --label gpu=yes`
1376    /// (§8.3 `deploy`).
1377    #[arg(long = "label", value_name = "KEY=VALUE")]
1378    pub labels: Vec<String>,
1379    /// Where the node socket and captured logs live (§24.2).
1380    #[arg(long)]
1381    pub runtime_dir: Option<PathBuf>,
1382    /// The directory node paths resolve against.
1383    #[arg(long)]
1384    pub working_dir: Option<PathBuf>,
1385    /// The 64-hex cluster token every node must present (§16).
1386    #[arg(long)]
1387    pub token: Option<String>,
1388    /// Read that token from this file instead of
1389    /// `<working-dir>/.astrs-token`.
1390    #[arg(long)]
1391    pub token_file: Option<PathBuf>,
1392    /// Write this process's pid here once the listeners are bound, so
1393    /// `astrs down` and `astrs status` can find it.
1394    #[arg(long)]
1395    pub pidfile: Option<PathBuf>,
1396    /// Print the bound addresses as one JSON line on stdout once ready —
1397    /// how `astrs up` learns a `--port 0` daemon's real port.
1398    #[arg(long)]
1399    pub announce: bool,
1400}
1401
1402/// `astrs coordinator` arguments (internal — the one process `astrs up`
1403/// starts first).
1404#[derive(Debug, Args)]
1405pub struct CoordinatorArgs {
1406    /// The TCP port to listen on; `0` binds a free one.
1407    #[arg(long, default_value_t = crate::command::doctor::DEFAULT_COORDINATOR_PORT)]
1408    pub port: u16,
1409    /// The address to bind; defaults to loopback.
1410    #[arg(long)]
1411    pub bind: Option<String>,
1412    /// The 64-hex cluster token every peer must present (§16).
1413    #[arg(long)]
1414    pub token: Option<String>,
1415    /// Read that token from this file instead of
1416    /// `<working-dir>/.astrs-token`.
1417    #[arg(long)]
1418    pub token_file: Option<PathBuf>,
1419    /// The directory holding `.astrs-token` (§16).
1420    #[arg(long)]
1421    pub working_dir: Option<PathBuf>,
1422    /// The parameter/state store's directory; an in-memory store is used
1423    /// when omitted.
1424    #[arg(long)]
1425    pub store: Option<PathBuf>,
1426    /// Delete `--store` before opening it.
1427    #[arg(long)]
1428    pub recreate_store: bool,
1429    /// Write this process's pid here once the listener is bound.
1430    #[arg(long)]
1431    pub pidfile: Option<PathBuf>,
1432    /// Print the bound address as one JSON line on stdout once ready —
1433    /// how `astrs up` learns a `--port 0` coordinator's real port.
1434    #[arg(long)]
1435    pub announce: bool,
1436    /// This coordinator's Raft peer id within a replicated set (§22).
1437    /// Requires at least one `--ha-peer`, and the id must appear in it.
1438    #[arg(long)]
1439    pub ha_node_id: Option<u64>,
1440    /// One coordinator in the replicated set, as `id=host:port` (§22).
1441    /// Repeat once per coordinator, including this one; every coordinator in
1442    /// the set is given the identical list.
1443    #[arg(long = "ha-peer")]
1444    pub ha_peers: Vec<String>,
1445}
1446
1447/// `astrs runtime` arguments (internal — spawned by a daemon for a
1448/// manifest node whose source is `operators:`).
1449#[derive(Debug, Args)]
1450pub struct RuntimeArgs {
1451    /// The node id (within its dataflow) this runtime process hosts
1452    /// operators for. Advisory: the authoritative id arrives in the
1453    /// `ASTRS_NODE_CONFIG` handshake blob, and a mismatch is refused.
1454    #[arg(long)]
1455    pub node_id: Option<String>,
1456}
1457
1458#[cfg(test)]
1459mod tests {
1460    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1461    use super::*;
1462    use clap::CommandFactory;
1463
1464    #[test]
1465    fn cli_tree_is_valid_per_clap_debug_assert() {
1466        // `clap::Command::debug_assert` runs every internal consistency
1467        // check clap has (duplicate arg ids, conflicting short flags,
1468        // ...) without needing to actually parse anything.
1469        Cli::command().debug_assert();
1470    }
1471
1472    #[test]
1473    fn the_coordinator_takes_a_repeated_ha_peer_flag() {
1474        // Every coordinator in a replicated set is given the identical peer
1475        // list; only `--ha-node-id` differs per machine (blueprint §22).
1476        let cli = Cli::try_parse_from([
1477            "astrs",
1478            "coordinator",
1479            "--ha-node-id",
1480            "2",
1481            "--ha-peer",
1482            "1=10.0.0.1:7601",
1483            "--ha-peer",
1484            "2=10.0.0.2:7601",
1485            "--ha-peer",
1486            "3=10.0.0.3:7601",
1487        ])
1488        .unwrap();
1489        let Command::Coordinator(args) = cli.command else {
1490            panic!("expected `coordinator`");
1491        };
1492        assert_eq!(args.ha_node_id, Some(2));
1493        assert_eq!(args.ha_peers.len(), 3);
1494        assert_eq!(args.ha_peers[0], "1=10.0.0.1:7601");
1495    }
1496
1497    #[test]
1498    fn the_coordinator_still_parses_without_any_ha_flags() {
1499        let cli = Cli::try_parse_from(["astrs", "coordinator"]).unwrap();
1500        let Command::Coordinator(args) = cli.command else {
1501            panic!("expected `coordinator`");
1502        };
1503        assert!(args.ha_node_id.is_none());
1504        assert!(args.ha_peers.is_empty());
1505    }
1506
1507    #[test]
1508    fn binary_name_is_astrs() {
1509        assert_eq!(Cli::command().get_name(), "astrs");
1510    }
1511
1512    #[test]
1513    fn json_and_color_are_global_flags() {
1514        let cli = Cli::try_parse_from(["astrs", "--json", "schema"]).unwrap();
1515        assert!(cli.json);
1516        let cli = Cli::try_parse_from(["astrs", "schema", "--json"]).unwrap();
1517        assert!(cli.json, "global flags must also work after the subcommand");
1518    }
1519
1520    #[test]
1521    fn token_mint_parses_its_scope() {
1522        let cli = Cli::try_parse_from(["astrs", "token", "mint", "--scope", "read"]).unwrap();
1523        let Command::Token(TokenCommand::Mint(args)) = cli.command else {
1524            panic!("expected `token mint`");
1525        };
1526        assert_eq!(args.scope, TokenScopeArg::Read);
1527
1528        let cli = Cli::try_parse_from(["astrs", "token", "mint", "--scope", "mutate"]).unwrap();
1529        let Command::Token(TokenCommand::Mint(args)) = cli.command else {
1530            panic!("expected `token mint`");
1531        };
1532        assert_eq!(args.scope, TokenScopeArg::Mutate);
1533    }
1534
1535    #[test]
1536    fn token_mint_requires_a_scope() {
1537        assert!(Cli::try_parse_from(["astrs", "token", "mint"]).is_err());
1538    }
1539
1540    #[test]
1541    fn validate_rejects_a_profile_without_prove() {
1542        assert!(
1543            Cli::try_parse_from(["astrs", "validate", "--profile", "v.yaml", "dataflow.yml"])
1544                .is_err(),
1545            "`--profile` only means something alongside `--prove`"
1546        );
1547    }
1548
1549    #[test]
1550    fn validate_parses_the_profile_flag() {
1551        let cli = Cli::try_parse_from([
1552            "astrs",
1553            "validate",
1554            "--prove",
1555            "--profile",
1556            "verify.yaml",
1557            "dataflow.yml",
1558        ])
1559        .unwrap();
1560        match cli.command {
1561            Command::Validate(args) => {
1562                assert!(args.prove);
1563                assert_eq!(
1564                    args.profile.as_deref(),
1565                    Some(std::path::Path::new("verify.yaml"))
1566                );
1567            }
1568            other => panic!("expected validate, got {other:?}"),
1569        }
1570    }
1571
1572    #[test]
1573    fn validate_parses_prove_flag() {
1574        let cli = Cli::try_parse_from(["astrs", "validate", "--prove", "dataflow.yml"]).unwrap();
1575        match cli.command {
1576            Command::Validate(args) => {
1577                assert!(args.prove);
1578                assert_eq!(args.manifest, PathBuf::from("dataflow.yml"));
1579            }
1580            other => panic!("expected Validate, got {other:?}"),
1581        }
1582    }
1583
1584    #[test]
1585    fn new_node_parses_with_defaults() {
1586        let cli = Cli::try_parse_from(["astrs", "new", "node", "my-node"]).unwrap();
1587        match cli.command {
1588            Command::New(NewCommand::Node(args)) => {
1589                assert_eq!(args.name, "my-node");
1590                assert_eq!(args.lang, NewLang::Rust);
1591                assert_eq!(args.dir, PathBuf::from("."));
1592                assert!(!args.force);
1593            }
1594            other => panic!("expected New(Node), got {other:?}"),
1595        }
1596    }
1597
1598    #[test]
1599    fn new_operator_dylib_parses_as_the_kebab_case_subcommand() {
1600        // `NewCommand`'s multi-word variants get clap's own default
1601        // kebab-case rendering (no `rename_all` override on the enum
1602        // itself — see `astrs migrate from-dora`'s identical precedent),
1603        // so `OperatorDylib` must parse as `operator-dylib`, not
1604        // `operatordylib` or `operator_dylib`.
1605        let cli = Cli::try_parse_from(["astrs", "new", "operator-dylib", "my-dylib-op"]).unwrap();
1606        match cli.command {
1607            Command::New(NewCommand::OperatorDylib(args)) => {
1608                assert_eq!(args.name, "my-dylib-op");
1609                assert_eq!(args.lang, NewLang::Rust);
1610                assert_eq!(args.dir, PathBuf::from("."));
1611                assert!(!args.force);
1612            }
1613            other => panic!("expected New(OperatorDylib), got {other:?}"),
1614        }
1615    }
1616
1617    #[test]
1618    fn migrate_from_dora_parses() {
1619        let cli = Cli::try_parse_from([
1620            "astrs",
1621            "migrate",
1622            "from-dora",
1623            "in.yml",
1624            "--output",
1625            "out.yml",
1626        ])
1627        .unwrap();
1628        match cli.command {
1629            Command::Migrate(MigrateCommand::FromDora(args)) => {
1630                assert_eq!(args.input, PathBuf::from("in.yml"));
1631                assert_eq!(args.output, Some(PathBuf::from("out.yml")));
1632            }
1633            other => panic!("expected Migrate(FromDora), got {other:?}"),
1634        }
1635    }
1636
1637    #[test]
1638    fn migrate_from_ros2_parses() {
1639        let cli = Cli::try_parse_from([
1640            "astrs",
1641            "migrate",
1642            "from-ros2",
1643            "in.launch.xml",
1644            "--output",
1645            "out.yml",
1646        ])
1647        .unwrap();
1648        match cli.command {
1649            Command::Migrate(MigrateCommand::FromRos2(args)) => {
1650                assert_eq!(args.input, PathBuf::from("in.launch.xml"));
1651                assert_eq!(args.output, Some(PathBuf::from("out.yml")));
1652            }
1653            other => panic!("expected Migrate(FromRos2), got {other:?}"),
1654        }
1655    }
1656
1657    #[test]
1658    fn every_daemon_needing_verb_still_parses() {
1659        // "present with real arg schemas" -- every verb blueprint §17 lists
1660        // must parse, whether it is implemented here or scheduled for a
1661        // later wave (see `command::stub`).
1662        let lines: &[&[&str]] = &[
1663            &["astrs", "run", "d.yml"],
1664            &["astrs", "up"],
1665            &["astrs", "down"],
1666            &["astrs", "build", "d.yml"],
1667            &["astrs", "start", "d.yml"],
1668            &["astrs", "stop", "my-flow"],
1669            &["astrs", "restart", "my-flow"],
1670            &["astrs", "destroy", "my-flow"],
1671            &["astrs", "clean"],
1672            &["astrs", "list"],
1673            &["astrs", "logs"],
1674            &["astrs", "top"],
1675            &["astrs", "topic", "echo", "cam/frames"],
1676            &["astrs", "topic", "hz", "cam/frames"],
1677            &["astrs", "topic", "info", "cam/frames"],
1678            &["astrs", "topic", "pub", "cam/frames", "{}"],
1679            &["astrs", "status"],
1680            &["astrs", "trace"],
1681            &["astrs", "node", "remove", "my-flow", "cam"],
1682            &["astrs", "param", "list", "my-flow"],
1683            &["astrs", "record", "stop", "my-flow"],
1684            &["astrs", "replay", "r.arec"],
1685            &["astrs", "bag", "info", "b.mcap"],
1686            &["astrs", "ros2", "doctor"],
1687            &["astrs", "ros2", "topics"],
1688            &["astrs", "daemon"],
1689            &["astrs", "coordinator"],
1690            &["astrs", "runtime", "--node-id", "cam"],
1691        ];
1692        for argv in lines {
1693            Cli::try_parse_from(*argv).unwrap_or_else(|e| panic!("{argv:?} failed to parse: {e}"));
1694        }
1695    }
1696
1697    #[test]
1698    fn every_client_verb_takes_the_same_connect_flags() {
1699        // `ConnectArgs` is flattened rather than repeated, so this asserts
1700        // the flattening actually reached each verb — a `#[command(flatten)]`
1701        // left off one of them would not fail to compile.
1702        for verb in [
1703            &["astrs", "list"][..],
1704            &["astrs", "logs"][..],
1705            &["astrs", "stop", "f"][..],
1706            &["astrs", "restart", "f"][..],
1707            &["astrs", "destroy"][..],
1708            &["astrs", "clean"][..],
1709            &["astrs", "start", "d.yml"][..],
1710            &["astrs", "status"][..],
1711            &["astrs", "up"][..],
1712            &["astrs", "down"][..],
1713            &["astrs", "top"][..],
1714        ] {
1715            let mut argv: Vec<&str> = verb.to_vec();
1716            argv.extend(["--coordinator", "127.0.0.1:7407", "--token", "ab"]);
1717            Cli::try_parse_from(&argv).unwrap_or_else(|e| panic!("{argv:?} failed to parse: {e}"));
1718        }
1719    }
1720
1721    #[test]
1722    fn top_parses_the_replay_flag() {
1723        let cli = Cli::try_parse_from(["astrs", "top", "--replay", "session.arec"]).unwrap();
1724        match cli.command {
1725            Command::Top(args) => {
1726                assert_eq!(args.replay, Some(PathBuf::from("session.arec")));
1727            }
1728            other => panic!("expected Command::Top, got {other:?}"),
1729        }
1730    }
1731
1732    #[test]
1733    fn top_without_replay_defaults_to_live() {
1734        let cli = Cli::try_parse_from(["astrs", "top"]).unwrap();
1735        match cli.command {
1736            Command::Top(args) => assert_eq!(args.replay, None),
1737            other => panic!("expected Command::Top, got {other:?}"),
1738        }
1739    }
1740
1741    #[test]
1742    fn run_parses_its_stage_two_flags() {
1743        let cli = Cli::try_parse_from([
1744            "astrs",
1745            "run",
1746            "d.yml",
1747            "--skip-build",
1748            "--level",
1749            "warn",
1750            "--timeout",
1751            "2.5",
1752            "--exit-when-nodes-finish",
1753        ])
1754        .unwrap();
1755        match cli.command {
1756            Command::Run(args) => {
1757                assert!(args.skip_build);
1758                assert!(args.exit_when_nodes_finish);
1759                assert_eq!(args.level.as_deref(), Some("warn"));
1760                assert_eq!(args.timeout, Some(2.5));
1761                assert!(!args.deterministic);
1762                assert_eq!(args.from_recording, None);
1763                assert_eq!(args.speed, None);
1764            }
1765            other => panic!("expected Run, got {other:?}"),
1766        }
1767    }
1768
1769    #[test]
1770    fn run_parses_deterministic_replay_flags() {
1771        let cli = Cli::try_parse_from([
1772            "astrs",
1773            "run",
1774            "d.yml",
1775            "--deterministic",
1776            "--from-recording",
1777            "session.arec",
1778            "--speed",
1779            "2.0",
1780        ])
1781        .unwrap();
1782        match cli.command {
1783            Command::Run(args) => {
1784                assert!(args.deterministic);
1785                assert_eq!(args.from_recording, Some(PathBuf::from("session.arec")));
1786                assert_eq!(args.speed, Some(2.0));
1787            }
1788            other => panic!("expected Run, got {other:?}"),
1789        }
1790    }
1791
1792    #[test]
1793    fn up_takes_no_manifest_because_it_brings_up_a_cluster() {
1794        // Blueprint §17 groups `up`/`down` under *cluster* lifecycle;
1795        // dataflows are started with `astrs start`.
1796        assert!(Cli::try_parse_from(["astrs", "up", "d.yml"]).is_err());
1797        let cli = Cli::try_parse_from(["astrs", "up", "--recreate-store", "--port", "0"]).unwrap();
1798        match cli.command {
1799            Command::Up(args) => {
1800                assert!(args.recreate_store);
1801                assert_eq!(args.port, Some(0));
1802                assert!(!args.no_daemon);
1803            }
1804            other => panic!("expected Up, got {other:?}"),
1805        }
1806    }
1807
1808    #[test]
1809    fn hidden_commands_are_marked_hidden() {
1810        let command = Cli::command();
1811        for name in ["daemon", "coordinator", "runtime"] {
1812            let sub = command
1813                .find_subcommand(name)
1814                .unwrap_or_else(|| panic!("missing subcommand {name}"));
1815            assert!(sub.is_hide_set(), "`{name}` should be hidden");
1816        }
1817        // A visible command, as a control.
1818        assert!(!command.find_subcommand("validate").unwrap().is_hide_set());
1819    }
1820
1821    #[test]
1822    fn graph_format_arg_maps_onto_graph_format() {
1823        assert_eq!(
1824            GraphFormat::from(GraphFormatArg::Mermaid),
1825            GraphFormat::Mermaid
1826        );
1827        assert_eq!(GraphFormat::from(GraphFormatArg::Dot), GraphFormat::Dot);
1828        assert_eq!(GraphFormat::from(GraphFormatArg::Html), GraphFormat::Html);
1829    }
1830
1831    #[test]
1832    fn new_command_flattens_into_new_args() {
1833        let cli = Cli::try_parse_from(["astrs", "new", "graph", "perception"]).unwrap();
1834        let Command::New(new_command) = cli.command else {
1835            panic!("expected New");
1836        };
1837        let args = new_command.into_new_args(false);
1838        assert_eq!(args.kind, NewKind::Graph);
1839        assert_eq!(args.name, "perception");
1840        assert!(!args.json);
1841    }
1842
1843    #[test]
1844    fn new_command_threads_the_global_json_flag_through() {
1845        let cli = Cli::try_parse_from(["astrs", "--json", "new", "node", "cam"]).unwrap();
1846        let Command::New(new_command) = cli.command else {
1847            panic!("expected New");
1848        };
1849        let args = new_command.into_new_args(cli.json);
1850        assert!(args.json);
1851    }
1852}