rhi

Coordinated trade for connected markets
git clone https://radroots.dev/git/rhi.git
Log | Files | Refs | README | LICENSE

cli_v1.rs (48585B)


      1 //! One-pass command-line admission for the hardened RHI command contract.
      2 
      3 use std::error::Error;
      4 use std::ffi::OsString;
      5 use std::fmt;
      6 use std::path::{Component, Path, PathBuf};
      7 
      8 use clap::{Parser, Subcommand, ValueEnum};
      9 use radroots_runtime_paths::InstanceId;
     10 
     11 /// The exact bootstrap profile selected by the operator.
     12 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
     13 pub enum RhiBootstrapProfileV1 {
     14     ServiceHost,
     15     Interactive,
     16     RepoLocal,
     17 }
     18 
     19 /// The only two governed command-result encodings.
     20 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
     21 pub enum RhiCliOutputModeV1 {
     22     #[default]
     23     Human,
     24     Json,
     25 }
     26 
     27 /// The exact governed top-level RHI command inventory.
     28 #[derive(PartialEq, Eq)]
     29 pub enum RhiCommandV1 {
     30     Run,
     31     Config(RhiConfigCommandV1),
     32     State(RhiStateCommandV1),
     33     Identity(RhiIdentityCommandV1),
     34     Status,
     35     Metrics(RhiMetricsCommandV1),
     36     Reconciliation(RhiReconciliationCommandV1),
     37     Sources(RhiSourcesCommandV1),
     38     Trade(RhiTradeCommandV1),
     39     Publication(RhiPublicationCommandV1),
     40     Presence(RhiPresenceCommandV1),
     41     Doctor,
     42 }
     43 
     44 /// Governed configuration commands.
     45 #[derive(PartialEq, Eq)]
     46 pub enum RhiConfigCommandV1 {
     47     Init,
     48     Validate,
     49     Show,
     50     Schema,
     51     Apply(RhiConfigApplyArgsV1),
     52 }
     53 
     54 /// Governed state commands.
     55 #[derive(PartialEq, Eq)]
     56 pub enum RhiStateCommandV1 {
     57     Init,
     58     Status,
     59     Backup(RhiStateBackupArgsV1),
     60     Restore(RhiStateRestoreArgsV1),
     61     Verify,
     62     Migrate,
     63 }
     64 
     65 /// Governed service-identity commands.
     66 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
     67 pub enum RhiIdentityCommandV1 {
     68     Init,
     69     Status,
     70     ExportPublic,
     71 }
     72 
     73 /// Governed metrics commands.
     74 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
     75 pub enum RhiMetricsCommandV1 {
     76     Snapshot,
     77 }
     78 
     79 /// Governed reconciliation commands.
     80 #[derive(PartialEq, Eq)]
     81 pub enum RhiReconciliationCommandV1 {
     82     Status,
     83     Jobs(RhiPageQueryArgsV1),
     84     Refresh(RhiReconciliationRefreshArgsV1),
     85 }
     86 
     87 /// Governed evidence-source commands.
     88 #[derive(PartialEq, Eq)]
     89 pub enum RhiSourcesCommandV1 {
     90     List(RhiPageQueryArgsV1),
     91 }
     92 
     93 /// Governed trade-query commands.
     94 #[derive(PartialEq, Eq)]
     95 pub enum RhiTradeCommandV1 {
     96     Projection(RhiTradeArgsV1),
     97     ReportCurrent(RhiTradeArgsV1),
     98     Reports(RhiTradePageArgsV1),
     99 }
    100 
    101 /// Governed publication commands.
    102 #[derive(PartialEq, Eq)]
    103 pub enum RhiPublicationCommandV1 {
    104     Backlog(RhiPageQueryArgsV1),
    105     Targets(RhiPageQueryArgsV1),
    106     Retry(RhiPublicationRetryArgsV1),
    107 }
    108 
    109 /// Governed desired-presence commands.
    110 #[derive(PartialEq, Eq)]
    111 pub enum RhiPresenceCommandV1 {
    112     Desired,
    113     Render(RhiPresenceMutationArgsV1),
    114     Refresh(RhiPresenceMutationArgsV1),
    115 }
    116 
    117 /// Exact offline configuration-apply input.
    118 #[derive(PartialEq, Eq)]
    119 pub struct RhiConfigApplyArgsV1 {
    120     candidate_config: PathBuf,
    121 }
    122 
    123 impl RhiConfigApplyArgsV1 {
    124     #[must_use]
    125     pub fn candidate_config(&self) -> &Path {
    126         &self.candidate_config
    127     }
    128 }
    129 
    130 /// Exact live state-backup input.
    131 #[derive(PartialEq, Eq)]
    132 pub struct RhiStateBackupArgsV1 {
    133     operation_id: Box<str>,
    134     target: PathBuf,
    135     expected_generation: u64,
    136 }
    137 
    138 impl RhiStateBackupArgsV1 {
    139     #[must_use]
    140     pub fn operation_id(&self) -> &str {
    141         &self.operation_id
    142     }
    143 
    144     #[must_use]
    145     pub fn target(&self) -> &Path {
    146         &self.target
    147     }
    148 
    149     #[must_use]
    150     pub const fn expected_generation(&self) -> u64 {
    151         self.expected_generation
    152     }
    153 }
    154 
    155 /// Exact offline state-restore input.
    156 #[derive(PartialEq, Eq)]
    157 pub struct RhiStateRestoreArgsV1 {
    158     manifest: PathBuf,
    159     manifest_sha256: Box<str>,
    160     bundle: PathBuf,
    161     maximum_state_bytes: u64,
    162 }
    163 
    164 impl RhiStateRestoreArgsV1 {
    165     #[must_use]
    166     pub fn manifest(&self) -> &Path {
    167         &self.manifest
    168     }
    169 
    170     #[must_use]
    171     pub fn manifest_sha256(&self) -> &str {
    172         &self.manifest_sha256
    173     }
    174 
    175     #[must_use]
    176     pub fn bundle(&self) -> &Path {
    177         &self.bundle
    178     }
    179 
    180     #[must_use]
    181     pub const fn maximum_state_bytes(&self) -> u64 {
    182         self.maximum_state_bytes
    183     }
    184 }
    185 
    186 /// Bounded stable pagination input shared by list commands.
    187 #[derive(PartialEq, Eq)]
    188 pub struct RhiPageQueryArgsV1 {
    189     limit: u16,
    190     cursor: Option<Box<str>>,
    191 }
    192 
    193 impl RhiPageQueryArgsV1 {
    194     #[must_use]
    195     pub const fn limit(&self) -> u16 {
    196         self.limit
    197     }
    198 
    199     #[must_use]
    200     pub fn cursor(&self) -> Option<&str> {
    201         self.cursor.as_deref()
    202     }
    203 }
    204 
    205 /// Exact trade selection for one live query.
    206 #[derive(PartialEq, Eq)]
    207 pub struct RhiTradeArgsV1 {
    208     trade_id: Box<str>,
    209 }
    210 
    211 impl RhiTradeArgsV1 {
    212     #[must_use]
    213     pub fn trade_id(&self) -> &str {
    214         &self.trade_id
    215     }
    216 }
    217 
    218 /// Exact trade selection plus bounded report pagination.
    219 #[derive(PartialEq, Eq)]
    220 pub struct RhiTradePageArgsV1 {
    221     trade_id: Box<str>,
    222     page: RhiPageQueryArgsV1,
    223 }
    224 
    225 impl RhiTradePageArgsV1 {
    226     #[must_use]
    227     pub fn trade_id(&self) -> &str {
    228         &self.trade_id
    229     }
    230 
    231     #[must_use]
    232     pub const fn page(&self) -> &RhiPageQueryArgsV1 {
    233         &self.page
    234     }
    235 }
    236 
    237 /// Exact refresh request and idempotency identity.
    238 #[derive(PartialEq, Eq)]
    239 pub struct RhiReconciliationRefreshArgsV1 {
    240     operation_id: Box<str>,
    241     trade_id: Box<str>,
    242     expected_dirty_generation: u64,
    243 }
    244 
    245 impl RhiReconciliationRefreshArgsV1 {
    246     #[must_use]
    247     pub fn operation_id(&self) -> &str {
    248         &self.operation_id
    249     }
    250 
    251     #[must_use]
    252     pub fn trade_id(&self) -> &str {
    253         &self.trade_id
    254     }
    255 
    256     #[must_use]
    257     pub const fn expected_dirty_generation(&self) -> u64 {
    258         self.expected_dirty_generation
    259     }
    260 }
    261 
    262 /// Exact publication retry request and idempotency identity.
    263 #[derive(PartialEq, Eq)]
    264 pub struct RhiPublicationRetryArgsV1 {
    265     operation_id: Box<str>,
    266     workflow_id: Box<str>,
    267     expected_generation: u64,
    268 }
    269 
    270 impl RhiPublicationRetryArgsV1 {
    271     #[must_use]
    272     pub fn operation_id(&self) -> &str {
    273         &self.operation_id
    274     }
    275 
    276     #[must_use]
    277     pub fn workflow_id(&self) -> &str {
    278         &self.workflow_id
    279     }
    280 
    281     #[must_use]
    282     pub const fn expected_generation(&self) -> u64 {
    283         self.expected_generation
    284     }
    285 }
    286 
    287 /// Exact presence mutation request and idempotency identity.
    288 #[derive(PartialEq, Eq)]
    289 pub struct RhiPresenceMutationArgsV1 {
    290     operation_id: Box<str>,
    291     expected_generation: u64,
    292 }
    293 
    294 impl RhiPresenceMutationArgsV1 {
    295     #[must_use]
    296     pub fn operation_id(&self) -> &str {
    297         &self.operation_id
    298     }
    299 
    300     #[must_use]
    301     pub const fn expected_generation(&self) -> u64 {
    302         self.expected_generation
    303     }
    304 }
    305 
    306 macro_rules! redacted_debug {
    307     ($($type:ty),+ $(,)?) => {
    308         $(
    309             impl fmt::Debug for $type {
    310                 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    311                     formatter.write_str(concat!(stringify!($type), "([redacted])"))
    312                 }
    313             }
    314         )+
    315     };
    316 }
    317 
    318 redacted_debug!(
    319     RhiConfigApplyArgsV1,
    320     RhiStateBackupArgsV1,
    321     RhiStateRestoreArgsV1,
    322     RhiPageQueryArgsV1,
    323     RhiTradeArgsV1,
    324     RhiTradePageArgsV1,
    325     RhiReconciliationRefreshArgsV1,
    326     RhiPublicationRetryArgsV1,
    327     RhiPresenceMutationArgsV1,
    328 );
    329 
    330 impl fmt::Debug for RhiCommandV1 {
    331     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    332         formatter.write_str(match self {
    333             Self::Run => "RhiCommandV1::Run",
    334             Self::Config(_) => "RhiCommandV1::Config([redacted])",
    335             Self::State(_) => "RhiCommandV1::State([redacted])",
    336             Self::Identity(_) => "RhiCommandV1::Identity([redacted])",
    337             Self::Status => "RhiCommandV1::Status",
    338             Self::Metrics(_) => "RhiCommandV1::Metrics([redacted])",
    339             Self::Reconciliation(_) => "RhiCommandV1::Reconciliation([redacted])",
    340             Self::Sources(_) => "RhiCommandV1::Sources([redacted])",
    341             Self::Trade(_) => "RhiCommandV1::Trade([redacted])",
    342             Self::Publication(_) => "RhiCommandV1::Publication([redacted])",
    343             Self::Presence(_) => "RhiCommandV1::Presence([redacted])",
    344             Self::Doctor => "RhiCommandV1::Doctor",
    345         })
    346     }
    347 }
    348 
    349 /// The only three process authorities selected by the hardened CLI.
    350 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    351 pub enum RhiCliPrimaryAuthorityV1 {
    352     Daemon,
    353     Offline,
    354     LiveUnixAdmin,
    355 }
    356 
    357 /// The closed offline operation classes selected before any state access.
    358 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    359 pub enum RhiCliOfflineOperationV1 {
    360     Config,
    361     StateExclusive,
    362     IdentityExclusive,
    363     Doctor,
    364 }
    365 
    366 /// The closed Unix-admin operations reachable from the command inventory.
    367 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    368 pub enum RhiCliAdminOperationV1 {
    369     Status,
    370     EffectiveConfig,
    371     IdentityStatus,
    372     IdentityPublic,
    373     StateStatus,
    374     StateBackup,
    375     MetricsSnapshot,
    376     ReconciliationStatus,
    377     ReconciliationJobs,
    378     ReconciliationRefresh,
    379     Sources,
    380     TradeProjection,
    381     TradeReportCurrent,
    382     TradeReports,
    383     PublicationBacklog,
    384     PublicationTargets,
    385     PublicationRetry,
    386     PresenceDesired,
    387     PresenceRender,
    388     PresenceRefresh,
    389 }
    390 
    391 #[cfg(any(target_os = "linux", target_os = "macos"))]
    392 impl RhiCliAdminOperationV1 {
    393     /// Returns the exact native Unix-admin route selected by this operation.
    394     #[must_use]
    395     pub const fn route(self) -> crate::RhiAdminRoute {
    396         match self {
    397             Self::Status => crate::RhiAdminRoute::Status,
    398             Self::EffectiveConfig => crate::RhiAdminRoute::EffectiveConfig,
    399             Self::IdentityStatus => crate::RhiAdminRoute::IdentityStatus,
    400             Self::IdentityPublic => crate::RhiAdminRoute::IdentityPublic,
    401             Self::StateStatus => crate::RhiAdminRoute::StateStatus,
    402             Self::StateBackup => crate::RhiAdminRoute::StateBackup,
    403             Self::MetricsSnapshot => crate::RhiAdminRoute::MetricsSnapshot,
    404             Self::ReconciliationStatus => crate::RhiAdminRoute::ReconciliationStatus,
    405             Self::ReconciliationJobs => crate::RhiAdminRoute::ReconciliationJobs,
    406             Self::ReconciliationRefresh => crate::RhiAdminRoute::ReconciliationRefresh,
    407             Self::Sources => crate::RhiAdminRoute::Sources,
    408             Self::TradeProjection => crate::RhiAdminRoute::TradeProjection,
    409             Self::TradeReportCurrent => crate::RhiAdminRoute::TradeReportCurrent,
    410             Self::TradeReports => crate::RhiAdminRoute::TradeReports,
    411             Self::PublicationBacklog => crate::RhiAdminRoute::PublicationBacklog,
    412             Self::PublicationTargets => crate::RhiAdminRoute::PublicationTargets,
    413             Self::PublicationRetry => crate::RhiAdminRoute::PublicationRetry,
    414             Self::PresenceDesired => crate::RhiAdminRoute::PresenceDesired,
    415             Self::PresenceRender => crate::RhiAdminRoute::PresenceRender,
    416             Self::PresenceRefresh => crate::RhiAdminRoute::PresenceRefresh,
    417         }
    418     }
    419 }
    420 
    421 /// A sealed, side-effect-free execution plan for one admitted CLI invocation.
    422 ///
    423 /// Construction is owned by [`plan_rhi_cli_v1`]. Live commands carry only a
    424 /// governed Unix-admin operation and never receive an offline or direct-SQLite
    425 /// fallback.
    426 ///
    427 /// ```compile_fail
    428 /// use rhi::{RhiCliExecutionPlanV1, RhiCliPrimaryAuthorityV1};
    429 ///
    430 /// let _ = RhiCliExecutionPlanV1 {
    431 ///     primary_authority: RhiCliPrimaryAuthorityV1::Offline,
    432 ///     offline_operation: None,
    433 ///     admin_operation: None,
    434 /// };
    435 /// ```
    436 #[derive(Clone, Copy, PartialEq, Eq)]
    437 pub struct RhiCliExecutionPlanV1 {
    438     primary_authority: RhiCliPrimaryAuthorityV1,
    439     offline_operation: Option<RhiCliOfflineOperationV1>,
    440     admin_operation: Option<RhiCliAdminOperationV1>,
    441 }
    442 
    443 impl RhiCliExecutionPlanV1 {
    444     /// Returns the sole selected process authority.
    445     #[must_use]
    446     pub const fn primary_authority(&self) -> RhiCliPrimaryAuthorityV1 {
    447         self.primary_authority
    448     }
    449 
    450     /// Returns the bounded offline operation, when the plan admits one.
    451     #[must_use]
    452     pub const fn offline_operation(&self) -> Option<RhiCliOfflineOperationV1> {
    453         self.offline_operation
    454     }
    455 
    456     /// Returns the bounded Unix-admin operation, when the plan admits one.
    457     #[must_use]
    458     pub const fn admin_operation(&self) -> Option<RhiCliAdminOperationV1> {
    459         self.admin_operation
    460     }
    461 }
    462 
    463 impl fmt::Debug for RhiCliExecutionPlanV1 {
    464     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    465         formatter
    466             .debug_struct("RhiCliExecutionPlanV1")
    467             .field("primary_authority", &self.primary_authority)
    468             .field("offline_operation", &self.offline_operation)
    469             .field("admin_operation", &self.admin_operation)
    470             .finish()
    471     }
    472 }
    473 
    474 /// Stable source-free classification for command-line admission failures.
    475 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    476 pub enum RhiCliV1ErrorKind {
    477     HelpRequested,
    478     InvalidArguments,
    479     InvalidInstance,
    480     InvalidRepoLocalRoot,
    481     UnexpectedRepoLocalRoot,
    482     InvalidConfigPath,
    483     InvalidCommandInput,
    484 }
    485 
    486 impl RhiCliV1ErrorKind {
    487     const fn message(self) -> &'static str {
    488         match self {
    489             Self::HelpRequested => "command-line help requested",
    490             Self::InvalidArguments => "command-line arguments are invalid",
    491             Self::InvalidInstance => "instance identifier is invalid",
    492             Self::InvalidRepoLocalRoot => "repo-local profile requires a valid absolute root",
    493             Self::UnexpectedRepoLocalRoot => {
    494                 "repo-local root is forbidden outside the repo-local profile"
    495             }
    496             Self::InvalidConfigPath => "configuration path must be absolute without traversal",
    497             Self::InvalidCommandInput => "command input is invalid",
    498         }
    499     }
    500 }
    501 
    502 /// One safe command-line admission outcome requiring process-level handling.
    503 #[derive(Clone, PartialEq, Eq)]
    504 pub struct RhiCliV1Error {
    505     kind: RhiCliV1ErrorKind,
    506     help_text: Option<Box<str>>,
    507 }
    508 
    509 impl RhiCliV1Error {
    510     const fn new(kind: RhiCliV1ErrorKind) -> Self {
    511         Self {
    512             kind,
    513             help_text: None,
    514         }
    515     }
    516 
    517     /// Returns the stable failure classification.
    518     #[must_use]
    519     pub const fn kind(&self) -> RhiCliV1ErrorKind {
    520         self.kind
    521     }
    522 
    523     /// Returns bounded static command help, without caller argument text.
    524     /// The process owner may print this on stdout and return success without
    525     /// executing a command. Display and Debug remain source-free diagnostics.
    526     #[must_use]
    527     pub fn help_text(&self) -> Option<&str> {
    528         self.help_text.as_deref()
    529     }
    530 }
    531 
    532 impl fmt::Debug for RhiCliV1Error {
    533     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    534         formatter
    535             .debug_struct("RhiCliV1Error")
    536             .field("kind", &self.kind)
    537             .finish()
    538     }
    539 }
    540 
    541 impl fmt::Display for RhiCliV1Error {
    542     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    543         formatter.write_str(self.kind.message())
    544     }
    545 }
    546 
    547 impl Error for RhiCliV1Error {}
    548 
    549 /// A validated one-pass RHI bootstrap and command selection.
    550 pub struct RhiCliInvocationV1 {
    551     profile: RhiBootstrapProfileV1,
    552     instance: InstanceId,
    553     repo_local_root: Option<PathBuf>,
    554     config_path: Option<PathBuf>,
    555     output_mode: RhiCliOutputModeV1,
    556     command: RhiCommandV1,
    557 }
    558 
    559 impl RhiCliInvocationV1 {
    560     /// Returns the explicitly selected bootstrap profile.
    561     #[must_use]
    562     pub const fn profile(&self) -> RhiBootstrapProfileV1 {
    563         self.profile
    564     }
    565 
    566     /// Returns the validated instance identifier.
    567     #[must_use]
    568     pub const fn instance(&self) -> &InstanceId {
    569         &self.instance
    570     }
    571 
    572     /// Returns the explicit repo-local root, when selected.
    573     #[must_use]
    574     pub fn repo_local_root(&self) -> Option<&Path> {
    575         self.repo_local_root.as_deref()
    576     }
    577 
    578     /// Returns the optional explicit configuration path.
    579     #[must_use]
    580     pub fn config_path(&self) -> Option<&Path> {
    581         self.config_path.as_deref()
    582     }
    583 
    584     /// Returns the selected human or governed machine-result encoding.
    585     #[must_use]
    586     pub const fn output_mode(&self) -> RhiCliOutputModeV1 {
    587         self.output_mode
    588     }
    589 
    590     /// Returns the exact governed command selection.
    591     #[must_use]
    592     pub const fn command(&self) -> &RhiCommandV1 {
    593         &self.command
    594     }
    595 }
    596 
    597 impl fmt::Debug for RhiCliInvocationV1 {
    598     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    599         formatter
    600             .debug_struct("RhiCliInvocationV1")
    601             .field("profile", &self.profile)
    602             .field("instance", &"[redacted]")
    603             .field(
    604                 "repo_local_root",
    605                 &self.repo_local_root.as_ref().map(|_| "[redacted]"),
    606             )
    607             .field(
    608                 "config_path",
    609                 &self.config_path.as_ref().map(|_| "[redacted]"),
    610             )
    611             .field("output_mode", &self.output_mode)
    612             .field("command", &self.command)
    613             .finish()
    614     }
    615 }
    616 
    617 /// Parses the exact hardened RHI bootstrap and command tree once.
    618 ///
    619 /// The iterator must include the program name as its first element. Clap's
    620 /// dependency-owned diagnostic is deliberately discarded so caller-controlled
    621 /// argument text cannot escape through this crate's stable error boundary.
    622 pub fn parse_rhi_cli_v1_from<I, T>(arguments: I) -> Result<RhiCliInvocationV1, RhiCliV1Error>
    623 where
    624     I: IntoIterator<Item = T>,
    625     T: Into<OsString> + Clone,
    626 {
    627     let parsed = RawRhiCliV1::try_parse_from(arguments).map_err(|error| {
    628         if error.kind() == clap::error::ErrorKind::DisplayHelp {
    629             let help = error.to_string();
    630             if help.len() <= 16 * 1024 {
    631                 return RhiCliV1Error {
    632                     kind: RhiCliV1ErrorKind::HelpRequested,
    633                     help_text: Some(help.into_boxed_str()),
    634                 };
    635             }
    636         }
    637         RhiCliV1Error::new(RhiCliV1ErrorKind::InvalidArguments)
    638     })?;
    639     let profile = parsed
    640         .profile
    641         .ok_or_else(|| RhiCliV1Error::new(RhiCliV1ErrorKind::InvalidArguments))?
    642         .into();
    643     let instance = parsed
    644         .instance
    645         .ok_or_else(|| RhiCliV1Error::new(RhiCliV1ErrorKind::InvalidArguments))?;
    646     let instance = InstanceId::new(instance)
    647         .map_err(|_| RhiCliV1Error::new(RhiCliV1ErrorKind::InvalidInstance))?;
    648     validate_bootstrap_paths(
    649         profile,
    650         parsed.repo_local_root.as_deref(),
    651         parsed.config.as_deref(),
    652     )?;
    653 
    654     Ok(RhiCliInvocationV1 {
    655         profile,
    656         instance,
    657         repo_local_root: parsed.repo_local_root,
    658         config_path: parsed.config,
    659         output_mode: parsed.output.into(),
    660         command: admit_command(parsed.command)?,
    661     })
    662 }
    663 
    664 /// Selects the sole permitted execution authority for an admitted command.
    665 ///
    666 /// This function performs no filesystem, database, socket, environment, task,
    667 /// or process work. Later executors consume the plan without reparsing process
    668 /// arguments. No live command receives direct SQLite or offline fallback
    669 /// authority.
    670 #[must_use]
    671 pub const fn plan_rhi_cli_v1(invocation: &RhiCliInvocationV1) -> RhiCliExecutionPlanV1 {
    672     match &invocation.command {
    673         RhiCommandV1::Run => daemon_plan(),
    674         RhiCommandV1::Config(RhiConfigCommandV1::Init)
    675         | RhiCommandV1::Config(RhiConfigCommandV1::Validate)
    676         | RhiCommandV1::Config(RhiConfigCommandV1::Schema)
    677         | RhiCommandV1::Config(RhiConfigCommandV1::Apply(_)) => {
    678             offline_plan(RhiCliOfflineOperationV1::Config)
    679         }
    680         RhiCommandV1::Config(RhiConfigCommandV1::Show) => {
    681             admin_plan(RhiCliAdminOperationV1::EffectiveConfig)
    682         }
    683         RhiCommandV1::State(RhiStateCommandV1::Init)
    684         | RhiCommandV1::State(RhiStateCommandV1::Restore(_))
    685         | RhiCommandV1::State(RhiStateCommandV1::Verify)
    686         | RhiCommandV1::State(RhiStateCommandV1::Migrate) => {
    687             offline_plan(RhiCliOfflineOperationV1::StateExclusive)
    688         }
    689         RhiCommandV1::State(RhiStateCommandV1::Status) => {
    690             admin_plan(RhiCliAdminOperationV1::StateStatus)
    691         }
    692         RhiCommandV1::State(RhiStateCommandV1::Backup(_)) => {
    693             admin_plan(RhiCliAdminOperationV1::StateBackup)
    694         }
    695         RhiCommandV1::Identity(RhiIdentityCommandV1::Init) => {
    696             offline_plan(RhiCliOfflineOperationV1::IdentityExclusive)
    697         }
    698         RhiCommandV1::Identity(RhiIdentityCommandV1::Status) => {
    699             admin_plan(RhiCliAdminOperationV1::IdentityStatus)
    700         }
    701         RhiCommandV1::Identity(RhiIdentityCommandV1::ExportPublic) => {
    702             admin_plan(RhiCliAdminOperationV1::IdentityPublic)
    703         }
    704         RhiCommandV1::Status => admin_plan(RhiCliAdminOperationV1::Status),
    705         RhiCommandV1::Metrics(RhiMetricsCommandV1::Snapshot) => {
    706             admin_plan(RhiCliAdminOperationV1::MetricsSnapshot)
    707         }
    708         RhiCommandV1::Reconciliation(RhiReconciliationCommandV1::Status) => {
    709             admin_plan(RhiCliAdminOperationV1::ReconciliationStatus)
    710         }
    711         RhiCommandV1::Reconciliation(RhiReconciliationCommandV1::Jobs(_)) => {
    712             admin_plan(RhiCliAdminOperationV1::ReconciliationJobs)
    713         }
    714         RhiCommandV1::Reconciliation(RhiReconciliationCommandV1::Refresh(_)) => {
    715             admin_plan(RhiCliAdminOperationV1::ReconciliationRefresh)
    716         }
    717         RhiCommandV1::Sources(RhiSourcesCommandV1::List(_)) => {
    718             admin_plan(RhiCliAdminOperationV1::Sources)
    719         }
    720         RhiCommandV1::Trade(RhiTradeCommandV1::Projection(_)) => {
    721             admin_plan(RhiCliAdminOperationV1::TradeProjection)
    722         }
    723         RhiCommandV1::Trade(RhiTradeCommandV1::ReportCurrent(_)) => {
    724             admin_plan(RhiCliAdminOperationV1::TradeReportCurrent)
    725         }
    726         RhiCommandV1::Trade(RhiTradeCommandV1::Reports(_)) => {
    727             admin_plan(RhiCliAdminOperationV1::TradeReports)
    728         }
    729         RhiCommandV1::Publication(RhiPublicationCommandV1::Backlog(_)) => {
    730             admin_plan(RhiCliAdminOperationV1::PublicationBacklog)
    731         }
    732         RhiCommandV1::Publication(RhiPublicationCommandV1::Targets(_)) => {
    733             admin_plan(RhiCliAdminOperationV1::PublicationTargets)
    734         }
    735         RhiCommandV1::Publication(RhiPublicationCommandV1::Retry(_)) => {
    736             admin_plan(RhiCliAdminOperationV1::PublicationRetry)
    737         }
    738         RhiCommandV1::Presence(RhiPresenceCommandV1::Desired) => {
    739             admin_plan(RhiCliAdminOperationV1::PresenceDesired)
    740         }
    741         RhiCommandV1::Presence(RhiPresenceCommandV1::Render(_)) => {
    742             admin_plan(RhiCliAdminOperationV1::PresenceRender)
    743         }
    744         RhiCommandV1::Presence(RhiPresenceCommandV1::Refresh(_)) => {
    745             admin_plan(RhiCliAdminOperationV1::PresenceRefresh)
    746         }
    747         RhiCommandV1::Doctor => offline_plan(RhiCliOfflineOperationV1::Doctor),
    748     }
    749 }
    750 
    751 const fn daemon_plan() -> RhiCliExecutionPlanV1 {
    752     RhiCliExecutionPlanV1 {
    753         primary_authority: RhiCliPrimaryAuthorityV1::Daemon,
    754         offline_operation: None,
    755         admin_operation: None,
    756     }
    757 }
    758 
    759 const fn offline_plan(operation: RhiCliOfflineOperationV1) -> RhiCliExecutionPlanV1 {
    760     RhiCliExecutionPlanV1 {
    761         primary_authority: RhiCliPrimaryAuthorityV1::Offline,
    762         offline_operation: Some(operation),
    763         admin_operation: None,
    764     }
    765 }
    766 
    767 const fn admin_plan(operation: RhiCliAdminOperationV1) -> RhiCliExecutionPlanV1 {
    768     RhiCliExecutionPlanV1 {
    769         primary_authority: RhiCliPrimaryAuthorityV1::LiveUnixAdmin,
    770         offline_operation: None,
    771         admin_operation: Some(operation),
    772     }
    773 }
    774 
    775 fn validate_bootstrap_paths(
    776     profile: RhiBootstrapProfileV1,
    777     repo_local_root: Option<&Path>,
    778     config_path: Option<&Path>,
    779 ) -> Result<(), RhiCliV1Error> {
    780     match (profile, repo_local_root) {
    781         (RhiBootstrapProfileV1::RepoLocal, Some(root)) if valid_absolute_path(root, true) => {}
    782         (RhiBootstrapProfileV1::RepoLocal, _) => {
    783             return Err(RhiCliV1Error::new(RhiCliV1ErrorKind::InvalidRepoLocalRoot));
    784         }
    785         (_, Some(_)) => {
    786             return Err(RhiCliV1Error::new(
    787                 RhiCliV1ErrorKind::UnexpectedRepoLocalRoot,
    788             ));
    789         }
    790         (_, None) => {}
    791     }
    792 
    793     if config_path.is_some_and(|path| !valid_absolute_path(path, true)) {
    794         return Err(RhiCliV1Error::new(RhiCliV1ErrorKind::InvalidConfigPath));
    795     }
    796     Ok(())
    797 }
    798 
    799 fn valid_absolute_path(path: &Path, require_non_root: bool) -> bool {
    800     path.is_absolute()
    801         && (!require_non_root || path.parent().is_some())
    802         && path
    803             .to_str()
    804             .is_some_and(|value| !value.is_empty() && value.len() <= 4_096)
    805         && !path
    806             .components()
    807             .any(|component| matches!(component, Component::ParentDir))
    808 }
    809 
    810 #[derive(Parser)]
    811 #[command(name = "rhi", bin_name = "rhi", disable_help_subcommand = true)]
    812 struct RawRhiCliV1 {
    813     #[arg(long, global = true, value_enum)]
    814     profile: Option<RawProfile>,
    815     #[arg(long, global = true)]
    816     instance: Option<String>,
    817     #[arg(long = "repo-local-root", global = true)]
    818     repo_local_root: Option<PathBuf>,
    819     #[arg(long, global = true)]
    820     config: Option<PathBuf>,
    821     #[arg(long, global = true, value_enum, default_value_t = RawOutputMode::Human)]
    822     output: RawOutputMode,
    823     #[command(subcommand)]
    824     command: RawCommand,
    825 }
    826 
    827 #[derive(Clone, Copy, ValueEnum)]
    828 enum RawProfile {
    829     ServiceHost,
    830     Interactive,
    831     RepoLocal,
    832 }
    833 
    834 impl From<RawProfile> for RhiBootstrapProfileV1 {
    835     fn from(value: RawProfile) -> Self {
    836         match value {
    837             RawProfile::ServiceHost => Self::ServiceHost,
    838             RawProfile::Interactive => Self::Interactive,
    839             RawProfile::RepoLocal => Self::RepoLocal,
    840         }
    841     }
    842 }
    843 
    844 #[derive(Clone, Copy, Default, ValueEnum)]
    845 enum RawOutputMode {
    846     #[default]
    847     Human,
    848     Json,
    849 }
    850 
    851 impl From<RawOutputMode> for RhiCliOutputModeV1 {
    852     fn from(value: RawOutputMode) -> Self {
    853         match value {
    854             RawOutputMode::Human => Self::Human,
    855             RawOutputMode::Json => Self::Json,
    856         }
    857     }
    858 }
    859 
    860 #[derive(Subcommand)]
    861 enum RawCommand {
    862     Run,
    863     Config {
    864         #[command(subcommand)]
    865         command: RawConfigCommand,
    866     },
    867     State {
    868         #[command(subcommand)]
    869         command: RawStateCommand,
    870     },
    871     Identity {
    872         #[command(subcommand)]
    873         command: RawIdentityCommand,
    874     },
    875     Status,
    876     Metrics {
    877         #[command(subcommand)]
    878         command: RawMetricsCommand,
    879     },
    880     Reconciliation {
    881         #[command(subcommand)]
    882         command: RawReconciliationCommand,
    883     },
    884     Sources {
    885         #[command(subcommand)]
    886         command: RawSourcesCommand,
    887     },
    888     Trade {
    889         #[command(subcommand)]
    890         command: RawTradeCommand,
    891     },
    892     Publication {
    893         #[command(subcommand)]
    894         command: RawPublicationCommand,
    895     },
    896     Presence {
    897         #[command(subcommand)]
    898         command: RawPresenceCommand,
    899     },
    900     Doctor,
    901 }
    902 
    903 macro_rules! command_enum {
    904     ($raw:ident, $public:ident, { $($variant:ident),+ $(,)? }) => {
    905         #[derive(Subcommand)]
    906         enum $raw {
    907             $($variant),+
    908         }
    909 
    910         impl From<$raw> for $public {
    911             fn from(value: $raw) -> Self {
    912                 match value {
    913                     $($raw::$variant => Self::$variant),+
    914                 }
    915             }
    916         }
    917     };
    918 }
    919 
    920 #[derive(Subcommand)]
    921 enum RawConfigCommand {
    922     Init,
    923     Validate,
    924     Show,
    925     Schema,
    926     Apply {
    927         #[arg(long = "candidate-config")]
    928         candidate_config: PathBuf,
    929     },
    930 }
    931 
    932 #[derive(Subcommand)]
    933 enum RawStateCommand {
    934     Init,
    935     Status,
    936     Backup {
    937         #[arg(long = "operation-id")]
    938         operation_id: String,
    939         #[arg(long)]
    940         target: PathBuf,
    941         #[arg(long = "expected-generation")]
    942         expected_generation: u64,
    943         #[arg(long, required = true)]
    944         confirm: bool,
    945     },
    946     Restore {
    947         #[arg(long)]
    948         manifest: PathBuf,
    949         #[arg(long = "manifest-sha256")]
    950         manifest_sha256: String,
    951         #[arg(long)]
    952         bundle: PathBuf,
    953         #[arg(long = "maximum-state-bytes")]
    954         maximum_state_bytes: u64,
    955         #[arg(long, required = true)]
    956         confirm: bool,
    957     },
    958     Verify,
    959     Migrate,
    960 }
    961 
    962 command_enum!(RawIdentityCommand, RhiIdentityCommandV1, {
    963     Init,
    964     Status,
    965     ExportPublic,
    966 });
    967 command_enum!(RawMetricsCommand, RhiMetricsCommandV1, { Snapshot });
    968 
    969 #[derive(Subcommand)]
    970 enum RawReconciliationCommand {
    971     Status,
    972     Jobs {
    973         #[command(flatten)]
    974         page: RawPageQuery,
    975     },
    976     Refresh {
    977         #[arg(long = "operation-id")]
    978         operation_id: String,
    979         #[arg(long = "trade-id")]
    980         trade_id: String,
    981         #[arg(long = "expected-dirty-generation")]
    982         expected_dirty_generation: u64,
    983     },
    984 }
    985 
    986 #[derive(Subcommand)]
    987 enum RawSourcesCommand {
    988     List {
    989         #[command(flatten)]
    990         page: RawPageQuery,
    991     },
    992 }
    993 
    994 #[derive(Subcommand)]
    995 enum RawTradeCommand {
    996     Projection {
    997         #[arg(long = "trade-id")]
    998         trade_id: String,
    999     },
   1000     ReportCurrent {
   1001         #[arg(long = "trade-id")]
   1002         trade_id: String,
   1003     },
   1004     Reports {
   1005         #[arg(long = "trade-id")]
   1006         trade_id: String,
   1007         #[command(flatten)]
   1008         page: RawPageQuery,
   1009     },
   1010 }
   1011 
   1012 #[derive(Subcommand)]
   1013 enum RawPublicationCommand {
   1014     Backlog {
   1015         #[command(flatten)]
   1016         page: RawPageQuery,
   1017     },
   1018     Targets {
   1019         #[command(flatten)]
   1020         page: RawPageQuery,
   1021     },
   1022     Retry {
   1023         #[arg(long = "operation-id")]
   1024         operation_id: String,
   1025         #[arg(long = "workflow-id")]
   1026         workflow_id: String,
   1027         #[arg(long = "expected-generation")]
   1028         expected_generation: u64,
   1029     },
   1030 }
   1031 
   1032 #[derive(Subcommand)]
   1033 enum RawPresenceCommand {
   1034     Desired,
   1035     Render {
   1036         #[arg(long = "operation-id")]
   1037         operation_id: String,
   1038         #[arg(long = "expected-generation")]
   1039         expected_generation: u64,
   1040     },
   1041     Refresh {
   1042         #[arg(long = "operation-id")]
   1043         operation_id: String,
   1044         #[arg(long = "expected-generation")]
   1045         expected_generation: u64,
   1046     },
   1047 }
   1048 
   1049 #[derive(clap::Args)]
   1050 struct RawPageQuery {
   1051     #[arg(long, default_value_t = 100)]
   1052     limit: u16,
   1053     #[arg(long)]
   1054     cursor: Option<String>,
   1055 }
   1056 
   1057 fn admit_command(command: RawCommand) -> Result<RhiCommandV1, RhiCliV1Error> {
   1058     let invalid = || RhiCliV1Error::new(RhiCliV1ErrorKind::InvalidCommandInput);
   1059     let page = |value: RawPageQuery| {
   1060         if !(1..=200).contains(&value.limit)
   1061             || value.cursor.as_deref().is_some_and(|cursor| {
   1062                 cursor.is_empty()
   1063                     || cursor.len() > 512
   1064                     || cursor != cursor.trim()
   1065                     || cursor.chars().any(char::is_control)
   1066             })
   1067         {
   1068             return Err(invalid());
   1069         }
   1070         Ok(RhiPageQueryArgsV1 {
   1071             limit: value.limit,
   1072             cursor: value.cursor.map(String::into_boxed_str),
   1073         })
   1074     };
   1075     let bounded_id = |value: String| {
   1076         if value.is_empty()
   1077             || value.len() > 128
   1078             || value != value.trim()
   1079             || value.chars().any(char::is_control)
   1080         {
   1081             Err(invalid())
   1082         } else {
   1083             Ok(value.into_boxed_str())
   1084         }
   1085     };
   1086     let trade_id = |value: String| match radroots_event::id::TradeId::parse(&value) {
   1087         Ok(parsed) if parsed.to_hex() == value => Ok(value.into_boxed_str()),
   1088         Ok(_) | Err(_) => Err(invalid()),
   1089     };
   1090     Ok(match command {
   1091         RawCommand::Run => RhiCommandV1::Run,
   1092         RawCommand::Config { command } => RhiCommandV1::Config(match command {
   1093             RawConfigCommand::Init => RhiConfigCommandV1::Init,
   1094             RawConfigCommand::Validate => RhiConfigCommandV1::Validate,
   1095             RawConfigCommand::Show => RhiConfigCommandV1::Show,
   1096             RawConfigCommand::Schema => RhiConfigCommandV1::Schema,
   1097             RawConfigCommand::Apply { candidate_config }
   1098                 if valid_absolute_path(&candidate_config, true) =>
   1099             {
   1100                 RhiConfigCommandV1::Apply(RhiConfigApplyArgsV1 { candidate_config })
   1101             }
   1102             RawConfigCommand::Apply { .. } => return Err(invalid()),
   1103         }),
   1104         RawCommand::State { command } => RhiCommandV1::State(match command {
   1105             RawStateCommand::Init => RhiStateCommandV1::Init,
   1106             RawStateCommand::Status => RhiStateCommandV1::Status,
   1107             RawStateCommand::Backup {
   1108                 operation_id,
   1109                 target,
   1110                 expected_generation,
   1111                 confirm: true,
   1112             } if valid_absolute_path(&target, true) => {
   1113                 RhiStateCommandV1::Backup(RhiStateBackupArgsV1 {
   1114                     operation_id: bounded_id(operation_id)?,
   1115                     target,
   1116                     expected_generation,
   1117                 })
   1118             }
   1119             RawStateCommand::Backup { .. } => return Err(invalid()),
   1120             RawStateCommand::Restore {
   1121                 manifest,
   1122                 manifest_sha256,
   1123                 bundle,
   1124                 maximum_state_bytes,
   1125                 confirm: true,
   1126             } if valid_absolute_path(&manifest, true)
   1127                 && valid_absolute_path(&bundle, true)
   1128                 && maximum_state_bytes != 0
   1129                 && is_lower_hex(&manifest_sha256, 64) =>
   1130             {
   1131                 RhiStateCommandV1::Restore(RhiStateRestoreArgsV1 {
   1132                     manifest,
   1133                     manifest_sha256: manifest_sha256.into_boxed_str(),
   1134                     bundle,
   1135                     maximum_state_bytes,
   1136                 })
   1137             }
   1138             RawStateCommand::Restore { .. } => return Err(invalid()),
   1139             RawStateCommand::Verify => RhiStateCommandV1::Verify,
   1140             RawStateCommand::Migrate => RhiStateCommandV1::Migrate,
   1141         }),
   1142         RawCommand::Identity { command } => RhiCommandV1::Identity(command.into()),
   1143         RawCommand::Status => RhiCommandV1::Status,
   1144         RawCommand::Metrics { command } => RhiCommandV1::Metrics(command.into()),
   1145         RawCommand::Reconciliation { command } => RhiCommandV1::Reconciliation(match command {
   1146             RawReconciliationCommand::Status => RhiReconciliationCommandV1::Status,
   1147             RawReconciliationCommand::Jobs { page: value } => {
   1148                 RhiReconciliationCommandV1::Jobs(page(value)?)
   1149             }
   1150             RawReconciliationCommand::Refresh {
   1151                 operation_id,
   1152                 trade_id: selected_trade,
   1153                 expected_dirty_generation,
   1154             } => RhiReconciliationCommandV1::Refresh(RhiReconciliationRefreshArgsV1 {
   1155                 operation_id: bounded_id(operation_id)?,
   1156                 trade_id: trade_id(selected_trade)?,
   1157                 expected_dirty_generation,
   1158             }),
   1159         }),
   1160         RawCommand::Sources { command } => RhiCommandV1::Sources(match command {
   1161             RawSourcesCommand::List { page: value } => RhiSourcesCommandV1::List(page(value)?),
   1162         }),
   1163         RawCommand::Trade { command } => RhiCommandV1::Trade(match command {
   1164             RawTradeCommand::Projection { trade_id: value } => {
   1165                 RhiTradeCommandV1::Projection(RhiTradeArgsV1 {
   1166                     trade_id: trade_id(value)?,
   1167                 })
   1168             }
   1169             RawTradeCommand::ReportCurrent { trade_id: value } => {
   1170                 RhiTradeCommandV1::ReportCurrent(RhiTradeArgsV1 {
   1171                     trade_id: trade_id(value)?,
   1172                 })
   1173             }
   1174             RawTradeCommand::Reports {
   1175                 trade_id: value,
   1176                 page: selected_page,
   1177             } => RhiTradeCommandV1::Reports(RhiTradePageArgsV1 {
   1178                 trade_id: trade_id(value)?,
   1179                 page: page(selected_page)?,
   1180             }),
   1181         }),
   1182         RawCommand::Publication { command } => RhiCommandV1::Publication(match command {
   1183             RawPublicationCommand::Backlog { page: value } => {
   1184                 RhiPublicationCommandV1::Backlog(page(value)?)
   1185             }
   1186             RawPublicationCommand::Targets { page: value } => {
   1187                 RhiPublicationCommandV1::Targets(page(value)?)
   1188             }
   1189             RawPublicationCommand::Retry {
   1190                 operation_id,
   1191                 workflow_id,
   1192                 expected_generation,
   1193             } => RhiPublicationCommandV1::Retry(RhiPublicationRetryArgsV1 {
   1194                 operation_id: bounded_id(operation_id)?,
   1195                 workflow_id: bounded_id(workflow_id)?,
   1196                 expected_generation,
   1197             }),
   1198         }),
   1199         RawCommand::Presence { command } => RhiCommandV1::Presence(match command {
   1200             RawPresenceCommand::Desired => RhiPresenceCommandV1::Desired,
   1201             RawPresenceCommand::Render {
   1202                 operation_id,
   1203                 expected_generation,
   1204             } => RhiPresenceCommandV1::Render(RhiPresenceMutationArgsV1 {
   1205                 operation_id: bounded_id(operation_id)?,
   1206                 expected_generation,
   1207             }),
   1208             RawPresenceCommand::Refresh {
   1209                 operation_id,
   1210                 expected_generation,
   1211             } => RhiPresenceCommandV1::Refresh(RhiPresenceMutationArgsV1 {
   1212                 operation_id: bounded_id(operation_id)?,
   1213                 expected_generation,
   1214             }),
   1215         }),
   1216         RawCommand::Doctor => RhiCommandV1::Doctor,
   1217     })
   1218 }
   1219 
   1220 fn is_lower_hex(value: &str, length: usize) -> bool {
   1221     value.len() == length
   1222         && value
   1223             .bytes()
   1224             .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
   1225 }
   1226 
   1227 #[cfg(test)]
   1228 mod tests {
   1229     use super::*;
   1230 
   1231     fn parse(command: &[&str]) -> Result<RhiCliInvocationV1, RhiCliV1Error> {
   1232         let mut arguments = vec!["rhi", "--profile", "service-host", "--instance", "default"];
   1233         arguments.extend_from_slice(command);
   1234         parse_rhi_cli_v1_from(arguments)
   1235     }
   1236 
   1237     #[test]
   1238     fn exact_command_inventory_parses() {
   1239         let trade = "00000000000000000000000000000000";
   1240         let vectors = [
   1241             vec!["run"],
   1242             vec!["config", "init"],
   1243             vec!["config", "validate"],
   1244             vec!["config", "show"],
   1245             vec!["config", "schema"],
   1246             vec![
   1247                 "config",
   1248                 "apply",
   1249                 "--candidate-config",
   1250                 "/tmp/candidate.toml",
   1251             ],
   1252             vec!["state", "init"],
   1253             vec!["state", "status"],
   1254             vec![
   1255                 "state",
   1256                 "backup",
   1257                 "--operation-id",
   1258                 "backup-1",
   1259                 "--target",
   1260                 "/tmp/backup",
   1261                 "--expected-generation",
   1262                 "1",
   1263                 "--confirm",
   1264             ],
   1265             vec![
   1266                 "state",
   1267                 "restore",
   1268                 "--manifest",
   1269                 "/tmp/manifest.json",
   1270                 "--manifest-sha256",
   1271                 "0000000000000000000000000000000000000000000000000000000000000000",
   1272                 "--bundle",
   1273                 "/tmp/backup",
   1274                 "--maximum-state-bytes",
   1275                 "1048576",
   1276                 "--confirm",
   1277             ],
   1278             vec!["state", "verify"],
   1279             vec!["state", "migrate"],
   1280             vec!["identity", "init"],
   1281             vec!["identity", "status"],
   1282             vec!["identity", "export-public"],
   1283             vec!["status"],
   1284             vec!["metrics", "snapshot"],
   1285             vec!["reconciliation", "status"],
   1286             vec!["reconciliation", "jobs"],
   1287             vec![
   1288                 "reconciliation",
   1289                 "refresh",
   1290                 "--operation-id",
   1291                 "refresh-1",
   1292                 "--trade-id",
   1293                 trade,
   1294                 "--expected-dirty-generation",
   1295                 "1",
   1296             ],
   1297             vec!["sources", "list"],
   1298             vec!["trade", "projection", "--trade-id", trade],
   1299             vec!["trade", "report-current", "--trade-id", trade],
   1300             vec!["trade", "reports", "--trade-id", trade],
   1301             vec!["publication", "backlog"],
   1302             vec!["publication", "targets"],
   1303             vec![
   1304                 "publication",
   1305                 "retry",
   1306                 "--operation-id",
   1307                 "retry-1",
   1308                 "--workflow-id",
   1309                 "workflow-1",
   1310                 "--expected-generation",
   1311                 "1",
   1312             ],
   1313             vec!["presence", "desired"],
   1314             vec![
   1315                 "presence",
   1316                 "render",
   1317                 "--operation-id",
   1318                 "render-1",
   1319                 "--expected-generation",
   1320                 "1",
   1321             ],
   1322             vec![
   1323                 "presence",
   1324                 "refresh",
   1325                 "--operation-id",
   1326                 "presence-1",
   1327                 "--expected-generation",
   1328                 "1",
   1329             ],
   1330             vec!["doctor"],
   1331         ];
   1332         for arguments in vectors {
   1333             parse(&arguments).expect("command");
   1334         }
   1335     }
   1336 
   1337     #[test]
   1338     fn profiles_paths_and_output_are_cross_bound() {
   1339         for profile in ["service-host", "interactive"] {
   1340             let invocation = parse_rhi_cli_v1_from([
   1341                 "rhi",
   1342                 "--profile",
   1343                 profile,
   1344                 "--instance",
   1345                 "north-01",
   1346                 "--config",
   1347                 "/etc/radroots/rhi.toml",
   1348                 "--output",
   1349                 "json",
   1350                 "run",
   1351             ])
   1352             .expect("host profile");
   1353             assert_eq!(invocation.instance().as_str(), "north-01");
   1354             assert_eq!(
   1355                 invocation.config_path(),
   1356                 Some(Path::new("/etc/radroots/rhi.toml"))
   1357             );
   1358             assert_eq!(invocation.output_mode(), RhiCliOutputModeV1::Json);
   1359             assert!(invocation.repo_local_root().is_none());
   1360         }
   1361 
   1362         let repo_local = parse_rhi_cli_v1_from([
   1363             "rhi",
   1364             "--profile",
   1365             "repo-local",
   1366             "--instance",
   1367             "dev",
   1368             "--repo-local-root",
   1369             "/repo/radroots",
   1370             "config",
   1371             "validate",
   1372         ])
   1373         .expect("repo local");
   1374         assert_eq!(repo_local.profile(), RhiBootstrapProfileV1::RepoLocal);
   1375         assert_eq!(
   1376             repo_local.repo_local_root(),
   1377             Some(Path::new("/repo/radroots"))
   1378         );
   1379         assert_eq!(repo_local.output_mode(), RhiCliOutputModeV1::Human);
   1380     }
   1381 
   1382     #[test]
   1383     fn invalid_bootstrap_values_fail_with_stable_kinds() {
   1384         for value in ["Upper", "north-", "north.west"] {
   1385             let error = parse_rhi_cli_v1_from([
   1386                 "rhi",
   1387                 "--profile",
   1388                 "service-host",
   1389                 "--instance",
   1390                 value,
   1391                 "run",
   1392             ])
   1393             .expect_err("invalid instance");
   1394             assert_eq!(error.kind(), RhiCliV1ErrorKind::InvalidInstance);
   1395         }
   1396 
   1397         let exact = "a".repeat(radroots_runtime_paths::INSTANCE_ID_MAX_BYTES);
   1398         assert!(
   1399             parse_rhi_cli_v1_from([
   1400                 "rhi",
   1401                 "--profile",
   1402                 "service-host",
   1403                 "--instance",
   1404                 exact.as_str(),
   1405                 "run",
   1406             ])
   1407             .is_ok()
   1408         );
   1409         let overlong = "a".repeat(radroots_runtime_paths::INSTANCE_ID_MAX_BYTES + 1);
   1410         assert_eq!(
   1411             parse_rhi_cli_v1_from([
   1412                 "rhi",
   1413                 "--profile",
   1414                 "service-host",
   1415                 "--instance",
   1416                 overlong.as_str(),
   1417                 "run",
   1418             ])
   1419             .expect_err("overlong instance")
   1420             .kind(),
   1421             RhiCliV1ErrorKind::InvalidInstance
   1422         );
   1423 
   1424         assert_eq!(
   1425             parse_rhi_cli_v1_from(["rhi", "--profile", "repo-local", "--instance", "dev", "run"])
   1426                 .expect_err("missing root")
   1427                 .kind(),
   1428             RhiCliV1ErrorKind::InvalidRepoLocalRoot
   1429         );
   1430         assert_eq!(
   1431             parse_rhi_cli_v1_from([
   1432                 "rhi",
   1433                 "--profile",
   1434                 "interactive",
   1435                 "--instance",
   1436                 "dev",
   1437                 "--repo-local-root",
   1438                 "/repo/radroots",
   1439                 "run",
   1440             ])
   1441             .expect_err("unexpected root")
   1442             .kind(),
   1443             RhiCliV1ErrorKind::UnexpectedRepoLocalRoot
   1444         );
   1445         for invalid in ["relative", "/", "/repo/../escape"] {
   1446             assert_eq!(
   1447                 parse_rhi_cli_v1_from([
   1448                     "rhi",
   1449                     "--profile",
   1450                     "repo-local",
   1451                     "--instance",
   1452                     "dev",
   1453                     "--repo-local-root",
   1454                     invalid,
   1455                     "run",
   1456                 ])
   1457                 .expect_err("invalid root")
   1458                 .kind(),
   1459                 RhiCliV1ErrorKind::InvalidRepoLocalRoot
   1460             );
   1461         }
   1462         for invalid in ["relative.toml", "/", "/etc/../secret.toml"] {
   1463             assert_eq!(
   1464                 parse_rhi_cli_v1_from([
   1465                     "rhi",
   1466                     "--profile",
   1467                     "service-host",
   1468                     "--instance",
   1469                     "default",
   1470                     "--config",
   1471                     invalid,
   1472                     "run",
   1473                 ])
   1474                 .expect_err("invalid config")
   1475                 .kind(),
   1476                 RhiCliV1ErrorKind::InvalidConfigPath
   1477             );
   1478         }
   1479     }
   1480 
   1481     #[test]
   1482     fn removed_and_unknown_inputs_fail_without_sources() {
   1483         for arguments in [
   1484             vec!["rhi", "run"],
   1485             vec!["rhi", "--profile", "service-host", "run"],
   1486             vec!["rhi", "--profile", "service-host", "--instance", "default"],
   1487             vec![
   1488                 "rhi",
   1489                 "--profile",
   1490                 "production",
   1491                 "--instance",
   1492                 "default",
   1493                 "run",
   1494             ],
   1495             vec![
   1496                 "rhi",
   1497                 "--profile",
   1498                 "service-host",
   1499                 "--instance",
   1500                 "default",
   1501                 "--identity",
   1502                 "/secret",
   1503                 "run",
   1504             ],
   1505             vec![
   1506                 "rhi",
   1507                 "--profile",
   1508                 "service-host",
   1509                 "--instance",
   1510                 "default",
   1511                 "--allow-generate-identity",
   1512                 "run",
   1513             ],
   1514             vec![
   1515                 "rhi",
   1516                 "--profile",
   1517                 "service-host",
   1518                 "--instance",
   1519                 "default",
   1520                 "--logs-dir",
   1521                 "/tmp/logs",
   1522                 "run",
   1523             ],
   1524             vec![
   1525                 "rhi",
   1526                 "--profile",
   1527                 "service-host",
   1528                 "--instance",
   1529                 "default",
   1530                 "--worker",
   1531                 "legacy",
   1532                 "run",
   1533             ],
   1534             vec![
   1535                 "rhi",
   1536                 "--profile",
   1537                 "service-host",
   1538                 "--instance",
   1539                 "default",
   1540                 "identity",
   1541                 "rekey",
   1542             ],
   1543             vec![
   1544                 "rhi",
   1545                 "--profile",
   1546                 "service-host",
   1547                 "--instance",
   1548                 "default",
   1549                 "identity",
   1550                 "replace",
   1551             ],
   1552         ] {
   1553             let failure = parse_rhi_cli_v1_from(arguments).expect_err("arguments must fail");
   1554             assert_eq!(failure.kind(), RhiCliV1ErrorKind::InvalidArguments);
   1555             assert!(Error::source(&failure).is_none());
   1556         }
   1557     }
   1558 
   1559     #[test]
   1560     fn debug_and_errors_do_not_render_caller_values() {
   1561         let instance = "sensitive-instance";
   1562         let config = "/sensitive/config.toml";
   1563         let invocation = parse_rhi_cli_v1_from([
   1564             "rhi",
   1565             "--profile",
   1566             "service-host",
   1567             "--instance",
   1568             instance,
   1569             "--config",
   1570             config,
   1571             "doctor",
   1572         ])
   1573         .expect("invocation");
   1574         let debug = format!("{invocation:?}");
   1575         assert!(!debug.contains(instance));
   1576         assert!(!debug.contains(config));
   1577 
   1578         let secret = "secret-cli-value";
   1579         let failure =
   1580             parse_rhi_cli_v1_from(["rhi", "--profile", secret, "--instance", "default", "run"])
   1581                 .expect_err("invalid profile");
   1582         let rendered = format!("{failure} {failure:?}");
   1583         assert!(!rendered.contains(secret));
   1584         assert!(Error::source(&failure).is_none());
   1585     }
   1586 }