net-cli 0.45.1

Unified `net-mesh` command-line tool for the Net mesh
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
//! `net-mesh transfer`-style command family `net-mesh typegen
//! (generate|snapshot|diff)` — generate typed language bindings
//! (TypeScript, Python) from discovered `ToolDescriptor`s
//! (`TYPEGEN_CLI_PLAN.md`).
//!
//! Descriptors come from one of two sources:
//!
//! - **Live discovery** — remote-attach to a mesh node (same flags as the
//!   `net-mesh aggregator` / `net-mesh transfer` verbs), let the capability fold
//!   populate, then `Mesh::list_tools`. Requires the attach flags.
//! - **Snapshot** — read a [`TypegenSnapshot`] JSON file pinned by an
//!   earlier `typegen snapshot`. Reproducible and offline; the path CI and
//!   golden tests use.
//!
//! Codegen itself is pure: `ToolDescriptor` → source files
//! (`schema.rs` parses the JSON Schema once into a language-neutral IR;
//! `ts.rs` / `python.rs` render it). The CLI plumbs source → codegen →
//! disk.

mod diff;
mod live;
mod python;
mod schema;
mod ts;

use std::path::{Path, PathBuf};
use std::time::Duration;

use clap::{Args, Subcommand, ValueEnum};
use serde::{Deserialize, Serialize};

use crate::commands::aggregator::RemoteAttachArgs;
use crate::context::{require_remote_attach, resolve_profile, CliContext};
use crate::error::{generic, invalid_args, CliError};
use crate::prelude::{emit_value, OutputFormat};

use net_sdk::tool::ToolDescriptor;

/// Snapshot format version. Bump on a non-additive shape change.
const SNAPSHOT_FORMAT_VERSION: u32 = 1;

#[derive(Subcommand, Debug)]
pub enum TypegenCommand {
    /// Generate typed bindings for tools matching a query (or from a snapshot).
    Generate(GenerateArgs),
    /// Pin currently discoverable tools into a snapshot file for
    /// reproducible later regeneration.
    Snapshot(SnapshotArgs),
    /// Show the schema-evolution diff between two snapshots.
    Diff(DiffArgs),
}

/// Target language for `generate`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
pub enum Language {
    /// TypeScript (`.d.ts` interfaces + `.ts` call helpers).
    Ts,
    /// Python (Pydantic v2 models + `.pyi` stubs).
    Python,
}

#[derive(Args, Debug)]
pub struct GenerateArgs {
    /// Language target.
    #[arg(long, value_enum)]
    pub language: Language,

    /// Tag filter — include a tool if ANY of its tags match. Applied to
    /// both live discovery and snapshot sources.
    #[arg(long = "tag", num_args = 1.., value_name = "TAG")]
    pub tags: Vec<String>,

    /// Explicit tool IDs to generate for (exact match). Applied to both
    /// live discovery and snapshot sources.
    #[arg(long = "tool", num_args = 1.., value_name = "TOOL_ID")]
    pub tools: Vec<String>,

    /// Read descriptors from a snapshot file instead of live discovery.
    #[arg(long, value_name = "PATH")]
    pub from_snapshot: Option<PathBuf>,

    /// Output directory. Created if missing.
    #[arg(long, default_value = "./generated")]
    pub out: PathBuf,

    #[arg(long)]
    pub identity: Option<PathBuf>,
    #[arg(long, default_value_t = crate::prelude::DEFAULT_SUPERVISOR_NODE)]
    pub node: u64,
    #[command(flatten)]
    pub attach: RemoteAttachArgs,
}

#[derive(Args, Debug)]
pub struct SnapshotArgs {
    /// Tag filter — include a tool if ANY of its tags match.
    #[arg(long = "tag", num_args = 1.., value_name = "TAG")]
    pub tags: Vec<String>,
    /// Explicit tool IDs to capture (exact match).
    #[arg(long = "tool", num_args = 1.., value_name = "TOOL_ID")]
    pub tools: Vec<String>,
    /// Snapshot file to write.
    #[arg(long, value_name = "PATH")]
    pub out: PathBuf,

