ucp-schema 1.3.0

Runtime resolution of UCP schema annotations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
//! UCP Schema CLI
//!
//! Command-line interface for resolving and validating UCP schemas.

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::{Parser, Subcommand};
use ucp_schema::{
    bundle_refs, bundle_refs_with_url_mapping, compose_from_payload, compose_schema,
    detect_direction, extract_capabilities, extract_capabilities_from_profile,
    extract_jsonrpc_payload, is_url, lint, load_schema, load_schema_auto, resolve,
    select_operation_schema, validate, ComposeError, DetectedDirection, Direction, FileStatus,
    ResolveError, ResolveOptions, SchemaBaseConfig, ValidateError,
};

/// Errors with associated CLI exit codes.
trait CliExitCode {
    fn exit_code(&self) -> u8;
}

impl CliExitCode for ResolveError {
    fn exit_code(&self) -> u8 {
        ResolveError::exit_code(self) as u8
    }
}

impl CliExitCode for ComposeError {
    fn exit_code(&self) -> u8 {
        ComposeError::exit_code(self) as u8
    }
}

/// Map an error to a CLI exit code, reporting it in the configured format.
fn cli_err<E: std::fmt::Display + CliExitCode>(json_output: bool) -> impl FnOnce(E) -> u8 {
    move |e| {
        report_error(json_output, &e.to_string());
        e.exit_code()
    }
}

/// Like cli_err but with a message prefix for additional context.
fn cli_err_ctx<'a, E: std::fmt::Display + CliExitCode>(
    json_output: bool,
    context: &'a str,
) -> impl FnOnce(E) -> u8 + 'a {
    move |e| {
        report_error(json_output, &format!("{}: {}", context, e));
        e.exit_code()
    }
}

/// Determine direction from CLI flags and optional inference.
///
/// Priority: explicit --request/--response flags override inference.
/// When neither flag is set, uses inferred direction if available.
fn determine_direction(
    request_flag: bool,
    response_flag: bool,
    inferred: Option<Direction>,
) -> Option<Direction> {
    if request_flag {
        Some(Direction::Request)
    } else if response_flag {
        Some(Direction::Response)
    } else {
        inferred
    }
}

#[cfg(feature = "remote")]
use ucp_schema::bundle_refs_remote;

