Skip to main content

hyprstream_core/cli/
schema_cli.rs

1// CLI module — prints to stdout for user interaction
2#![allow(clippy::print_stdout, clippy::print_stderr)]
3//! Schema-driven CLI command builder and dispatcher.
4//!
5//! Builds clap `Command` objects at runtime from `MethodSchema` metadata
6//! (generated by hyprstream-rpc-derive from Cap'n Proto schemas) and
7//! dispatches invocations to the appropriate service client's `call_method()`.
8
9use anyhow::{bail, Context, Result};
10use clap::{Arg, ArgMatches, Command};
11use ed25519_dalek::SigningKey;
12use hyprstream_service::ScopedClientTreeNode;
13use serde_json::Value;
14
15use hyprstream_rpc_std::discovery_client::DiscoveryClient;
16use hyprstream_rpc_std::inference_client::InferenceClient;
17use hyprstream_rpc_std::model_client::ModelClient;
18use hyprstream_rpc_std::registry_client::RegistryClient;
19use hyprstream_rpc_std::worker_client::WorkerClient;
20use hyprstream_rpc_std::{
21    inference_client, model_client, policy_client, registry_client, worker_client, workflow_client,
22};
23
24// ─────────────────────────────────────────────────────────────────────────────
25// MethodSchemaLike trait — unifies per-module MethodSchema types
26// ─────────────────────────────────────────────────────────────────────────────
27
28/// Trait to abstract over the structurally identical but distinct `MethodSchema`
29/// types generated by each service's proc macro invocation.
30pub trait MethodSchemaLike {
31    fn name(&self) -> &str;
32    fn params(&self) -> &[impl ParamSchemaLike];
33    fn is_scoped(&self) -> bool;
34    fn scope_field(&self) -> &str;
35    fn description(&self) -> &str;
36    fn is_streaming(&self) -> bool;
37    fn cli_hidden(&self) -> bool;
38}
39
40pub trait ParamSchemaLike {
41    fn name(&self) -> &str;
42    fn type_name(&self) -> &str;
43    fn required(&self) -> bool;
44    fn description(&self) -> &str;
45}
46
47/// Portable view of a method schema, extracted from any generated MethodSchema.
48#[derive(Debug, Clone)]
49pub struct MethodView {
50    pub name: String,
51    pub params: Vec<ParamView>,
52    pub is_scoped: bool,
53    pub scope_field: String,
54    pub description: String,
55    pub is_streaming: bool,
56    pub cli_hidden: bool,
57}
58
59#[derive(Debug, Clone)]
60pub struct ParamView {
61    pub name: String,
62    pub type_name: String,
63    pub required: bool,
64    pub description: String,
65    pub default_value: String,
66}
67
68/// Extract a portable MethodView list from any generated module's schema_metadata.
69/// Uses a macro since each module's MethodSchema is a distinct type.
70macro_rules! extract_methods {
71    ($schema_fn:expr) => {{
72        let (_service_name, methods) = $schema_fn;
73        methods_to_views(methods)
74    }};
75}
76
77/// Convert a slice of MethodMeta into MethodView values.
78fn methods_to_views(methods: &[hyprstream_service::MethodMeta]) -> Vec<MethodView> {
79    methods
80        .iter()
81        .map(|m| MethodView {
82            name: m.name.to_owned(),
83            params: m
84                .params
85                .iter()
86                .map(|p| ParamView {
87                    name: p.name.to_owned(),
88                    type_name: p.type_name.to_owned(),
89                    required: p.required,
90                    description: p.description.to_owned(),
91                    default_value: p.default_value.to_owned(),
92                })
93                .collect(),
94            is_scoped: m.is_scoped,
95            scope_field: m.scope_field.to_owned(),
96            description: m.description.to_owned(),
97            is_streaming: m.is_streaming,
98            cli_hidden: m.hidden,
99        })
100        .collect()
101}
102
103/// Convert scoped metadata (service, scope, methods) into MethodView values.
104fn scoped_methods_to_views(
105    metadata_fn: hyprstream_service::ScopedSchemaMetadataFn,
106) -> Vec<MethodView> {
107    let (_service_name, _scope_name, methods) = metadata_fn();
108    methods_to_views(methods)
109}
110
111// ─────────────────────────────────────────────────────────────────────────────
112// Build clap Commands from schema metadata
113// ─────────────────────────────────────────────────────────────────────────────
114
115/// Build a clap `Command` for a service from its methods and scoped client tree.
116fn build_service_command(
117    service_name: &str,
118    methods: &[MethodView],
119    tree: &'static [ScopedClientTreeNode],
120) -> Command {
121    // Leak service_name to get 'static lifetime required by clap
122    let name: &'static str = service_name.to_owned().leak();
123    let mut cmd = Command::new(name)
124        .about(format!("{} service commands", service_name))
125        .arg_required_else_help(true);
126
127    // Add top-level methods as subcommands (filtering cli_hidden and streaming)
128    for method in methods {
129        if method.cli_hidden || method.is_streaming {
130            continue;
131        }
132        cmd = cmd.subcommand(build_method_command(method));
133    }
134
135    // Add scoped subcommands from tree (recursive)
136    for node in tree {
137        cmd = cmd.subcommand(build_scoped_command_from_node(node));
138    }
139
140    cmd
141}
142
143/// Recursively build a scoped command from a tree node.
144fn build_scoped_command_from_node(node: &ScopedClientTreeNode) -> Command {
145    let sn: &'static str = node.scope_name;
146    let methods = scoped_methods_to_views(node.metadata_fn);
147
148    let mut cmd = Command::new(sn)
149        .about(format!("{} scoped commands", node.scope_name))
150        .subcommand_required(true)
151        .arg_required_else_help(true);
152
153    // Only add scope_id positional arg if there's a scope field
154    if !node.scope_field.is_empty() {
155        cmd = cmd.arg(
156            Arg::new("scope_id")
157                .required(true)
158                .help("Scope identifier (e.g., model name, repo ID)"),
159        );
160    }
161
162    for method in &methods {
163        if method.cli_hidden || method.is_streaming {
164            continue;
165        }
166        cmd = cmd.subcommand(build_method_command(method));
167    }
168
169    // Recursively add nested scoped commands
170    for nested in node.nested {
171        cmd = cmd.subcommand(build_scoped_command_from_node(nested));
172    }
173
174    cmd
175}
176
177/// Build a clap `Command` for a single method.
178fn build_method_command(method: &MethodView) -> Command {
179    // Convert snake_case method name to kebab-case for CLI
180    // Leak the string to get a &'static str for clap's Str type
181    let cli_name: &'static str = method.name.replace('_', "-").leak();
182    let mut cmd = Command::new(cli_name);
183
184    if !method.description.is_empty() {
185        let desc: &'static str = method.description.clone().leak();
186        cmd = cmd.about(desc);
187    }
188
189    for param in &method.params {
190        let arg_name: &'static str = param.name.replace('_', "-").leak();
191        let param_id: &'static str = param.name.clone().leak();
192        let mut arg = Arg::new(param_id).long(arg_name);
193
194        if param.type_name == "Bool" {
195            // Bool params are flags: --read (present=true, absent=false)
196            arg = arg.action(clap::ArgAction::SetTrue);
197        } else {
198            arg = arg.required(param.required);
199        }
200
201        if !param.description.is_empty() {
202            let help: &'static str = param.description.clone().leak();
203            arg = arg.help(help);
204        }
205
206        cmd = cmd.arg(arg);
207    }
208    cmd
209}
210
211/// Build the `tool` command containing all schema-driven service subcommands.
212///
213/// Usage: `hyprstream tool <service> [scope <id>] <method> [--param value ...]`
214pub fn build_tool_command() -> Command {
215    let mut tool =
216        Command::new("tool").about("Direct RPC tool access (schema-driven, mirrors MCP tools)");
217
218    // Registry service
219    let registry_methods = extract_methods!(registry_client::schema_metadata());
220    let registry_tree = registry_client::scoped_client_tree();
221    tool = tool.subcommand(build_service_command(
222        "registry",
223        &registry_methods,
224        registry_tree,
225    ));
226
227    // Model service
228    let model_methods = extract_methods!(model_client::schema_metadata());
229    let model_tree = model_client::scoped_client_tree();
230    tool = tool.subcommand(build_service_command("model", &model_methods, model_tree));
231
232    // Inference service (standalone, no scoped)
233    let inference_methods = extract_methods!(inference_client::schema_metadata());
234    let inference_tree = inference_client::scoped_client_tree();
235    tool = tool.subcommand(build_service_command(
236        "inference",
237        &inference_methods,
238        inference_tree,
239    ));
240
241    // Policy service (standalone, no scoped)
242    let policy_methods = extract_methods!(policy_client::schema_metadata());
243    let policy_tree = policy_client::scoped_client_tree();
244    tool = tool.subcommand(build_service_command(
245        "policy",
246        &policy_methods,
247        policy_tree,
248    ));
249
250    // Discovery intentionally exposes only its read-only health check here.
251    // The remaining generated methods are service/bootstrap operations and are
252    // not part of this diagnostic CLI surface.
253    let discovery = Command::new("discovery")
254        .about("Discovery health check")
255        .subcommand(Command::new("ping").about("Health check"))
256        .subcommand_required(true)
257        .arg_required_else_help(true);
258    tool = tool.subcommand(discovery);
259
260    // Worker service + CRI-aligned scoped resources
261    let worker_methods = extract_methods!(worker_client::schema_metadata());
262    let worker_tree = worker_client::scoped_client_tree();
263    tool = tool.subcommand(build_service_command(
264        "worker",
265        &worker_methods,
266        worker_tree,
267    ));
268
269    // Workflow service
270    let workflow_methods = extract_methods!(workflow_client::schema_metadata());
271    let workflow_tree = workflow_client::scoped_client_tree();
272    tool = tool.subcommand(build_service_command(
273        "workflow",
274        &workflow_methods,
275        workflow_tree,
276    ));
277
278    tool
279}
280
281/// Handle a `tool` subcommand by extracting the service name and delegating.
282pub async fn handle_tool_command(matches: &ArgMatches, signing_key: SigningKey) -> Result<()> {
283    let (service_name, service_matches) = matches.subcommand().ok_or_else(|| {
284        anyhow::anyhow!(
285            "No service specified. Use: tool <registry|discovery|model|inference|policy|worker|workflow> ..."
286        )
287    })?;
288    handle_schema_command(service_name, service_matches, signing_key).await
289}
290
291// ─────────────────────────────────────────────────────────────────────────────
292// Dispatch schema commands
293// ─────────────────────────────────────────────────────────────────────────────
294
295/// Get the scoped client tree for a service.
296fn get_service_tree(service: &str) -> &'static [ScopedClientTreeNode] {
297    match service {
298        "registry" => registry_client::scoped_client_tree(),
299        "model" => model_client::scoped_client_tree(),
300        "inference" => inference_client::scoped_client_tree(),
301        "policy" => policy_client::scoped_client_tree(),
302        "worker" => worker_client::scoped_client_tree(),
303        "workflow" => workflow_client::scoped_client_tree(),
304        _ => &[],
305    }
306}
307
308/// Dispatch a schema-driven CLI command based on matched subcommands.
309///
310/// Supports recursive scoped commands (e.g., `registry repo <id> worktree <name> <method>`).
311pub async fn handle_schema_command(
312    service_name: &str,
313    matches: &ArgMatches,
314    signing_key: SigningKey,
315) -> Result<()> {
316    // Determine which subcommand was invoked
317    let (sub_name, sub_matches) = matches
318        .subcommand()
319        .ok_or_else(|| anyhow::anyhow!("No subcommand provided for {}", service_name))?;
320
321    let tree = get_service_tree(service_name);
322
323    // Check if this is a scoped command by looking up the sub_name in the tree
324    if let Some(node) = tree.iter().find(|n| n.scope_name == sub_name) {
325        // Scoped: recursively walk scope chain
326        let mut scope_chain: Vec<(&str, &str)> = Vec::new();
327        let mut current_node = node;
328        let mut current_matches = sub_matches;
329
330        // Collect scope_id if this node has scope fields
331        if !current_node.scope_field.is_empty() {
332            let scope_id = current_matches
333                .get_one::<String>("scope_id")
334                .ok_or_else(|| anyhow::anyhow!("Missing scope ID for {}", sub_name))?;
335            scope_chain.push((current_node.scope_name, scope_id.as_str()));
336        } else {
337            scope_chain.push((current_node.scope_name, ""));
338        }
339
340        loop {
341            let (next_name, next_matches) = current_matches
342                .subcommand()
343                .ok_or_else(|| anyhow::anyhow!("No method provided"))?;
344
345            // Check if next_name is a nested scope
346            if let Some(nested_node) = current_node
347                .nested
348                .iter()
349                .find(|n| n.scope_name == next_name)
350            {
351                // It's a deeper scope level
352                if !nested_node.scope_field.is_empty() {
353                    let nested_id = next_matches
354                        .get_one::<String>("scope_id")
355                        .ok_or_else(|| anyhow::anyhow!("Missing scope ID for {}", next_name))?;
356                    scope_chain.push((nested_node.scope_name, nested_id.as_str()));
357                } else {
358                    scope_chain.push((nested_node.scope_name, ""));
359                }
360                current_node = nested_node;
361                current_matches = next_matches;
362            } else {
363                // Reached the method — dispatch
364                let method_snake = next_name.replace('-', "_");
365                let methods = find_methods_in_tree(tree, &scope_chain);
366                let args = matches_to_json(next_matches, &methods, &method_snake);
367
368                let result = dispatch_scoped_dynamic(
369                    service_name,
370                    &scope_chain,
371                    &method_snake,
372                    &args,
373                    signing_key,
374                )
375                .await?;
376
377                println!("{}", format_response(&result));
378                break;
379            }
380        }
381    } else {
382        // Top-level: e.g., "registry list"
383        let method_snake = sub_name.replace('-', "_");
384        let methods = get_top_level_methods(service_name);
385        let args = matches_to_json(sub_matches, &methods, &method_snake);
386
387        let result = dispatch_top_level(service_name, &method_snake, &args, signing_key).await?;
388        println!("{}", format_response(&result));
389    }
390
391    Ok(())
392}
393
394/// Dispatch a top-level (non-scoped) method call.
395async fn dispatch_top_level(
396    service: &str,
397    method: &str,
398    args: &Value,
399    signing_key: SigningKey,
400) -> Result<Value> {
401    match service {
402        "registry" => {
403            let client: RegistryClient = RegistryClient::from_provider(
404                &hyprstream_discovery::ProductionRpcClientProvider,
405                signing_key,
406                None,
407            )?;
408            client.call_method(method, args).await
409        }
410        "model" => {
411            let client = ModelClient::from_provider(
412                &hyprstream_discovery::ProductionRpcClientProvider,
413                signing_key,
414                None,
415            )?;
416            client.call_method(method, args).await
417        }
418        "inference" => {
419            let client = InferenceClient::from_provider(
420                &hyprstream_discovery::ProductionRpcClientProvider,
421                signing_key,
422                None,
423            )?;
424            client.call_method(method, args).await
425        }
426        "policy" => {
427            let client = super::policy_handlers::create_policy_client(&signing_key)?;
428            client.call_method(method, args).await
429        }
430        "discovery" => {
431            if method != "ping" {
432                bail!("Discovery CLI exposes only the ping method")
433            }
434            let client = create_discovery_client(&signing_key)?;
435            client.call_method(method, args).await
436        }
437        "worker" => {
438            bail!("Worker service has no top-level methods. Use: tool worker <runtime|sandbox|container|image> <method>")
439        }
440        "workflow" => {
441            // #989: WorkflowService factory is registered (default-off). The
442            // factory still has to be started (`[worker.workflow] enabled = true`)
443            // for this dispatch to reach a live service; the explicit provider
444            // resolves the registered endpoint and errors clearly if nothing is listening.
445            let client = workflow_client::WorkflowClient::from_provider(
446                &hyprstream_discovery::ProductionRpcClientProvider,
447                signing_key,
448                None,
449            )?;
450            client.call_method(method, args).await
451        }
452        _ => bail!("Unknown service: {}", service),
453    }
454}
455
456/// Construct the Discovery client using the process's already-selected
457/// network profile. An authenticated bootstrap-installed client (required-
458/// native checkpoint-backed resolver, or the DID-anchored reach — including
459/// `remote_node = true`, which boots with `network_required = false`) is
460/// used directly. Required-native never falls back to a local endpoint;
461/// Compatibility standalone uses the installed service trust key and
462/// deterministic local REP transport.
463fn create_discovery_client(signing_key: &SigningKey) -> Result<DiscoveryClient> {
464    create_discovery_client_for_profile(
465        signing_key,
466        hyprstream_discovery::native_network_required(),
467    )
468}
469
470fn create_discovery_client_for_profile(
471    signing_key: &SigningKey,
472    network_required: bool,
473) -> Result<DiscoveryClient> {
474    // The reach this process's own bootstrap installed is authoritative
475    // regardless of the native-network profile: process topology and
476    // transport enforcement are separate axes. DID-anchored `remote_node =
477    // true` bootstrap explicitly runs with `network_required = false` while
478    // installing a signed, liveness-verified network client; branching only
479    // on the profile here would discard that authenticated reach and dial a
480    // local REP socket the remote node does not have.
481    if let Some(installed) = hyprstream_discovery::installed_bootstrap_discovery_client() {
482        return Ok(installed);
483    }
484
485    if network_required {
486        return DiscoveryClient::from_provider(
487            &hyprstream_discovery::ProductionRpcClientProvider,
488            signing_key.clone(),
489            None,
490        );
491    }
492
493    let discovery_key = hyprstream_service::global_trust_store()
494        .resolve_one("discovery")
495        .ok_or_else(|| anyhow::anyhow!("Discovery service trust key is not installed"))?;
496    let registry = hyprstream_rpc::registry::try_global()
497        .ok_or_else(|| anyhow::anyhow!("EndpointRegistry not initialized"))?;
498    let transport = registry
499        .try_endpoint("discovery", hyprstream_rpc::registry::SocketKind::Rep)
500        .context("resolve local DiscoveryService REP endpoint")?;
501    DiscoveryClient::for_local_transport_bootstrap(
502        &transport,
503        signing_key.clone(),
504        discovery_key,
505        None,
506    )
507}
508
509/// Dispatch a scoped method call via `call_scoped_method` through the scope chain.
510async fn dispatch_scoped_dynamic(
511    service: &str,
512    scope_chain: &[(&str, &str)],
513    method: &str,
514    args: &Value,
515    signing_key: SigningKey,
516) -> Result<Value> {
517    match service {
518        "registry" => {
519            let client: RegistryClient = RegistryClient::from_provider(
520                &hyprstream_discovery::ProductionRpcClientProvider,
521                signing_key,
522                None,
523            )?;
524            client.call_scoped_method(scope_chain, method, args).await
525        }
526        "model" => {
527            let client = ModelClient::from_provider(
528                &hyprstream_discovery::ProductionRpcClientProvider,
529                signing_key,
530                None,
531            )?;
532            client.call_scoped_method(scope_chain, method, args).await
533        }
534        "worker" => {
535            let client = WorkerClient::from_provider(
536                &hyprstream_discovery::ProductionRpcClientProvider,
537                signing_key,
538                None,
539            )?;
540            client.call_scoped_method(scope_chain, method, args).await
541        }
542        // "workflow" has no scoped sub-resources (unlike worker's
543        // runtime/sandbox/container/image scopes) — its methods (list/dispatch/
544        // getRun/…) are all top-level and dispatched via dispatch_dynamic.
545        _ => bail!("Service '{}' has no scoped methods", service),
546    }
547}
548
549// ─────────────────────────────────────────────────────────────────────────────
550// ArgMatches → JSON conversion
551// ─────────────────────────────────────────────────────────────────────────────
552
553/// Get the top-level methods for a service (used for type conversion).
554fn get_top_level_methods(service: &str) -> Vec<MethodView> {
555    match service {
556        "registry" => extract_methods!(registry_client::schema_metadata()),
557        "model" => extract_methods!(model_client::schema_metadata()),
558        "inference" => extract_methods!(inference_client::schema_metadata()),
559        "policy" => extract_methods!(policy_client::schema_metadata()),
560        "worker" => extract_methods!(worker_client::schema_metadata()),
561        "workflow" => extract_methods!(workflow_client::schema_metadata()),
562        _ => Vec::new(),
563    }
564}
565
566/// Find methods for a scope chain by walking the tree.
567fn find_methods_in_tree(
568    tree: &[ScopedClientTreeNode],
569    scope_chain: &[(&str, &str)],
570) -> Vec<MethodView> {
571    if scope_chain.is_empty() {
572        return vec![];
573    }
574    for node in tree {
575        if node.scope_name == scope_chain[0].0 {
576            if scope_chain.len() == 1 {
577                return scoped_methods_to_views(node.metadata_fn);
578            }
579            return find_methods_in_tree(node.nested, &scope_chain[1..]);
580        }
581    }
582    vec![]
583}
584
585/// Convert a snake_case CLI parameter name to the camelCase key the generated
586/// request structs expect (`#[serde(rename_all = "camelCase")]`).
587fn snake_to_camel(name: &str) -> String {
588    let mut out = String::with_capacity(name.len());
589    let mut upper = false;
590    for ch in name.chars() {
591        if ch == '_' {
592            upper = true;
593        } else if std::mem::take(&mut upper) {
594            out.extend(ch.to_uppercase());
595        } else {
596            out.push(ch);
597        }
598    }
599    out
600}
601
602/// Convert clap `ArgMatches` into a JSON object, using MethodView params for type coercion.
603fn matches_to_json(matches: &ArgMatches, methods: &[MethodView], method_name: &str) -> Value {
604    let method = methods.iter().find(|m| m.name == method_name);
605    let mut map = serde_json::Map::new();
606
607    if let Some(method) = method {
608        for param in &method.params {
609            // The generated wire structs deserialize camelCase capnp field
610            // names (ttlSeconds); the CLI schema view carries snake_case.
611            // Insert both keys — serde picks the one the target struct
612            // declares.
613            let camel = snake_to_camel(&param.name);
614            if param.type_name == "Bool" {
615                // Bool flags use get_flag() (ArgAction::SetTrue)
616                let val = matches.get_flag(&param.name);
617                map.insert(param.name.clone(), Value::Bool(val));
618                if camel != param.name {
619                    map.insert(camel, Value::Bool(val));
620                }
621            } else if let Some(val) = matches.get_one::<String>(&param.name) {
622                let json_val = coerce_value(val, &param.type_name);
623                map.insert(param.name.clone(), json_val.clone());
624                if camel != param.name {
625                    map.insert(camel, json_val);
626                }
627            }
628        }
629    } else {
630        // Fallback: extract all string args
631        for id in matches.ids() {
632            if let Some(val) = matches.get_one::<String>(id.as_str()) {
633                map.insert(id.to_string(), Value::String(val.clone()));
634            }
635        }
636    }
637
638    Value::Object(map)
639}
640
641/// Coerce a string value to the appropriate JSON type based on Cap'n Proto type name.
642///
643/// Optional fields arrive as an `Option<T>` wrapper struct (codegen metadata
644/// spells it `OptionUint32`, from the short name of the shared
645/// `optional.capnp` struct; the `Opt.` alias is import-local and never
646/// appears here). Unwrap the wrapper so optional numerics parse as numbers
647/// instead of strings. Matching is case-insensitive because the wrapper
648/// struct names use capnp casing (`Uint32`) while top-level type names use
649/// the codegen spelling (`UInt32`).
650fn coerce_value(s: &str, type_name: &str) -> Value {
651    let inner = type_name
652        .strip_prefix("Option<")
653        .and_then(|r| r.strip_suffix('>'))
654        .or_else(|| type_name.strip_prefix("Opt.Option"))
655        .or_else(|| type_name.strip_prefix("Option"));
656    let type_name = inner.unwrap_or(type_name);
657    match type_name.to_ascii_lowercase().as_str() {
658        "bool" => Value::Bool(s.parse().unwrap_or(false)),
659        "uint8" | "uint16" | "uint32" | "uint64" => s
660            .parse::<u64>()
661            .map(Value::from)
662            .unwrap_or_else(|_| Value::String(s.to_owned())),
663        "int8" | "int16" | "int32" | "int64" => s
664            .parse::<i64>()
665            .map(Value::from)
666            .unwrap_or_else(|_| Value::String(s.to_owned())),
667        "float32" | "float64" => s
668            .parse::<f64>()
669            .map(Value::from)
670            .unwrap_or_else(|_| Value::String(s.to_owned())),
671        _ if type_name.starts_with("List(") => {
672            // Split comma-separated values into a JSON array
673            Value::Array(
674                s.split(',')
675                    .map(|v| Value::String(v.trim().to_owned()))
676                    .collect(),
677            )
678        }
679        _ => Value::String(s.to_owned()),
680    }
681}
682
683// ─────────────────────────────────────────────────────────────────────────────
684// Response formatting
685// ─────────────────────────────────────────────────────────────────────────────
686
687/// Format a JSON value as a human-readable string for CLI output.
688pub fn format_response(value: &Value) -> String {
689    match value {
690        Value::Null => "OK".to_owned(),
691        Value::String(s) => s.clone(),
692        Value::Bool(b) => b.to_string(),
693        Value::Number(n) => n.to_string(),
694        Value::Array(arr) if arr.is_empty() => "(empty)".to_owned(),
695        Value::Array(arr) => format_array_as_table(arr),
696        Value::Object(obj) if obj.is_empty() => "OK".to_owned(),
697        Value::Object(obj) => format_object_as_kv(obj),
698    }
699}
700
701/// Format a JSON array as an aligned table.
702fn format_array_as_table(arr: &[Value]) -> String {
703    // If array of objects, format as columnar table
704    if let Some(Value::Object(first)) = arr.first() {
705        let keys: Vec<String> = first.keys().cloned().collect();
706
707        // Calculate column widths
708        let mut widths: Vec<usize> = keys.iter().map(std::string::String::len).collect();
709        for item in arr {
710            if let Value::Object(obj) = item {
711                for (i, key) in keys.iter().enumerate() {
712                    let val_len = format_cell(obj.get(key)).len();
713                    if val_len > widths[i] {
714                        widths[i] = val_len;
715                    }
716                }
717            }
718        }
719
720        let mut out = String::new();
721
722        // Header
723        for (i, key) in keys.iter().enumerate() {
724            if i > 0 {
725                out.push_str("  ");
726            }
727            out.push_str(&format!(
728                "{:<width$}",
729                key.to_uppercase(),
730                width = widths[i]
731            ));
732        }
733        out.push('\n');
734
735        // Separator
736        for (i, width) in widths.iter().enumerate() {
737            if i > 0 {
738                out.push_str("  ");
739            }
740            for _ in 0..*width {
741                out.push('-');
742            }
743        }
744        out.push('\n');
745
746        // Rows
747        for item in arr {
748            if let Value::Object(obj) = item {
749                for (i, key) in keys.iter().enumerate() {
750                    if i > 0 {
751                        out.push_str("  ");
752                    }
753                    out.push_str(&format!(
754                        "{:<width$}",
755                        format_cell(obj.get(key)),
756                        width = widths[i]
757                    ));
758                }
759                out.push('\n');
760            }
761        }
762
763        out.trim_end().to_owned()
764    } else {
765        // Array of primitives
766        arr.iter()
767            .map(|v| match v {
768                Value::String(s) => s.clone(),
769                other => other.to_string(),
770            })
771            .collect::<Vec<_>>()
772            .join("\n")
773    }
774}
775
776/// Format a JSON object as aligned key-value pairs.
777fn format_object_as_kv(obj: &serde_json::Map<String, Value>) -> String {
778    if obj.is_empty() {
779        return "OK".to_owned();
780    }
781
782    let max_key_len = obj.keys().map(std::string::String::len).max().unwrap_or(0);
783    let mut out = String::new();
784
785    for (key, value) in obj {
786        out.push_str(&format!(
787            "{:<width$}  {}\n",
788            key,
789            format_cell(Some(value)),
790            width = max_key_len
791        ));
792    }
793
794    out.trim_end().to_owned()
795}
796
797/// Format a single cell value for table output.
798fn format_cell(value: Option<&Value>) -> String {
799    match value {
800        None | Some(Value::Null) => "-".to_owned(),
801        Some(Value::String(s)) => s.clone(),
802        Some(Value::Bool(b)) => b.to_string(),
803        Some(Value::Number(n)) => n.to_string(),
804        Some(Value::Array(arr)) => {
805            let items: Vec<String> = arr
806                .iter()
807                .map(|v| match v {
808                    Value::String(s) => s.clone(),
809                    other => other.to_string(),
810                })
811                .collect();
812            items.join(", ")
813        }
814        Some(Value::Object(obj)) => serde_json::to_string(obj).unwrap_or_else(|_| "{}".to_owned()),
815    }
816}
817
818#[cfg(test)]
819#[allow(clippy::expect_used, clippy::unwrap_used)]
820mod tests {
821    use super::*;
822
823    fn test_signing_key() -> SigningKey {
824        SigningKey::from_bytes(&[7u8; 32])
825    }
826
827    #[test]
828    fn snake_to_camel_maps_cli_names_to_wire_keys() {
829        assert_eq!(snake_to_camel("max_context"), "maxContext");
830        assert_eq!(snake_to_camel("ttl_seconds"), "ttlSeconds");
831        assert_eq!(snake_to_camel("top_p"), "topP");
832        assert_eq!(snake_to_camel("model_ref"), "modelRef");
833        assert_eq!(snake_to_camel("name"), "name");
834    }
835
836    #[test]
837    fn option_numeric_values_coerce_to_numbers() {
838        // The codegen metadata spelling (short name of the optional.capnp
839        // wrapper struct, no `Opt.` alias).
840        assert_eq!(coerce_value("4096", "OptionUint32"), Value::from(4096u64));
841        assert_eq!(
842            coerce_value("18446744073709551615", "OptionUint64"),
843            Value::from(u64::MAX)
844        );
845        let temperature = coerce_value("0.5", "OptionFloat32");
846        assert!(
847            matches!(temperature, Value::Number(ref n) if n.as_f64() == Some(0.5)),
848            "OptionFloat32 must coerce to a JSON number: {temperature}"
849        );
850        // The schema-text `Opt.` alias spelling and the Rust-style spelling
851        // are accepted as fallbacks.
852        assert_eq!(
853            coerce_value("4096", "Opt.OptionUint32"),
854            Value::from(4096u64)
855        );
856        assert_eq!(coerce_value("7", "Option<UInt64>"), Value::from(7u64));
857        // Plain (non-Option) numerics keep their existing behavior.
858        assert_eq!(coerce_value("42", "UInt32"), Value::from(42u64));
859        assert_eq!(coerce_value("-3", "Int64"), Value::from(-3i64));
860        // Non-primitive Option wrappers (e.g. OptionKVQuantType) are
861        // untouched — they stay strings.
862        assert_eq!(
863            coerce_value("none", "OptionKVQuantType"),
864            Value::String("none".to_owned())
865        );
866    }
867
868    #[test]
869    fn malformed_numeric_stays_a_string_for_downstream_rejection() {
870        // A value that does not parse must NOT be silently coerced to a
871        // number/zero; leaving it a string makes the generated request
872        // struct's serde deserialization reject it with a type error.
873        for bad in ["abc", "", "4.5", "-1"] {
874            assert_eq!(
875                coerce_value(bad, "OptionUint32"),
876                Value::String(bad.to_owned()),
877                "malformed uint must stay a string: {bad:?}"
878            );
879        }
880    }
881
882    #[test]
883    fn matches_to_json_emits_camel_case_keys_for_snake_case_params() {
884        // model load has `maxContext :Opt.OptionUint32`; the CLI param
885        // is snake_case `max_context`.
886        let command = build_tool_command();
887        let matches = command
888            .try_get_matches_from([
889                "tool",
890                "model",
891                "load",
892                "--model-ref",
893                "qwen3-small:main",
894                "--max-context",
895                "4096",
896                "--kv-quant",
897                "none",
898            ])
899            .expect("load command must parse");
900        let (_, service_matches) = matches.subcommand().expect("service subcommand");
901        let (_, method_matches) = service_matches.subcommand().expect("method subcommand");
902        let methods = get_top_level_methods("model");
903        let args = matches_to_json(method_matches, &methods, "load");
904        assert_eq!(
905            args.get("maxContext"),
906            Some(&Value::from(4096u64)),
907            "camelCase wire key must carry the coerced number: {args}"
908        );
909        assert_eq!(
910            args.get("modelRef"),
911            Some(&Value::String("qwen3-small:main".to_owned())),
912            "camelCase text key must be present: {args}"
913        );
914    }
915
916    #[test]
917    fn bool_flag_emits_both_key_spellings() {
918        let method = MethodView {
919            name: "refresh".to_owned(),
920            params: vec![ParamView {
921                name: "dry_run".to_owned(),
922                type_name: "Bool".to_owned(),
923                required: false,
924                description: String::new(),
925                default_value: "false".to_owned(),
926            }],
927            is_scoped: false,
928            scope_field: String::new(),
929            description: String::new(),
930            is_streaming: false,
931            cli_hidden: false,
932        };
933        let matches = build_method_command(&method)
934            .try_get_matches_from(["refresh", "--dry-run"])
935            .expect("flag must parse");
936        let args = matches_to_json(&matches, std::slice::from_ref(&method), "refresh");
937        assert_eq!(args.get("dry_run"), Some(&Value::Bool(true)));
938        assert_eq!(args.get("dryRun"), Some(&Value::Bool(true)));
939    }
940
941    #[test]
942    fn unknown_arguments_are_rejected() {
943        build_tool_command()
944            .try_get_matches_from([
945                "tool",
946                "model",
947                "load",
948                "--model-ref",
949                "qwen3-small:main",
950                "--kv-quant",
951                "none",
952                "--definitely-unknown",
953                "1",
954            ])
955            .expect_err("unknown arguments must be rejected");
956    }
957
958    #[test]
959    fn discovery_cli_exposes_only_ping() {
960        let command = build_tool_command();
961        command
962            .clone()
963            .try_get_matches_from(["tool", "discovery", "ping"])
964            .expect("discovery ping must be a valid CLI command");
965        command
966            .try_get_matches_from(["tool", "discovery", "list-services"])
967            .expect_err("Discovery management methods must stay outside this CLI");
968        assert!(get_service_tree("discovery").is_empty());
969    }
970
971    #[tokio::test]
972    async fn compatibility_ping_command_denies_without_trusted_local_service() {
973        // Run the assertion in a fresh test process so unrelated tests cannot
974        // install a process-global resolver and turn this into a false pass.
975        if std::env::var_os("HYPRSTREAM_DISCOVERY_PING_DENIAL_CHILD").is_none() {
976            let status = std::process::Command::new(std::env::current_exe().unwrap())
977                .args([
978                    "--exact",
979                    "cli::schema_cli::tests::compatibility_ping_command_denies_without_trusted_local_service",
980                    "--nocapture",
981                ])
982                .env("HYPRSTREAM_DISCOVERY_PING_DENIAL_CHILD", "1")
983                .status()
984                .unwrap();
985            assert!(status.success(), "isolated denial child failed: {status}");
986            return;
987        }
988
989        let matches = build_tool_command()
990            .try_get_matches_from(["tool", "discovery", "ping"])
991            .unwrap();
992        let (_, service_matches) = matches.subcommand().unwrap();
993        let error = handle_schema_command("discovery", service_matches, test_signing_key())
994            .await
995            .expect_err("ping must fail closed when no resolver is installed");
996        let text = error.to_string();
997        assert!(
998            text.contains("Discovery service trust key is not installed"),
999            "unexpected compatibility denial: {text}"
1000        );
1001    }
1002
1003    #[tokio::test]
1004    async fn required_native_ping_denies_without_resolver_and_never_uses_local_fallback() {
1005        if std::env::var_os("HYPRSTREAM_DISCOVERY_PING_REQUIRED_CHILD").is_none() {
1006            let status = std::process::Command::new(std::env::current_exe().unwrap())
1007                .args([
1008                    "--exact",
1009                    "cli::schema_cli::tests::required_native_ping_denies_without_resolver_and_never_uses_local_fallback",
1010                    "--nocapture",
1011                ])
1012                .env("HYPRSTREAM_DISCOVERY_PING_REQUIRED_CHILD", "1")
1013                .status()
1014                .unwrap();
1015            assert!(
1016                status.success(),
1017                "isolated required-mode child failed: {status}"
1018            );
1019            return;
1020        }
1021
1022        let error = match create_discovery_client_for_profile(&test_signing_key(), true) {
1023            Ok(_) => panic!("required-native Discovery must require resolver evidence"),
1024            Err(error) => error,
1025        };
1026        let text = error.to_string();
1027        assert!(
1028            text.contains("resolver") || text.contains("validated alternative"),
1029            "unexpected required-native denial: {text}"
1030        );
1031    }
1032
1033    /// Selection/signed-response proof over an installed authenticated client:
1034    /// with a bootstrap-installed Discovery client present, the ping command
1035    /// must use that client — not the profile's local-REP branch — even when a
1036    /// local endpoint is registered. The client here rides an IPC stand-in for
1037    /// the installed network reach (selection semantics are transport-
1038    /// independent); the REAL remote DID bootstrap + network reach + accessor
1039    /// integration is proven in `did_trust_e2e.rs`
1040    /// (`did_anchored_bootstrap_boots_end_to_end`). Deployed Policy/MAC
1041    /// acceptance is out of scope for this fixture.
1042    #[tokio::test]
1043    async fn installed_client_ping_uses_installed_reach_not_local_decoy() {
1044        if std::env::var_os("HYPRSTREAM_DISCOVERY_PING_INSTALLED_CHILD").is_none() {
1045            let status = std::process::Command::new(std::env::current_exe().unwrap())
1046                .args([
1047                    "--exact",
1048                    "cli::schema_cli::tests::installed_client_ping_uses_installed_reach_not_local_decoy",
1049                    "--nocapture",
1050                ])
1051                .env("HYPRSTREAM_DISCOVERY_PING_INSTALLED_CHILD", "1")
1052                .status()
1053                .unwrap();
1054            assert!(
1055                status.success(),
1056                "isolated remote-node child failed: {status}"
1057            );
1058            return;
1059        }
1060
1061        use std::collections::HashSet;
1062        use std::sync::Arc;
1063        use tokio::sync::{oneshot, Notify};
1064
1065        crate::mac::install_explicit_test_dispatch_pep();
1066        let service_key = SigningKey::from_bytes(&[9u8; 32]);
1067        let caller_key = test_signing_key();
1068        let caller_pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&caller_key);
1069        let caller_pq_vk = hyprstream_rpc::crypto::pq::ml_dsa_vk_from_bytes(
1070            &hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&caller_pq),
1071        )
1072        .unwrap();
1073        let service_pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&service_key);
1074        let service_pq_vk = hyprstream_rpc::crypto::pq::ml_dsa_vk_from_bytes(
1075            &hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&service_pq),
1076        )
1077        .unwrap();
1078        let mut pq_store = hyprstream_rpc::envelope::KeyedPqTrustStore::new();
1079        pq_store.bind(caller_key.verifying_key().to_bytes(), &caller_pq_vk);
1080        pq_store.bind(service_key.verifying_key().to_bytes(), &service_pq_vk);
1081        let _ = hyprstream_rpc::envelope::install_verify_config(
1082            hyprstream_rpc::envelope::EnvelopeVerifyConfig {
1083                policy: hyprstream_rpc::crypto::CryptoPolicy::Hybrid,
1084                pq_store: Some(Arc::new(pq_store)),
1085            },
1086        );
1087        let mut response_pq_store = hyprstream_rpc::envelope::KeyedPqTrustStore::new();
1088        response_pq_store.bind(service_key.verifying_key().to_bytes(), &service_pq_vk);
1089        let _ = hyprstream_rpc::envelope::install_response_verify_config(
1090            hyprstream_rpc::envelope::ResponseVerifyConfig {
1091                policy: hyprstream_rpc::crypto::CryptoPolicy::Hybrid,
1092                pq_store: Some(Arc::new(response_pq_store)),
1093            },
1094        );
1095
1096        // The installed network reach: a REAL Discovery service serving signed
1097        // responses behind the pinned genuine discovery key. Fixture bound:
1098        // proves selection and signed-response verification over the installed
1099        // client; it does not exercise a remote KEM/PQ dial (bootstrap's own
1100        // tested behavior) or deployed Policy/MAC acceptance.
1101        let reach_dir = tempfile::tempdir().unwrap();
1102        let reach_transport = hyprstream_rpc::transport::TransportConfig::ipc(
1103            reach_dir.path().join("remote-discovery.sock"),
1104        );
1105        hyprstream_service::global_trust_store().insert(
1106            service_key.verifying_key(),
1107            hyprstream_service::Attestation {
1108                scopes: HashSet::from(["discovery".to_owned()]),
1109                subject: None,
1110                jwt: None,
1111                expires_at: 0,
1112                attested_by: None,
1113            },
1114        );
1115        let service = hyprstream_discovery::DiscoveryService::new(
1116            Arc::new(service_key.clone()),
1117            service_key.verifying_key(),
1118            reach_transport.clone(),
1119        )
1120        .with_auth_provider(Box::new(CompatAllowAll));
1121        let bridge = Arc::new(
1122            hyprstream_rpc::transport::iroh_rpc::LocalServiceBridge::spawn(
1123                service,
1124                Arc::new(hyprstream_rpc::envelope::InMemoryNonceCache::new()),
1125                0,
1126            )
1127            .unwrap(),
1128        );
1129        let shutdown = Arc::new(Notify::new());
1130        let (ready_tx, ready_rx) = oneshot::channel();
1131        let server_shutdown = Arc::clone(&shutdown);
1132        let server_transport = reach_transport.clone();
1133        let server_bridge = Arc::clone(&bridge);
1134        let service_vk = service_key.verifying_key();
1135        let spawn_key = service_key.clone();
1136        let server = tokio::spawn(async move {
1137            hyprstream_rpc::service::serve::serve_bridged(
1138                &server_transport,
1139                server_bridge,
1140                spawn_key,
1141                server_shutdown,
1142                Some(ready_tx),
1143            )
1144            .await
1145        });
1146        ready_rx.await.unwrap();
1147
1148        // The client bootstrap installed (authenticated: pinned discovery key)
1149        // — in production this is the DID-anchored remote-node network client.
1150        let installed =
1151            hyprstream_rpc_std::discovery_client::DiscoveryClient::for_local_transport_bootstrap(
1152                &reach_transport,
1153                caller_key.clone(),
1154                service_vk,
1155                None,
1156            )
1157            .unwrap();
1158        hyprstream_discovery::install_bootstrap_discovery_client_fixture(installed)
1159            .expect("install bootstrap client fixture");
1160
1161        // The unusable local decoy: an explicitly registered local Discovery
1162        // REP behind which nothing listens. If selection wrongly took the
1163        // local branch (the P2 defect), the dial here fails.
1164        let decoy_dir = tempfile::tempdir().unwrap();
1165        hyprstream_rpc::registry::init(
1166            hyprstream_rpc::registry::EndpointMode::Ipc,
1167            Some(decoy_dir.path().to_owned()),
1168        );
1169        hyprstream_rpc::registry::try_global()
1170            .unwrap()
1171            .register_rep(
1172                "discovery",
1173                hyprstream_rpc::transport::TransportConfig::ipc(
1174                    decoy_dir.path().join("decoy-discovery.sock"),
1175                ),
1176                None,
1177            );
1178
1179        // Actual command path: ping must succeed over the installed reach.
1180        let matches = build_tool_command()
1181            .try_get_matches_from(["tool", "discovery", "ping"])
1182            .unwrap();
1183        let (_, service_matches) = matches.subcommand().unwrap();
1184        handle_schema_command("discovery", service_matches, caller_key.clone())
1185            .await
1186            .expect("ping must use the installed authenticated network reach");
1187
1188        let args = Value::Object(serde_json::Map::new());
1189        let result = dispatch_top_level("discovery", "ping", &args, caller_key)
1190            .await
1191            .expect("typed Discovery ping over installed reach");
1192        assert_eq!(result["status"], "ok");
1193
1194        shutdown.notify_waiters();
1195        server.await.unwrap().unwrap();
1196        bridge.shutdown().await.unwrap();
1197    }
1198
1199    /// Dead-endpoint control for the remote-node selection test: the identical
1200    /// rig WITHOUT the installed client fails on the dead local decoy, so the
1201    /// success above is attributable to the installed reach, not the rig.
1202    #[tokio::test]
1203    async fn remote_node_selection_without_installed_client_fails_on_dead_local_decoy() {
1204        if std::env::var_os("HYPRSTREAM_DISCOVERY_PING_REMOTE_CONTROL_CHILD").is_none() {
1205            let status = std::process::Command::new(std::env::current_exe().unwrap())
1206                .args([
1207                    "--exact",
1208                    "cli::schema_cli::tests::remote_node_selection_without_installed_client_fails_on_dead_local_decoy",
1209                    "--nocapture",
1210                ])
1211                .env("HYPRSTREAM_DISCOVERY_PING_REMOTE_CONTROL_CHILD", "1")
1212                .status()
1213                .unwrap();
1214            assert!(status.success(), "isolated control child failed: {status}");
1215            return;
1216        }
1217
1218        use std::collections::HashSet;
1219
1220        let service_key = SigningKey::from_bytes(&[9u8; 32]);
1221        let caller_key = test_signing_key();
1222        hyprstream_service::global_trust_store().insert(
1223            service_key.verifying_key(),
1224            hyprstream_service::Attestation {
1225                scopes: HashSet::from(["discovery".to_owned()]),
1226                subject: None,
1227                jwt: None,
1228                expires_at: 0,
1229                attested_by: None,
1230            },
1231        );
1232        let decoy_dir = tempfile::tempdir().unwrap();
1233        hyprstream_rpc::registry::init(
1234            hyprstream_rpc::registry::EndpointMode::Ipc,
1235            Some(decoy_dir.path().to_owned()),
1236        );
1237        hyprstream_rpc::registry::try_global()
1238            .unwrap()
1239            .register_rep(
1240                "discovery",
1241                hyprstream_rpc::transport::TransportConfig::ipc(
1242                    decoy_dir.path().join("decoy-discovery.sock"),
1243                ),
1244                None,
1245            );
1246
1247        // No bootstrap client installed: the local branch constructs (trust key
1248        // + registered decoy present) and then fails on the dead socket.
1249        let result = create_discovery_client_for_profile(&caller_key, false);
1250        let client = match result {
1251            Ok(client) => client,
1252            Err(error) => panic!(
1253                "decoy registration must let the local branch construct; it failed earlier: {error}"
1254            ),
1255        };
1256        let error = client
1257            .call_method("ping", &serde_json::Value::Null)
1258            .await
1259            .expect_err("dead local decoy must not serve the ping");
1260        let text = error.to_string();
1261        assert!(
1262            !text.contains("installed"),
1263            "unexpected control failure shape: {text}"
1264        );
1265    }
1266
1267    #[tokio::test]
1268    async fn compatibility_ping_uses_trusted_local_discovery_service() {
1269        // Keep the process-global registry and trust store isolated from the
1270        // rest of the test suite while exercising the real command path.
1271        if std::env::var_os("HYPRSTREAM_DISCOVERY_PING_COMPAT_CHILD").is_none() {
1272            let status = std::process::Command::new(std::env::current_exe().unwrap())
1273                .args([
1274                    "--exact",
1275                    "cli::schema_cli::tests::compatibility_ping_uses_trusted_local_discovery_service",
1276                    "--nocapture",
1277                ])
1278                .env("HYPRSTREAM_DISCOVERY_PING_COMPAT_CHILD", "1")
1279                .status()
1280                .unwrap();
1281            assert!(
1282                status.success(),
1283                "isolated compatibility child failed: {status}"
1284            );
1285            return;
1286        }
1287
1288        use std::collections::HashSet;
1289        use std::sync::Arc;
1290        use tokio::sync::{oneshot, Notify};
1291
1292        crate::mac::install_explicit_test_dispatch_pep();
1293        let service_key = SigningKey::from_bytes(&[9u8; 32]);
1294        let caller_key = test_signing_key();
1295        let caller_pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&caller_key);
1296        let caller_pq_vk = hyprstream_rpc::crypto::pq::ml_dsa_vk_from_bytes(
1297            &hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&caller_pq),
1298        )
1299        .unwrap();
1300        let service_pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&service_key);
1301        let service_pq_vk = hyprstream_rpc::crypto::pq::ml_dsa_vk_from_bytes(
1302            &hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&service_pq),
1303        )
1304        .unwrap();
1305        let mut pq_store = hyprstream_rpc::envelope::KeyedPqTrustStore::new();
1306        pq_store.bind(caller_key.verifying_key().to_bytes(), &caller_pq_vk);
1307        pq_store.bind(service_key.verifying_key().to_bytes(), &service_pq_vk);
1308        let _ = hyprstream_rpc::envelope::install_verify_config(
1309            hyprstream_rpc::envelope::EnvelopeVerifyConfig {
1310                policy: hyprstream_rpc::crypto::CryptoPolicy::Hybrid,
1311                pq_store: Some(Arc::new(pq_store)),
1312            },
1313        );
1314        let mut response_pq_store = hyprstream_rpc::envelope::KeyedPqTrustStore::new();
1315        response_pq_store.bind(service_key.verifying_key().to_bytes(), &service_pq_vk);
1316        let _ = hyprstream_rpc::envelope::install_response_verify_config(
1317            hyprstream_rpc::envelope::ResponseVerifyConfig {
1318                policy: hyprstream_rpc::crypto::CryptoPolicy::Hybrid,
1319                pq_store: Some(Arc::new(response_pq_store)),
1320            },
1321        );
1322        let runtime_dir = tempfile::tempdir().unwrap();
1323        let transport = hyprstream_rpc::transport::TransportConfig::ipc(
1324            runtime_dir.path().join("discovery.sock"),
1325        );
1326        hyprstream_rpc::registry::init(
1327            hyprstream_rpc::registry::EndpointMode::Ipc,
1328            Some(runtime_dir.path().to_owned()),
1329        );
1330        hyprstream_service::global_trust_store().insert(
1331            service_key.verifying_key(),
1332            hyprstream_service::Attestation {
1333                scopes: HashSet::from(["discovery".to_owned()]),
1334                subject: None,
1335                jwt: None,
1336                expires_at: 0,
1337                attested_by: None,
1338            },
1339        );
1340
1341        let service = hyprstream_discovery::DiscoveryService::new(
1342            Arc::new(service_key.clone()),
1343            service_key.verifying_key(),
1344            transport.clone(),
1345        )
1346        .with_auth_provider(Box::new(CompatAllowAll));
1347        let bridge = Arc::new(
1348            hyprstream_rpc::transport::iroh_rpc::LocalServiceBridge::spawn(
1349                service,
1350                Arc::new(hyprstream_rpc::envelope::InMemoryNonceCache::new()),
1351                0,
1352            )
1353            .unwrap(),
1354        );
1355        let shutdown = Arc::new(Notify::new());
1356        let (ready_tx, ready_rx) = oneshot::channel();
1357        let server_shutdown = Arc::clone(&shutdown);
1358        let server_transport = transport.clone();
1359        let server_bridge = Arc::clone(&bridge);
1360        let server = tokio::spawn(async move {
1361            hyprstream_rpc::service::serve::serve_bridged(
1362                &server_transport,
1363                server_bridge,
1364                service_key,
1365                server_shutdown,
1366                Some(ready_tx),
1367            )
1368            .await
1369        });
1370        ready_rx.await.unwrap();
1371
1372        let matches = build_tool_command()
1373            .try_get_matches_from(["tool", "discovery", "ping"])
1374            .unwrap();
1375        let (_, service_matches) = matches.subcommand().unwrap();
1376        handle_schema_command("discovery", service_matches, caller_key.clone())
1377            .await
1378            .expect("compatibility ping should reach the local generated service");
1379
1380        let args = Value::Object(serde_json::Map::new());
1381        let result = dispatch_top_level("discovery", "ping", &args, caller_key)
1382            .await
1383            .expect("generated Discovery ping should return a response");
1384        assert_eq!(result["status"], "ok");
1385        assert!(result["serviceCount"].as_u64().is_some());
1386        assert!(result["uptime"].as_u64().is_some());
1387
1388        shutdown.notify_waiters();
1389        server.await.unwrap().unwrap();
1390        bridge.shutdown().await.unwrap();
1391    }
1392
1393    struct CompatAllowAll;
1394
1395    #[async_trait::async_trait(?Send)]
1396    impl hyprstream_discovery::AuthorizationProvider for CompatAllowAll {
1397        async fn check(
1398            &self,
1399            _subject: &str,
1400            _domain: &str,
1401            _resource: &str,
1402            _operation: &str,
1403            _bearer: Option<&str>,
1404        ) -> Result<bool> {
1405            Ok(true)
1406        }
1407    }
1408}