    #[arg(long)]
    pub identity: Option<PathBuf>,
    #[arg(long, default_value_t = crate::prelude::DEFAULT_SUPERVISOR_NODE)]
    pub node: u64,
    #[command(flatten)]
    pub attach: RemoteAttachArgs,
}

#[derive(Args, Debug)]
pub struct DiffArgs {
    /// Baseline snapshot.
    #[arg(long, value_name = "PATH")]
    pub from: PathBuf,
    /// Updated snapshot to compare against the baseline.
    #[arg(long, value_name = "PATH")]
    pub to: PathBuf,
    /// Exit non-zero (code 14) when any BREAKING change is detected — for
    /// gating CI on schema evolution. The report is still printed.
    #[arg(long)]
    pub exit_code: bool,
}

// ── snapshot format ─────────────────────────────────────────────────

/// Pinned, source-control-friendly capture of a `list_tools` result.
/// Deterministic given the same query against the same mesh state.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypegenSnapshot {
    /// Snapshot format version (`SNAPSHOT_FORMAT_VERSION`).
    pub format_version: u32,
    /// RFC 3339 UTC capture time. Audit metadata; ignored at regenerate.
    pub captured_at: String,
    /// The query that produced this snapshot.
    pub source_query: SnapshotQuery,
    /// Descriptors in `list_tools` order.
    pub descriptors: Vec<ToolDescriptor>,
}

/// The filter a snapshot was captured with (for audit / re-execution).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SnapshotQuery {
    /// `--tag` values (empty = no tag filter).
    pub tags: Vec<String>,
    /// `--tool` values (empty = no id filter).
    pub tools: Vec<String>,
}

// ── codegen interface ───────────────────────────────────────────────

/// One file a renderer wants written, relative to the output dir.
pub struct GeneratedFile {
    /// Path relative to `--out` (forward slashes; mapped to the OS sep).
    pub rel_path: String,
    /// File contents.
    pub contents: String,
}

/// Generation-time provenance threaded into file headers + `meta.json`.
pub struct GenMeta {
    /// Human label of the source (`"live discovery"` or the snapshot path).
    pub source_label: String,
    /// RFC 3339 capture time carried from the snapshot, or generation time.
    pub captured_at: String,
    /// Snapshot format version, for the emitted metadata file.
    pub format_version: u32,
}

pub async fn run(
    cmd: TypegenCommand,
    output: Option<OutputFormat>,
    config_path: Option<&std::path::Path>,
    profile_name: &str,
    deadline: Option<crate::deadline::Deadline>,
) -> Result<(), CliError> {
    match cmd {
        TypegenCommand::Generate(args) => {
            run_generate(args, output, config_path, profile_name, deadline).await
        }
        TypegenCommand::Snapshot(args) => {
            run_snapshot(args, output, config_path, profile_name, deadline).await
        }
        TypegenCommand::Diff(args) => run_diff(args, output).await,
    }
}

// ── generate ────────────────────────────────────────────────────────