#[derive(Parser)]
#[command(name = "ucp-schema")]
#[command(about = "Resolve and validate UCP schema annotations")]
#[command(version)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Resolve a schema for a specific direction and operation.
    /// Accepts a schema file or a self-describing payload (auto-composes if payload detected).
    Resolve {
        /// Schema or payload source: file path or URL (http:// or https://)
        schema: String,

        /// Resolve for request direction (auto-inferred for payloads)
        #[arg(long, conflicts_with = "response")]
        request: bool,

        /// Resolve for response direction (auto-inferred for payloads)
        #[arg(long, conflicts_with = "request")]
        response: bool,

        /// Operation to resolve for (e.g., create, update, read)
        #[arg(long, short)]
        op: String,

        /// Select an explicit $defs entry to output (e.g. search_response,
        /// business_schema, error_response), overriding the {op}_{direction}
        /// derivation for container-shaped schemas.
        #[arg(long)]
        def: Option<String>,

        /// Output file (stdout if not specified)
        #[arg(long)]
        output: Option<PathBuf>,

        /// Pretty-print JSON output
        #[arg(long)]
        pretty: bool,

        /// Dereference all $ref pointers (bundle into single schema; schema input only)
        #[arg(long)]
        bundle: bool,

        /// Local directory containing schema files (used when input is a payload)
        #[arg(long)]
        schema_local_base: Option<PathBuf>,

        /// URL prefix to strip when mapping to local (e.g., https://ucp.dev/draft)
        #[arg(long, requires = "schema_local_base")]
        schema_remote_base: Option<String>,

        /// Strict mode: set additionalProperties=false to reject unknown fields (default: false)
        #[arg(long, default_value_t = false, action = clap::ArgAction::Set)]
        strict: bool,

        /// Include future fields: omit-visibility fields with a transition targeting
        /// non-omit (planned additions). Surfaces them with x-ucp-schema-transition
        /// metadata but does not add to required.
        #[arg(long)]
        include_future: bool,

        /// Print pipeline stages to stderr for debugging
        #[arg(long, short)]
        verbose: bool,
    },

    /// Validate a payload against a resolved schema
    Validate {
        /// Payload file to validate
        payload: PathBuf,

        /// Explicit schema (default: infer from payload's UCP metadata)
        #[arg(long)]
        schema: Option<String>,

        /// Local directory containing schema files
        #[arg(long)]
        schema_local_base: Option<PathBuf>,

        /// URL prefix to strip when mapping to local (e.g., https://ucp.dev/draft)
        #[arg(long, requires = "schema_local_base")]
        schema_remote_base: Option<String>,

        /// Agent profile URL (REST pattern: profile via header, payload is raw object)
        #[arg(long, conflicts_with = "schema")]
        profile: Option<String>,

        /// Validate as request (auto-inferred if omitted)
        #[arg(long, conflicts_with = "response")]
        request: bool,

        /// Validate as response (auto-inferred if omitted)
        #[arg(long, conflicts_with = "request")]
        response: bool,

        /// Operation to validate for (e.g., create, update, read)
        #[arg(long, short)]
        op: String,

        /// Validate against an explicit $defs entry (e.g. search_response,
        /// business_schema, error_response), overriding the {op}_{direction}
        /// derivation. Works on any schema that defines the named $def.
        #[arg(long)]
        def: Option<String>,

        /// Output results as JSON (for automation)
        #[arg(long)]
        json: bool,

        /// Strict mode: reject unknown fields (default: false)
        #[arg(long, default_value_t = false, action = clap::ArgAction::Set)]
        strict: bool,

        /// Print pipeline stages to stderr for debugging
        #[arg(long, short)]
        verbose: bool,
    },

    /// Compose capability schemas from a self-describing payload (annotations preserved)
    Compose {
        /// Payload file with UCP capabilities metadata
        payload: PathBuf,

        /// Local directory containing schema files
        #[arg(long)]
        schema_local_base: Option<PathBuf>,

        /// URL prefix to strip when mapping to local (e.g., https://ucp.dev/draft)
        #[arg(long, requires = "schema_local_base")]
        schema_remote_base: Option<String>,

        /// Output file (stdout if not specified)
        #[arg(long)]
        output: Option<PathBuf>,

        /// Pretty-print JSON output
        #[arg(long)]
        pretty: bool,

        /// Print pipeline stages to stderr for debugging
        #[arg(long, short)]
        verbose: bool,
    },

    /// Lint schema files for errors (syntax, broken refs, invalid annotations)
    Lint {
        /// File or directory to lint
        path: PathBuf,

        /// Output format: text (default) or json
        #[arg(long, default_value = "text")]
        format: String,

        /// Treat warnings as errors
        #[arg(long)]
        strict: bool,

        /// Suppress progress output, only show errors
        #[arg(long, short)]
        quiet: bool,
    },
}

fn main() -> ExitCode {
    let cli = Cli::parse();

    let result = match cli.command {
        Commands::Resolve {
            schema,
            request,
            response,
            op,
            def,
            output,
            pretty,
            bundle,
            schema_local_base,
            schema_remote_base,
            strict,
            include_future,
            verbose,
        } => run_resolve(
            &schema,
            request,
            response,
            op,
            def,
            output,
            pretty,
            bundle,
            schema_local_base,
            schema_remote_base,
            strict,
            include_future,
            verbose,
        ),

        Commands::Compose {
            payload,
            schema_local_base,
            schema_remote_base,
            output,
            pretty,
            verbose,
        } => run_compose(
            &payload,
            schema_local_base,
            schema_remote_base,
            output,
            pretty,
            verbose,
        ),

        Commands::Validate {
            payload,
            schema,
            schema_local_base,
            schema_remote_base,
            profile,
            request,
            response,
            op,
            def,
            json,
            strict,
            verbose,
        } => run_validate(ValidateArgs {
            payload,
            schema,
            schema_local_base,
            schema_remote_base,
            profile,
            request,
            response,
            op,
            def,
            json_output: json,
            strict,
            verbose,
        }),

        Commands::Lint {
            path,
            format,
            strict,
            quiet,
        } => run_lint(&path, &format, strict, quiet),
    };

    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(code) => ExitCode::from(code),
    }
}

/// Resolve a schema for a specific direction and operation.
///
/// Auto-detects input type: if the input is a self-describing payload (has
/// ucp.capabilities or meta.profile), composes schemas first then resolves.
/// Otherwise resolves the schema directly.
#[allow(clippy::too_many_arguments)]
fn run_resolve(
    schema_source: &str,
    request: bool,
    response: bool,
    op: String,
    def: Option<String>,
    output: Option<PathBuf>,
    pretty: bool,
    bundle: bool,
    schema_local_base: Option<PathBuf>,
    schema_remote_base: Option<String>,
    strict: bool,
    include_future: bool,
    verbose: bool,
) -> Result<(), u8> {
    if verbose {
        eprintln!("[load] reading {}", schema_source);
    }
    let mut input = load_schema_auto(schema_source).map_err(cli_err(false))?;

    // Auto-detect: is this a payload (needs compose) or a schema (resolve directly)?
    let detected = detect_direction(&input);

    // Flag validation: --bundle only applies to schema file input, not payloads
    if detected.is_some() && bundle {
        report_error(false, "--bundle does not apply to payload input (schemas are auto-composed from capabilities). Remove --bundle, or pass a schema file instead of a payload.");
        return Err(2);
    }

    let schema = if detected.is_some() {
        // Input is a self-describing payload — compose schemas from capabilities
        let config = SchemaBaseConfig {
            local_base: schema_local_base.as_deref(),
            remote_base: schema_remote_base.as_deref(),
        };
        if verbose {
            verbose_capabilities(&input, &config);
            eprintln!("[compose] composing schemas from payload capabilities");
        }
        compose_from_payload(&input, &config).map_err(cli_err(false))?
    } else {
        if verbose {
            eprintln!("[detect] input is a schema file (no ucp.capabilities)");
        }
        // Input is a schema file — bundle $refs if requested
        if bundle {
            if verbose {
                match (schema_local_base.as_deref(), schema_remote_base.as_deref()) {
                    (Some(local), Some(remote)) => eprintln!(
                        "[bundle] inlining $ref pointers (mapping {} -> {})",
                        remote,
                        local.display()
                    ),
                    _ => eprintln!("[bundle] inlining $ref pointers"),
                }
            }
            bundle_local_refs(
                &mut input,
                schema_source,
                &schema_local_base,
                &schema_remote_base,
                false,
            )?;
        }
        input
    };

    // Direction: explicit flag > auto-inferred from payload > require explicit
    let direction = determine_direction(request, response, detected.map(Direction::from))
        .ok_or_else(|| {
            report_error(
                false,
                "--request or --response is required for schema input",
            );
            2u8
        })?;

    let options = ResolveOptions::new(direction, &op)
        .strict(strict)
        .include_future(include_future)
        .def_name(def);
    if verbose {
        let mut flags = Vec::new();
        if strict {
            flags.push("strict");
        }
        if include_future {
            flags.push("include-future");
        }
        let suffix = if flags.is_empty() {
            String::new()
        } else {
            format!(" ({})", flags.join(", "))
        };
        eprintln!(
            "[resolve] resolving for {}/{}{}",
            direction
                .annotation_key()
                .strip_prefix("ucp_")
                .unwrap_or(direction.annotation_key()),
            op,
            suffix
        );
    }
    let resolved = resolve(&schema, &options).map_err(cli_err(false))?;

    // `resolve` defaults to emitting the full resolved schema (container $defs
    // intact). Only an explicit --def slices to a single $def; auto-derivation
    // is a validate-time concern, so standalone `resolve` never auto-selects.
    let output_value = if options.def_name.is_some() {
        select_operation_schema(&resolved, &options).map_err(cli_err(false))?
    } else {
        resolved
    };

    write_json_output(&output_value, output, pretty)
}