async fn run_generate(
    args: GenerateArgs,
    output: Option<OutputFormat>,
    config_path: Option<&std::path::Path>,
    profile_name: &str,
    deadline: Option<crate::deadline::Deadline>,
) -> Result<(), CliError> {
    let (descriptors, meta) = match &args.from_snapshot {
        Some(path) => {
            if args.attach.has_target_flags() {
                return Err(invalid_args("remote target/bind flags are for live typegen; remove them when using --from-snapshot"));
            }
            if args.attach.inspect_target {
                let profile = resolve_profile(config_path, profile_name).await?;
                let mut view = crate::target::TargetInspection::local(&profile, "offline");
                view.source = Some(path.clone());
                view.destination = Some(args.out.clone());
                view.provenance("mode", "flag");
                view.provenance("source", "flag");
                view.provenance("destination", "flag");
                return view.emit(output);
            }
            load_snapshot_source(path, &args.tags, &args.tools)?
        }
        None => {
            let Some(ctx) = crate::deadline::run_optional(
                deadline,
                prepare_live_context(
                    &args.attach,
                    args.identity.as_deref(),
                    args.node,
                    config_path,
                    profile_name,
                    output,
                    &args.out,
                ),
            )
            .await?
            else {
                return Ok(());
            };
            crate::deadline::run_optional(
                deadline,
                fetch_live_source(&args.tags, &args.tools, ctx, deadline),
            )
            .await?
        }
    };

    // Legacy offline snapshots keep their skip behavior. Live acquisition
    // has already required a usable input schema for every selected tool.
    let mut skipped: Vec<String> = Vec::new();
    let usable: Vec<ToolDescriptor> = descriptors
        .into_iter()
        .filter(|d| {
            if d.input_schema.is_none() {
                eprintln!(
                    "warning: tool `{}` has no input schema in the saved snapshot; \
                     binding skipped. Capture a new live snapshot to fetch metadata.",
                    d.tool_id
                );
                skipped.push(d.tool_id.clone());
                false
            } else {
                true
            }
        })
        .collect();

    // Nothing matched (empty mesh, over-narrow --tag/--tool, or every tool
    // skipped): say so, since `generate` otherwise reports success while
    // writing only the index + metadata files.
    if usable.is_empty() {
        eprintln!(
            "warning: no tools to generate (after filters and schema skips); \
             only index + metadata files will be written."
        );
    }

    // Distinct tool ids can sanitize to the same module basename and would
    // silently overwrite each other's files. That's data loss, so refuse the
    // run and tell the operator exactly which ids clash.
    let collisions = basename_collisions(&usable);
    if !collisions.is_empty() {
        let detail = collisions
            .iter()
            .map(|(base, ids)| {
                format!(
                    "`{base}` ← {}",
                    ids.iter()
                        .map(|id| format!("`{id}`"))
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            })
            .collect::<Vec<_>>()
            .join("; ");
        return Err(invalid_args(format!(
            "tool ids collide after sanitization and would overwrite each other's generated \
             files: {detail}. Rename a tool id, or narrow the set with --tag / --tool."
        )));
    }

    let files = match args.language {
        Language::Ts => ts::generate(&usable, &meta, &mut skipped)?,
        Language::Python => python::generate(&usable, &meta, &mut skipped)?,
    };

    if args.from_snapshot.is_none() && !skipped.is_empty() {
        return Err(invalid_args(format!(
            "live typegen cannot render selected tools: {}; no output was written",
            skipped.join(", ")
        )));
    }

    let written = write_generated(&args.out, &files).await?;

    let view = GenerateView {
        language: format!("{:?}", args.language).to_lowercase(),
        tool_count: usable.len() as u64,
        files_written: written,
        skipped,
        out: args.out.display().to_string(),
    };
    emit_value(OutputFormat::resolve_oneshot(output), &view)
        .map_err(|e| generic(format!("write typegen generate result: {e}")))?;
    Ok(())
}

// ── snapshot ────────────────────────────────────────────────────────

async fn run_snapshot(
    args: SnapshotArgs,
    output: Option<OutputFormat>,
    config_path: Option<&std::path::Path>,
    profile_name: &str,
    deadline: Option<crate::deadline::Deadline>,
) -> Result<(), CliError> {
    let Some(ctx) = crate::deadline::run_optional(
        deadline,
        prepare_live_context(
            &args.attach,
            args.identity.as_deref(),
            args.node,
            config_path,
            profile_name,
            output,
            &args.out,
        ),
    )
    .await?
    else {
        return Ok(());
    };
    let (descriptors, _meta) = crate::deadline::run_optional(
        deadline,
        fetch_live_source(&args.tags, &args.tools, ctx, deadline),
    )
    .await?;

    let schema_bytes: u64 = descriptors
        .iter()
        .map(|d| {
            d.input_schema.as_ref().map(|s| s.len()).unwrap_or(0) as u64
                + d.output_schema.as_ref().map(|s| s.len()).unwrap_or(0) as u64
        })
        .sum();

    let snapshot = TypegenSnapshot {
        format_version: SNAPSHOT_FORMAT_VERSION,
        captured_at: now_rfc3339(),
        source_query: SnapshotQuery {
            tags: args.tags.clone(),
            tools: args.tools.clone(),
        },
        descriptors,
    };

    // Pretty + stable so snapshots diff cleanly in source control.
    let json = serde_json::to_string_pretty(&snapshot)
        .map_err(|e| generic(format!("serialize snapshot: {e}")))?;
    if let Some(parent) = args.out.parent() {
        if !parent.as_os_str().is_empty() {
            tokio::fs::create_dir_all(parent)
                .await
                .map_err(|e| generic(format!("create snapshot dir {}: {e}", parent.display())))?;
        }
    }
    tokio::fs::write(&args.out, json.as_bytes())
        .await
        .map_err(|e| generic(format!("write snapshot {}: {e}", args.out.display())))?;

    let view = SnapshotView {
        tool_count: snapshot.descriptors.len() as u64,
        schema_bytes,
        out: args.out.display().to_string(),
    };
    emit_value(OutputFormat::resolve_oneshot(output), &view)
        .map_err(|e| generic(format!("write typegen snapshot result: {e}")))?;
    Ok(())
}

// ── diff ────────────────────────────────────────────────────────────

async fn run_diff(args: DiffArgs, output: Option<OutputFormat>) -> Result<(), CliError> {
    let from = read_snapshot(&args.from)?;
    let to = read_snapshot(&args.to)?;
    let report = diff::diff(&from, &to);

    match OutputFormat::resolve_oneshot(output) {
        // Human formats get the operator-facing report; machine formats get
        // the structured tree.
        OutputFormat::Table | OutputFormat::Text => {
            print!("{}", diff::render_text(&report));
        }
        format => {
            emit_value(format, &report).map_err(|e| generic(format!("write typegen diff: {e}")))?;
        }
    }

    if args.exit_code && report.breaking_count > 0 {
        return Err(CliError::new(
            crate::error::ExitCodeKind::TypegenBreakingChanges,
            format!(
                "{} BREAKING schema change(s) detected",
                report.breaking_count
            ),
        ));
    }
    Ok(())
}

// ── descriptor sources ──────────────────────────────────────────────

/// Read descriptors from a snapshot file, optionally narrowing by `--tag`
/// / `--tool`. Returns the descriptors + provenance for file headers.
fn load_snapshot_source(
    path: &Path,
    tags: &[String],
    tools: &[String],
) -> Result<(Vec<ToolDescriptor>, GenMeta), CliError> {
    let snapshot = read_snapshot(path)?;
    let meta = GenMeta {
        source_label: format!("snapshot {}", path.display()),
        captured_at: snapshot.captured_at.clone(),
        format_version: snapshot.format_version,
    };
    let descriptors = filter_descriptors(snapshot.descriptors, tags, tools);
    Ok((descriptors, meta))
}

/// Read + validate a snapshot file into a [`TypegenSnapshot`].
fn read_snapshot(path: &Path) -> Result<TypegenSnapshot, CliError> {
    let bytes = std::fs::read(path)
        .map_err(|e| generic(format!("read snapshot {}: {e}", path.display())))?;
    let snapshot: TypegenSnapshot = serde_json::from_slice(&bytes).map_err(|e| {
        invalid_args(format!(
            "snapshot {} is not a valid TypegenSnapshot: {e}",
            path.display()
        ))
    })?;
    if snapshot.format_version != SNAPSHOT_FORMAT_VERSION {
        return Err(invalid_args(format!(
            "snapshot {} has format_version {} (this build understands {})",
            path.display(),
            snapshot.format_version,
            SNAPSHOT_FORMAT_VERSION
        )));
    }
    Ok(snapshot)
}

/// Resolve once, then either emit inspection or attach for live discovery.
async fn prepare_live_context(
    attach: &RemoteAttachArgs,
    identity: Option<&Path>,
    node: u64,
    config_path: Option<&std::path::Path>,
    profile_name: &str,
    output: Option<OutputFormat>,
    destination: &Path,
) -> Result<Option<CliContext>, CliError> {
    let profile = resolve_profile(config_path, profile_name).await?;
    let remote = require_remote_attach(&profile, attach, || {
        invalid_args(
            "net-mesh typegen live discovery needs a mesh target: pass --node-addr <IP:PORT> \
             --node-pubkey <HEX> --node-id <N> --psk-hex <HEX> (each defaultable in the \
             profile), or use --from-snapshot for offline generation.",
        )
    })?;
    if attach.inspect_target {
        let mut view =
            crate::target::inspect(&profile, attach, identity, Some(&remote), "remote").await?;
        view.destination = Some(destination.to_path_buf());
        view.emit(output)?;
        return Ok(None);
    }
    CliContext::build_with_remote(&profile, identity, node, false, remote)
        .await
        .map(Some)
}

async fn fetch_live_source(
    tags: &[String],
    tools: &[String],
    ctx: CliContext,
    deadline: Option<crate::deadline::Deadline>,
) -> Result<(Vec<ToolDescriptor>, GenMeta), CliError> {
    let mesh = ctx.require_mesh()?;
    let descriptors = Box::pin(live::acquire(mesh, tags, tools, deadline)).await?;
    // Broad observation may legitimately end empty, but must not imply that
    // the entire mesh has no tools (or that a requested ID was satisfied).
    if descriptors.is_empty() {
        eprintln!(
            "warning: live discovery found no tools within 5s — the capability fold may still \
             be populating, or this node advertises none; proceeding with an empty set."
        );
    }

    let meta = GenMeta {
        source_label: "live discovery".to_string(),
        captured_at: now_rfc3339(),
        format_version: SNAPSHOT_FORMAT_VERSION,
    };
    Ok((descriptors, meta))
}

/// Await every explicitly requested ID after both filters. Without IDs,
/// observe the whole bounded window; this is not a complete mesh inventory.
/// The caller's absolute CLI deadline can interrupt this observation.
async fn discover_with_timeout(
    mut observe: impl FnMut() -> Vec<ToolDescriptor>,
    tags: &[String],
    requested: &[String],
    budget: Duration,
) -> Result<Vec<ToolDescriptor>, CliError> {
    let end = tokio::time::Instant::now() + budget;
    loop {
        let selected = filter_descriptors(observe(), tags, requested);
        let missing: std::collections::BTreeSet<&str> = requested
            .iter()
            .filter(|id| !selected.iter().any(|d| d.tool_id == **id))
            .map(String::as_str)
            .collect();
        if !requested.is_empty() && missing.is_empty() {
            return Ok(selected);
        }
        if tokio::time::Instant::now() >= end {
            if !missing.is_empty() {
                return Err(CliError::new(
                    crate::error::ExitCodeKind::Timeout,
                    format!(
                        "live discovery budget elapsed; requested tools not observed after filters: {}. This does not prove mesh-wide absence; no output was written.",
                        missing.into_iter().collect::<Vec<_>>().join(", ")
                    ),
                ));
            }
            return Ok(selected);
        }
        tokio::time::sleep_until(
            (tokio::time::Instant::now() + Duration::from_millis(200)).min(end),
        )
        .await;
    }
}

/// Apply `--tag` (ANY-match over `descriptor.tags`) and `--tool` (exact id)
/// filters. Empty filters are no-ops.
fn filter_descriptors(
    descriptors: Vec<ToolDescriptor>,
    tags: &[String],
    tools: &[String],
) -> Vec<ToolDescriptor> {
    let by_tag: Vec<ToolDescriptor> = if tags.is_empty() {
        descriptors
    } else {
        descriptors
            .into_iter()
            .filter(|d| d.tags.iter().any(|t| tags.contains(t)))
            .collect()
    };
    filter_by_tools(by_tag, tools)
}

/// Groups of tool ids that sanitize to the same [`module_basename`] (only
/// genuine collisions — groups of size ≥ 2 — are returned, sorted by basename
/// for deterministic output).
fn basename_collisions(descriptors: &[ToolDescriptor]) -> Vec<(String, Vec<String>)> {
    let mut groups: std::collections::BTreeMap<String, Vec<String>> =
        std::collections::BTreeMap::new();
    for d in descriptors {
        groups
            .entry(module_basename(&d.tool_id))
            .or_default()
            .push(d.tool_id.clone());
    }
    groups
        .into_iter()
        .filter(|(_, ids)| ids.len() > 1)
        .collect()
}

fn filter_by_tools(descriptors: Vec<ToolDescriptor>, tools: &[String]) -> Vec<ToolDescriptor> {
    if tools.is_empty() {
        descriptors
    } else {
        descriptors
            .into_iter()
            .filter(|d| tools.contains(&d.tool_id))
            .collect()
    }
}

// ── output writer ───────────────────────────────────────────────────

/// Write every generated file under `out`, creating parent dirs. Returns
/// the file count.
async fn write_generated(out: &Path, files: &[GeneratedFile]) -> Result<u64, CliError> {
    for file in files {
        let dest = out.join(rel_to_os_path(&file.rel_path));
        if let Some(parent) = dest.parent() {
            tokio::fs::create_dir_all(parent)
                .await
                .map_err(|e| generic(format!("create dir {}: {e}", parent.display())))?;
        }
        tokio::fs::write(&dest, file.contents.as_bytes())
            .await
            .map_err(|e| generic(format!("write {}: {e}", dest.display())))?;
    }
    Ok(files.len() as u64)
}

/// Map a forward-slash relative path to an OS path.
fn rel_to_os_path(rel: &str) -> PathBuf {
    rel.split('/').collect()
}

// ── shared naming helpers ───────────────────────────────────────────

/// PascalCase a tool id for a type name: `acme/web_search` → `AcmeWebSearch`.
/// Splits on any non-alphanumeric character; a leading digit is prefixed
/// with `_` so the result is a valid identifier.
pub(crate) fn pascal_case(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut new_word = true;
    for ch in s.chars() {
        if ch.is_ascii_alphanumeric() {
            if new_word {
                out.extend(ch.to_uppercase());
            } else {
                out.push(ch);
            }
            new_word = false;
        } else {
            new_word = true;
        }
    }
    if out.chars().next().is_some_and(|c| c.is_ascii_digit()) {
        out.insert(0, '_');
    }
    if out.is_empty() {
        out.push('_');
    }
    out
}

/// Filesystem-safe module base name: every char outside `[A-Za-z0-9_]`
/// becomes `_`. `acme/web_search` → `acme_web_search`.
pub(crate) fn module_basename(tool_id: &str) -> String {
    let mut out: String = tool_id
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect();
    if out.chars().next().is_some_and(|c| c.is_ascii_digit()) {
        out.insert(0, '_');
    }
    if out.is_empty() {
        out.push('_');
    }
    out
}

/// RFC 3339 UTC timestamp for "now". Hand-rolled (no time crate in the CLI
/// deps) via the civil-from-days algorithm.
fn now_rfc3339() -> String {
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let days = (secs / 86_400) as i64;
    let rem = secs % 86_400;
    let (h, mi, s) = (rem / 3600, (rem % 3600) / 60, rem % 60);
    let (y, m, d) = civil_from_days(days);
    format!("{y:04}-{m:02}-{d:02}T{h:02}:{mi:02}:{s:02}Z")
}

/// Days since the Unix epoch → `(year, month, day)` (Howard Hinnant's
/// `civil_from_days`).
fn civil_from_days(z: i64) -> (i64, u32, u32) {
    let z = z + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
    let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
    (if m <= 2 { y + 1 } else { y }, m, d)
}

// ── output views ────────────────────────────────────────────────────

#[derive(Serialize)]
struct GenerateView {
    language: String,
    tool_count: u64,
    files_written: u64,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    skipped: Vec<String>,
    out: String,
}

#[derive(Serialize)]
struct SnapshotView {
    tool_count: u64,
    schema_bytes: u64,
    out: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pascal_case_handles_separators_and_digits() {
        assert_eq!(pascal_case("acme/web_search"), "AcmeWebSearch");
        assert_eq!(pascal_case("vendor.tool-name"), "VendorToolName");
        assert_eq!(pascal_case("3d_render"), "_3dRender");
        assert_eq!(pascal_case("already"), "Already");
    }

    #[test]
    fn module_basename_sanitizes() {
        assert_eq!(module_basename("acme/web_search"), "acme_web_search");
        assert_eq!(module_basename("a.b/c"), "a_b_c");
        assert_eq!(module_basename("9lives"), "_9lives");
    }

    #[test]
    fn civil_from_days_known_dates() {
        assert_eq!(civil_from_days(0), (1970, 1, 1));
        assert_eq!(civil_from_days(18_993), (2022, 1, 1));
    }

    pub(super) fn desc(tool_id: &str) -> ToolDescriptor {
        ToolDescriptor {
            tool_id: tool_id.into(),
            name: tool_id.into(),
            version: "1.0.0".into(),
            description: None,
            input_schema: None,
            output_schema: None,
            requires: vec![],
            estimated_time_ms: 0,
            stateless: true,
            streaming: false,
            tags: vec![],
            pricing_terms: None,
            node_count: 1,
        }
    }

    #[tokio::test]
    async fn discovery_waits_for_all_requested_ids_after_tag_filtering() {
        let mut observations = 0;
        let result = discover_with_timeout(
            || {
                observations += 1;
                let mut wanted = desc("wanted");
                if observations > 1 {
                    wanted.tags.push("selected".into());
                }
                vec![desc("unrelated"), wanted, desc("second")]
            },
            &["selected".into()],
            &["wanted".into()],
            Duration::from_millis(20),
        )
        .await
        .unwrap();
        assert_eq!(observations, 2);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].tool_id, "wanted");
    }

    #[tokio::test]
    async fn discovery_missing_ids_fail_and_broad_selection_observes_full_window() {
        let error = discover_with_timeout(
            || vec![desc("present")],
            &[],
            &["present".into(), "missing".into(), "missing".into()],
            Duration::ZERO,
        )
        .await
        .unwrap_err();
        assert!(error
            .to_string()
            .contains("requested tools not observed after filters: missing."));
        let mut observations = 0;
        let result = discover_with_timeout(
            || {
                observations += 1;
                if observations == 1 {
                    vec![desc("early")]
                } else {
                    vec![desc("early"), desc("late")]
                }
            },
            &[],
            &[],
            Duration::from_millis(20),
        )
        .await
        .unwrap();
        assert_eq!(observations, 2);
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn basename_collisions_detects_only_clashing_ids() {
        // `web-search` and `web_search` both sanitize to `web_search`.
        let descriptors = vec![
            desc("acme/web-search"),
            desc("acme/web_search"),
            desc("acme/maps"),
        ];
        let collisions = basename_collisions(&descriptors);
        assert_eq!(collisions.len(), 1, "{collisions:?}");
        assert_eq!(collisions[0].0, "acme_web_search");
        assert_eq!(
            collisions[0].1,
            vec!["acme/web-search".to_string(), "acme/web_search".to_string()]
        );
    }

    #[test]
    fn snapshot_round_trips() {
        let snap = TypegenSnapshot {
            format_version: SNAPSHOT_FORMAT_VERSION,
            captured_at: "2026-06-04T10:00:00Z".into(),
            source_query: SnapshotQuery {
                tags: vec!["search".into()],
                tools: vec![],
            },
            descriptors: vec![],
        };
        let json = serde_json::to_string(&snap).expect("ser");
        let back: TypegenSnapshot = serde_json::from_str(&json).expect("de");
        assert_eq!(back.format_version, SNAPSHOT_FORMAT_VERSION);
        assert_eq!(back.source_query.tags, vec!["search".to_string()]);
    }
}