/// Pure composition: merge capability schemas from a self-describing payload.
/// Output preserves UCP annotations (no resolve step).
fn run_compose(
    payload_path: &Path,
    schema_local_base: Option<PathBuf>,
    schema_remote_base: Option<String>,
    output: Option<PathBuf>,
    pretty: bool,
    verbose: bool,
) -> Result<(), u8> {
    if verbose {
        eprintln!("[load] reading {}", payload_path.display());
    }
    let payload = load_schema(payload_path).map_err(cli_err_ctx(false, "loading payload"))?;

    // Verify input is a self-describing payload
    if detect_direction(&payload).is_none() {
        report_error(false, "input is not a self-describing payload (missing ucp.capabilities or meta.profile). Use `resolve` for schema files.");
        return Err(2);
    }

    let config = SchemaBaseConfig {
        local_base: schema_local_base.as_deref(),
        remote_base: schema_remote_base.as_deref(),
    };
    if verbose {
        verbose_capabilities(&payload, &config);
        eprintln!("[compose] composing schemas (annotations preserved)");
    }
    let schema = compose_from_payload(&payload, &config).map_err(cli_err(false))?;

    write_json_output(&schema, output, pretty)
}

struct ValidateArgs {
    payload: PathBuf,
    schema: Option<String>,
    schema_local_base: Option<PathBuf>,
    schema_remote_base: Option<String>,
    profile: Option<String>,
    request: bool,
    response: bool,
    op: String,
    def: Option<String>,
    json_output: bool,
    strict: bool,
    verbose: bool,
}

fn run_validate(args: ValidateArgs) -> Result<(), u8> {
    let ValidateArgs {
        payload: payload_path,
        schema: schema_source,
        schema_local_base,
        schema_remote_base,
        profile: profile_url,
        request,
        response,
        op,
        def,
        json_output,
        strict,
        verbose,
    } = args;

    // Note: --schema-local-base/--schema-remote-base apply to both modes:
    // - Self-describing: passed to compose for capability schema URL resolution
    // - Explicit --schema: used for URL-to-local mapping when bundling $ref values

    let config = SchemaBaseConfig {
        local_base: schema_local_base.as_deref(),
        remote_base: schema_remote_base.as_deref(),
    };

    // Load payload file
    if verbose {
        eprintln!("[load] reading payload {}", payload_path.display());
    }
    let payload_file =
        load_schema(&payload_path).map_err(cli_err_ctx(json_output, "loading payload"))?;

    // Determine validation mode and extract actual payload to validate:
    // 1. --profile: REST pattern, payload is raw object
    // 2. --schema: explicit schema, payload is raw object
    // 3. JSONRPC: meta.profile in payload, extract nested payload
    // 4. Response: ucp.capabilities in payload, payload is self-describing
    let (schema, payload, direction) = if let Some(ref profile) = profile_url {
        // REST pattern: --profile flag provides profile URL, payload is raw
        if verbose {
            eprintln!("[detect] REST pattern: using --profile {}", profile);
        }
        let direction = determine_direction(request, response, None).unwrap_or(Direction::Request);

        let capabilities =
            extract_capabilities_from_profile(profile, &config).map_err(cli_err(json_output))?;

        if verbose {
            eprintln!(
                "[compose] composing {} capability schemas from profile",
                capabilities.len()
            );
        }
        let schema = compose_schema(&capabilities, &config).map_err(cli_err(json_output))?;

        (schema, payload_file, direction)
    } else if let Some(ref source) = schema_source {
        // Explicit schema: try to infer direction from payload
        if verbose {
            eprintln!("[load] using explicit schema: {}", source);
        }
        let inferred = detect_direction(&payload_file).map(Direction::from);
        let direction =
            determine_direction(request, response, inferred).unwrap_or(Direction::Request);

        let mut schema =
            load_schema_auto(source).map_err(cli_err_ctx(json_output, "loading schema"))?;

        // Bundle refs based on source type and available mappings
        #[cfg(feature = "remote")]
        {
            if is_url(source) {
                bundle_refs_remote(&mut schema, source)
                    .map_err(cli_err_ctx(json_output, "bundling refs"))?;
            } else {
                bundle_local_refs(
                    &mut schema,
                    source,
                    &schema_local_base,
                    &schema_remote_base,
                    json_output,
                )?;
            }
        }
        #[cfg(not(feature = "remote"))]
        {
            bundle_local_refs(
                &mut schema,
                source,
                &schema_local_base,
                &schema_remote_base,
                json_output,
            )?;
        }

        (schema, payload_file, direction)
    } else {
        // Self-describing mode - detect from payload structure
        match detect_direction(&payload_file) {
            Some(DetectedDirection::Response) => {
                // Response: ucp.capabilities, compose and validate full payload
                if verbose {
                    verbose_capabilities(&payload_file, &config);
                    eprintln!("[compose] composing schemas from payload capabilities");
                }
                let direction = determine_direction(request, response, Some(Direction::Response))
                    .unwrap_or(Direction::Response);
                let schema =
                    compose_from_payload(&payload_file, &config).map_err(cli_err(json_output))?;
                (schema, payload_file, direction)
            }
            Some(DetectedDirection::Request) => {
                // JSONRPC request: meta.profile, extract nested payload
                let direction = determine_direction(request, response, Some(Direction::Request))
                    .unwrap_or(Direction::Request);

                // Get profile URL from meta.profile
                let profile = payload_file
                    .get("meta")
                    .and_then(|m| m.get("profile"))
                    .and_then(|p| p.as_str())
                    .ok_or_else(|| {
                        report_error(json_output, "JSONRPC request missing meta.profile");
                        2u8
                    })?;

                if verbose {
                    eprintln!("[detect] JSONRPC request: fetching profile {}", profile);
                }

                let capabilities = extract_capabilities_from_profile(profile, &config)
                    .map_err(cli_err(json_output))?;

                // Extract actual payload from envelope (e.g., "checkout" key)
                let (nested_payload, _key) = extract_jsonrpc_payload(&payload_file, &capabilities)
                    .map_err(cli_err(json_output))?;

                if verbose {
                    eprintln!(
                        "[compose] composing {} capability schemas from profile",
                        capabilities.len()
                    );
                }
                let schema =
                    compose_schema(&capabilities, &config).map_err(cli_err(json_output))?;

                (schema, nested_payload.clone(), direction)
            }
            None => {
                report_error(
                    json_output,
                    "cannot infer direction: payload has no ucp.capabilities (response) or meta.profile (request). Use --schema, --profile, --request, or --response.",
                );
                return Err(2);
            }
        }
    };

    let options = ResolveOptions::new(direction, op)
        .strict(strict)
        .def_name(def);
    if verbose {
        eprintln!(
            "[resolve] resolving for {}/{}",
            direction
                .annotation_key()
                .strip_prefix("ucp_")
                .unwrap_or(direction.annotation_key()),
            options.operation
        );
        eprintln!("[validate] validating payload against resolved schema");
    }

    match validate(&schema, &payload, &options) {
        Ok(()) => {
            if json_output {
                println!(r#"{{"valid":true}}"#);
            } else {
                println!("Valid");
            }
            Ok(())
        }
        Err(ValidateError::Invalid { errors, .. }) => {
            if json_output {
                let output = serde_json::json!({
                    "valid": false,
                    "errors": errors
                });
                println!("{}", output);
            } else {
                eprintln!("Validation failed:");
                for error in errors {
                    eprintln!("  {}", error);
                }
            }
            Err(1)
        }
        Err(ValidateError::Resolve(e)) => {
            report_error(json_output, &e.to_string());
            Err(e.exit_code() as u8)
        }
    }
}

/// Shared helper: serialize JSON and write to output or stdout.
fn write_json_output(
    value: &serde_json::Value,
    output: Option<PathBuf>,
    pretty: bool,
) -> Result<(), u8> {
    let json = if pretty {
        serde_json::to_string_pretty(value)
    } else {
        serde_json::to_string(value)
    }
    .map_err(|e| {
        eprintln!("Error serializing output: {}", e);
        2u8
    })?;

    match output {
        Some(path) => {
            std::fs::write(&path, &json).map_err(|e| {
                eprintln!("Error writing to {}: {}", path.display(), e);
                3u8
            })?;
        }
        None => {
            println!("{}", json);
        }
    }

    Ok(())
}

/// Print capability details to stderr for --verbose mode.
/// Best-effort: silently skips if extraction fails (errors surface later).
fn verbose_capabilities(payload: &serde_json::Value, config: &SchemaBaseConfig) {
    if let Ok(caps) = extract_capabilities(payload, config) {
        let roots: Vec<_> = caps.iter().filter(|c| c.extends.is_none()).collect();
        let exts: Vec<_> = caps.iter().filter(|c| c.extends.is_some()).collect();
        eprintln!(
            "[detect] payload with {} capabilities ({} root, {} extensions)",
            caps.len(),
            roots.len(),
            exts.len()
        );
        for cap in &caps {
            let kind = if cap.extends.is_some() { "ext" } else { "root" };
            eprintln!("[detect]   {} {}{}", kind, cap.name, cap.schema_url);
        }
    }
}

/// Bundle refs for a local schema file.
fn bundle_local_refs(
    schema: &mut serde_json::Value,
    source: &str,
    schema_local_base: &Option<PathBuf>,
    schema_remote_base: &Option<String>,
    json_output: bool,
) -> Result<(), u8> {
    let schema_dir = Path::new(source).parent().unwrap_or(Path::new("."));

    if let (Some(local_base), Some(remote_base)) = (schema_local_base, schema_remote_base) {
        bundle_refs_with_url_mapping(schema, schema_dir, local_base, remote_base)
            .map_err(cli_err_ctx(json_output, "bundling refs"))?;
    } else {
        bundle_refs(schema, schema_dir).map_err(cli_err_ctx(json_output, "bundling refs"))?;
    }

    Ok(())
}

/// Output an error message in plain text or JSON format.
///
/// Uses same shape as validation errors for consistent API:
/// `{"valid": false, "errors": [{"path": "", "message": "..."}]}`
fn report_error(json_output: bool, msg: &str) {
    if json_output {
        let output = serde_json::json!({
            "valid": false,
            "errors": [{"path": "", "message": msg}]
        });
        println!("{}", output);
    } else {
        eprintln!("Error: {}", msg);
    }
}

fn run_lint(path: &Path, format: &str, strict: bool, quiet: bool) -> Result<(), u8> {
    use ucp_schema::Severity;

    if !path.exists() {
        eprintln!("Error: path not found: {}", path.display());
        return Err(2);
    }

    let result = lint(path, strict);

    if format == "json" {
        println!("{}", serde_json::to_string_pretty(&result).unwrap());
    } else {
        // Text output
        if !quiet {
            println!("Linting {} ...\n", path.display());
        }

        for file_result in &result.results {
            let status_icon = match file_result.status {
                FileStatus::Ok => "\x1b[32m✓\x1b[0m",
                FileStatus::Warning => "\x1b[33m⚠\x1b[0m",
                FileStatus::Error => "\x1b[31m✗\x1b[0m",
            };

            if !quiet || file_result.status != FileStatus::Ok {
                println!("  {} {}", status_icon, file_result.file.display());
            }

            for diag in &file_result.diagnostics {
                let color = match diag.severity {
                    Severity::Error => "\x1b[31m",
                    Severity::Warning => "\x1b[33m",
                };
                if !quiet || diag.severity == Severity::Error {
                    println!(
                        "    {}{}[{}]\x1b[0m: {} - {}",
                        color,
                        match diag.severity {
                            Severity::Error => "error",
                            Severity::Warning => "warning",
                        },
                        diag.code,
                        diag.path,
                        diag.message
                    );
                }
            }
        }

        println!();
        if result.is_ok() && (!strict || result.warnings == 0) {
            println!(
                "\x1b[32m✓ {} files checked, all passed\x1b[0m",
                result.files_checked
            );
        } else {
            println!(
                "\x1b[31m✗ {} files checked: {} passed, {} failed ({} errors, {} warnings)\x1b[0m",
                result.files_checked, result.passed, result.failed, result.errors, result.warnings
            );
        }
    }

    if result.is_ok() && (!strict || result.warnings == 0) {
        Ok(())
    } else {
        Err(1)
    }
}