tatara 0.3.44

tatara — umbrella CLI: fmt, lint, run, test, deploy. Drives feira for static checks, tatara-script for execution, wasm-platform for deploy.
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
//! tatara — umbrella CLI for the pleme-io tatara-lisp ecosystem.
//!
//! One binary, ruthlessly standardized subcommands. Each subcommand
//! either delegates to an existing tool or implements the missing
//! piece directly here.
//!
//! Subcommand map (canonical, rustfmt-style — one way per task):
//!
//! ```text
//!   tatara fmt [path...]              ← delegates to `feira fmt` if available
//!   tatara lint [path...]             ← delegates to `feira lint`
//!   tatara lint --fix [path...]
//!   tatara run <path-or-url> [args]   ← delegates to `tatara-script`
//!   tatara test <path-or-url>         ← delegates to `tatara-script --test`
//!   tatara repl                       ← delegates to `tatara-script --repl`
//!   tatara deploy <github-url>        ← fetch + check + package as ComputeUnit YAML
//!   tatara typecheck <path> [--expand]  build-time gradual typing pass
//! ```
//!
//! `feira` is searched on `$PATH` (typically installed via the caixa
//! workspace). `tatara-script` is searched relative to this binary's
//! directory (release path) and fallback `$PATH`.

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

use anyhow::{bail, Context, Result};
use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(
    name = "tatara",
    version,
    about = "tatara — umbrella CLI: fmt, lint, run, test, deploy"
)]
struct Cli {
    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// Format .tlisp / .lisp files in place via caixa-fmt.
    Fmt {
        /// Paths to format. Default: ./caixa.lisp + every *.tlisp/*.lisp
        /// recursively below cwd.
        #[arg(value_name = "PATH")]
        paths: Vec<PathBuf>,
        /// Just check; don't write.
        #[arg(long)]
        check: bool,
    },

    /// Lint via caixa-lint, optionally autofixing. With --types,
    /// also runs the build-time gradual type checker over each file
    /// and merges its diagnostics into the report.
    Lint {
        #[arg(value_name = "PATH")]
        paths: Vec<PathBuf>,
        /// Apply mechanically-safe autofixes.
        #[arg(long)]
        fix: bool,
        /// Apply heuristic fixes too. Implies --fix.
        #[arg(long)]
        fix_unsafe: bool,
        /// Errors only.
        #[arg(long)]
        errors_only: bool,
        /// Also run the build-time gradual type checker.
        #[arg(long)]
        types: bool,
        /// With --types: macro-expand each file before type-checking, by
        /// running the real interpreter at build time. Reaches annotations
        /// that only exist after expansion (`defn-typed`). Opt-in — see
        /// `tatara typecheck --expand`.
        #[arg(long)]
        expand: bool,
    },

    /// Execute a tatara-lisp script.
    Run {
        /// Local path or URL (github:/gitlab:/codeberg:/https:).
        path_or_url: String,
        /// Arguments forwarded to the script's `argv`.
        #[arg(trailing_var_arg = true)]
        args: Vec<String>,
    },

    /// Run all `(deftest …)` forms in a script + report pass/fail.
    Test { path_or_url: String },

    /// Drop into the interactive REPL.
    Repl,

    /// Run the build-time gradual type-check pass over a .tlisp source.
    /// Reports any (the …) / (declare …) / (define …) annotations whose
    /// inferred type doesn't match.
    Typecheck {
        /// Path to a .tlisp file or a fetchable URL.
        path_or_url: String,
        /// Macro-expand before checking, by RUNNING the real interpreter
        /// at build time.
        ///
        /// Off by default because it is a capability change, not a
        /// precision knob: expansion evaluates user macro BODIES. The
        /// build-time environment installs a denying module loader and
        /// registers no filesystem / process / network natives, so it
        /// cannot read or write; `print` from a macro body still reaches
        /// stdout.
        ///
        /// Turn it on to check `defn-typed` annotations — a procedural
        /// macro, so without expansion its `(the …)` forms do not exist
        /// yet and nothing about them is checked.
        #[arg(long)]
        expand: bool,
    },

    /// Fetch a tatara-lisp program from a URL, run the canonical
    /// pre-flight checks (fmt/lint/test), and emit a ComputeUnit YAML
    /// manifest ready to apply.
    Deploy {
        /// URL — e.g. github:owner/repo/main.tlisp[?ref=v1.0.0]
        url: String,
        /// Output the manifest to this file (default: stdout).
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Skip pre-flight checks (fmt/lint). Speeds up iteration.
        #[arg(long)]
        skip_checks: bool,
        /// ComputeUnit name (default: derived from URL).
        #[arg(long)]
        name: Option<String>,
        /// Target K8s namespace (default: "default").
        #[arg(long, default_value = "default")]
        namespace: String,
    },

    /// Run platform-wide invariant checks against the registered
    /// tatara catalog. Useful in CI gates and as a pre-flight
    /// before promoting a build to a `:tier "prod"` env. Exit
    /// code is non-zero when any invariant fails; the output
    /// names every (invariant, keyword, reason) triple.
    Checks {
        /// Print the full report even when every invariant passes.
        #[arg(long)]
        verbose: bool,
    },

    /// Generate a tatara-lisp domain crate from a typed input
    /// (currently: K8s CRD YAML — single doc or multi-doc bundle).
    /// The generated crate ships #[derive(TataraDomain)] structs +
    /// register() so embedders pull it in like any other crate
    /// and immediately get keyword forms in the Lisp surface.
    ForgeDomain {
        /// Input file. K8s CRD YAML — single CRD or multi-doc bundle.
        #[arg(long)]
        input: PathBuf,
        /// Crate name, by convention `tatara-{thing}`.
        #[arg(long)]
        name: String,
        /// Output directory (created if missing). Holds Cargo.toml,
        /// src/lib.rs, README.md.
        #[arg(long)]
        output: PathBuf,
        /// Print emitted files to stdout instead of writing —
        /// useful for diffing against existing generated output.
        #[arg(long)]
        dry_run: bool,
        /// Emit a Cargo.toml that inherits version / edition / etc.
        /// from the parent workspace and uses path-deps for the
        /// tatara-lisp{,-derive} crates. Use when generating a
        /// crate as a new member of an existing Cargo workspace
        /// (vs a standalone repo).
        #[arg(long)]
        workspace_member: bool,
    },
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    match dispatch(cli) {
        Ok(code) => code,
        Err(e) => {
            eprintln!("tatara: error: {e:#}");
            ExitCode::from(1)
        }
    }
}

fn dispatch(cli: Cli) -> Result<ExitCode> {
    match cli.cmd {
        Cmd::Fmt { paths, check } => run_feira_fmt(&paths, check),
        Cmd::Lint {
            paths,
            fix,
            fix_unsafe,
            errors_only,
            types,
            expand,
        } => {
            let lint = run_feira_lint(&paths, fix, fix_unsafe, errors_only)?;
            if types {
                let tc = typecheck_paths(&paths, expand)?;
                Ok(merge_exit(lint, tc))
            } else {
                Ok(lint)
            }
        }
        Cmd::Run { path_or_url, args } => run_script(&path_or_url, &args, false, false),
        Cmd::Test { path_or_url } => run_script(&path_or_url, &[], true, false),
        Cmd::Repl => run_script("", &[], false, true),
        Cmd::Typecheck {
            path_or_url,
            expand,
        } => typecheck(&path_or_url, expand),
        Cmd::Deploy {
            url,
            output,
            skip_checks,
            name,
            namespace,
        } => deploy(
            &url,
            output.as_deref(),
            skip_checks,
            name.as_deref(),
            &namespace,
        ),
        Cmd::ForgeDomain {
            input,
            name,
            output,
            dry_run,
            workspace_member,
        } => forge_domain(&input, &name, &output, dry_run, workspace_member),
        Cmd::Checks { verbose } => run_platform_checks(verbose),
    }
}

// ── platform checks ──────────────────────────────────────────────

fn run_platform_checks(verbose: bool) -> Result<ExitCode> {
    // Register every catalog crate the CLI knows about so the
    // global registries are populated before the invariants walk.
    // New catalog crates added: include them here. (A future
    // `tatara-platform-registry` crate could collapse this list
    // into a single `register_all()` for further compounding.)
    // A refusal here means two of these catalog crates claim one keyword in
    // ONE binary — the ambiguity is in this process's crate graph, so the
    // honest response is to stop, not to run the invariant walk against a
    // registry whose winner was decided by the order of these four lines.
    tatara_gateway_api::register()?;
    tatara_cilium::register()?;
    tatara_prometheus_operator::register()?;
    tatara_ebpf::register()?;

    let invariants = tatara_platform_checks::default_invariants();
    let run = tatara_platform_checks::run_all(&invariants);
    let fails = run.fail_count();

    if verbose || fails > 0 {
        eprintln!("{}", run.report());
    }

    let kw_count = tatara_lisp::domain::registered_keywords().len();
    eprintln!(
        "tatara checks: {} invariant(s) over {} keyword(s) — {} failure(s)",
        invariants.len(),
        kw_count,
        fails,
    );

    if fails == 0 {
        Ok(ExitCode::SUCCESS)
    } else {
        for (inv, kw, msg) in run.failures() {
            eprintln!("  FAIL  [{inv}] {kw}: {msg}");
        }
        Ok(ExitCode::from(1))
    }
}

// ── domain forge ─────────────────────────────────────────────────

fn forge_domain(
    input: &std::path::Path,
    name: &str,
    output: &std::path::Path,
    dry_run: bool,
    workspace_member: bool,
) -> Result<ExitCode> {
    let domain = tatara_domain_forge::from_crd_yaml(input, name)
        .with_context(|| format!("parsing CRD input {}", input.display()))?;
    let opts = if workspace_member {
        tatara_domain_forge::EmitOptions::workspace_member()
    } else {
        tatara_domain_forge::EmitOptions::default()
    };
    let cargo = tatara_domain_forge::emit_cargo_toml(&domain, &opts);
    let lib = tatara_domain_forge::emit_lib_rs(&domain);
    let readme = tatara_domain_forge::emit_readme(&domain);
    if dry_run {
        println!("───── Cargo.toml ─────\n{cargo}");
        println!("───── src/lib.rs ─────\n{lib}");
        println!("───── README.md ─────\n{readme}");
        return Ok(ExitCode::SUCCESS);
    }
    let src_dir = output.join("src");
    std::fs::create_dir_all(&src_dir).with_context(|| format!("mkdir {}", src_dir.display()))?;
    std::fs::write(output.join("Cargo.toml"), &cargo)
        .with_context(|| format!("write {}/Cargo.toml", output.display()))?;
    std::fs::write(src_dir.join("lib.rs"), &lib)
        .with_context(|| format!("write {}/src/lib.rs", output.display()))?;
    std::fs::write(output.join("README.md"), &readme)
        .with_context(|| format!("write {}/README.md", output.display()))?;
    eprintln!(
        "tatara: forge-domain → wrote {} ({} resource{})",
        output.display(),
        domain.resources.len(),
        if domain.resources.len() == 1 { "" } else { "s" }
    );
    Ok(ExitCode::SUCCESS)
}

// ── feira delegates ──────────────────────────────────────────────

fn find_feira() -> Result<PathBuf> {
    if let Ok(p) = which("feira") {
        return Ok(p);
    }
    bail!(
        "feira not found on $PATH — install it via `cargo install --path \
         caixa/caixa-feira` or build the caixa workspace and put \
         caixa/target/release on $PATH"
    )
}

fn run_feira_fmt(paths: &[PathBuf], check: bool) -> Result<ExitCode> {
    let feira = find_feira()?;
    let mut cmd = Command::new(feira);
    cmd.arg("fmt");
    if check {
        cmd.arg("--check");
    }
    for p in paths {
        cmd.arg(p);
    }
    let status = cmd.status().context("running feira fmt")?;
    Ok(ExitCode::from(status.code().unwrap_or(1) as u8))
}

fn run_feira_lint(
    paths: &[PathBuf],
    fix: bool,
    fix_unsafe: bool,
    errors_only: bool,
) -> Result<ExitCode> {
    let feira = find_feira()?;
    let mut cmd = Command::new(feira);
    cmd.arg("lint");
    if fix {
        cmd.arg("--fix");
    }
    if fix_unsafe {
        cmd.arg("--fix-unsafe");
    }
    if errors_only {
        cmd.arg("--errors-only");
    }
    for p in paths {
        cmd.arg(p);
    }
    let status = cmd.status().context("running feira lint")?;
    Ok(ExitCode::from(status.code().unwrap_or(1) as u8))
}

// ── tatara-script delegates ──────────────────────────────────────

fn find_script() -> Result<PathBuf> {
    // Try sibling binary in the same dir as `tatara` (release builds).
    if let Ok(self_path) = std::env::current_exe() {
        if let Some(parent) = self_path.parent() {
            let sibling = parent.join("tatara-script");
            if sibling.exists() {
                return Ok(sibling);
            }
        }
    }
    if let Ok(p) = which("tatara-script") {
        return Ok(p);
    }
    bail!("tatara-script not found — build it with `cargo build --release` and ensure it's adjacent to `tatara` or on $PATH")
}

fn run_script(path: &str, args: &[String], test: bool, repl: bool) -> Result<ExitCode> {
    let script = find_script()?;
    let mut cmd = Command::new(script);
    if test {
        cmd.arg("--test");
    }
    if repl {
        cmd.arg("--repl");
    }
    if !path.is_empty() {
        cmd.arg(path);
    }
    for a in args {
        cmd.arg(a);
    }
    let status = cmd.status().context("running tatara-script")?;
    Ok(ExitCode::from(status.code().unwrap_or(1) as u8))
}

// ── typecheck ────────────────────────────────────────────────────

/// Run typecheck across many paths (default: every .tlisp under cwd
/// recursively). Returns ExitCode::SUCCESS only if every file is
/// clean.
///
/// `expand` selects the build-phase expansion path. The expansion
/// environment is built ONCE and forked per file: standing it up
/// evaluates the embedded Lisp stdlib (≈1 ms), and per-file isolation is
/// what keeps one file's macros out of the next file's check.
fn typecheck_paths(paths: &[PathBuf], expand: bool) -> Result<ExitCode> {
    let targets: Vec<PathBuf> = if paths.is_empty() {
        find_tlisp_files(std::path::Path::new("."))
    } else {
        paths.to_vec()
    };
    let expander = expand.then(tatara_lisp_eval::build_check::BuildExpander::new);
    let mut total_errors = 0usize;
    let mut total_expansion_failures = 0usize;
    for path in &targets {
        let src =
            std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
        let forms = match tatara_lisp::read_spanned(&src) {
            Ok(f) => f,
            Err(e) => {
                eprintln!("{}: parse error: {e:?}", path.display());
                total_errors += 1;
                continue;
            }
        };
        let (diags, failures) = match &expander {
            Some(exp) => {
                let out = exp.check(&forms);
                (out.diagnostics, out.expansion_failures)
            }
            None => (
                tatara_lisp_eval::build_check::check_program(&forms),
                Vec::new(),
            ),
        };
        // Reduced coverage, not a failure: the form was still checked in
        // its unexpanded shape. Reported so it is never silent, but it
        // does not move the exit code — see `BuildExpander::expand`.
        for f in &failures {
            eprintln!("{}: {}", path.display(), f.render(&src));
        }
        for d in &diags {
            eprintln!("{}: {}", path.display(), d.render(&src));
        }
        total_errors += diags.len();
        total_expansion_failures += failures.len();
    }
    eprintln!(
        "tatara typecheck: {} file(s) checked{}, {} type error(s){}",
        targets.len(),
        if expand { " (macro-expanded)" } else { "" },
        total_errors,
        if total_expansion_failures > 0 {
            format!(", {total_expansion_failures} form(s) left unexpanded")
        } else {
            String::new()
        }
    );
    if total_errors > 0 {
        Ok(ExitCode::from(1))
    } else {
        Ok(ExitCode::SUCCESS)
    }
}

/// Walk a directory, returning every `.tlisp` / `.lisp` file. Used
/// when `tatara lint --types` is run with no explicit paths.
fn find_tlisp_files(root: &std::path::Path) -> Vec<PathBuf> {
    let mut out = Vec::new();
    walk_collect(root, &mut out);
    out
}

fn walk_collect(dir: &std::path::Path, out: &mut Vec<PathBuf>) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let p = entry.path();
        // Skip hidden + target/.git.
        let name = p.file_name().and_then(|s| s.to_str()).unwrap_or("");
        if name.starts_with('.') || name == "target" || name == "node_modules" {
            continue;
        }
        if p.is_dir() {
            walk_collect(&p, out);
        } else if p.extension().is_some_and(|e| e == "tlisp" || e == "lisp") {
            out.push(p);
        }
    }
}

/// Merge two exit codes — non-zero wins so the caller sees the
/// failing pass even if the other succeeded.
fn merge_exit(a: ExitCode, b: ExitCode) -> ExitCode {
    if is_success(&a) && is_success(&b) {
        ExitCode::SUCCESS
    } else {
        ExitCode::from(1)
    }
}

fn typecheck(path_or_url: &str, expand: bool) -> Result<ExitCode> {
    let resolved =
        tatara_lisp_source::resolve_once(path_or_url).context("resolving source for typecheck")?;
    let src = String::from_utf8(resolved.bytes).context("source is not UTF-8")?;
    let forms =
        tatara_lisp::read_spanned(&src).map_err(|e| anyhow::anyhow!("parse error: {e:?}"))?;
    let diags = if expand {
        let out = tatara_lisp_eval::build_check::check_program_expanded(&forms);
        for f in &out.expansion_failures {
            eprintln!("{path_or_url}: {}", f.render(&src));
        }
        out.diagnostics
    } else {
        tatara_lisp_eval::build_check::check_program(&forms)
    };
    if diags.is_empty() {
        eprintln!("tatara typecheck: 0 errors");
        return Ok(ExitCode::SUCCESS);
    }
    for d in &diags {
        eprintln!("{}: {}", path_or_url, d.render(&src));
    }
    eprintln!("tatara typecheck: {} type error(s)", diags.len());
    Ok(ExitCode::from(1))
}

// ── deploy ───────────────────────────────────────────────────────

fn deploy(
    url: &str,
    output: Option<&std::path::Path>,
    skip_checks: bool,
    name: Option<&str>,
    namespace: &str,
) -> Result<ExitCode> {
    eprintln!("tatara deploy: resolving {url}");
    let resolved = tatara_lisp_source::resolve_once(url).context("resolving source")?;
    let bytes_len = resolved.bytes.len();
    let blake3 = resolved.blake3.clone();
    eprintln!(
        "tatara deploy: fetched {bytes_len} bytes, blake3={}",
        &blake3[..16]
    );

    if !skip_checks {
        // Write to a temp file so feira fmt --check + feira lint can run.
        let tmp = tempfile_path(".tlisp")?;
        std::fs::write(&tmp, &resolved.bytes).context("writing temp source")?;
        eprintln!("tatara deploy: pre-flight fmt --check");
        let fmt_ok = run_feira_fmt(&[tmp.clone()], true)?;
        if !is_success(&fmt_ok) {
            // Don't hard-fail — fmt drift on remote sources is common.
            eprintln!("tatara deploy: WARN format drift detected; continuing");
        }
        eprintln!("tatara deploy: pre-flight lint");
        let lint_ok = run_feira_lint(&[tmp.clone()], false, false, true)?;
        if !is_success(&lint_ok) {
            eprintln!("tatara deploy: lint errors; continuing (use --skip-checks to silence)");
        }
        let _ = std::fs::remove_file(&tmp);
    }

    // Default the unit name from the URL: last segment without extension.
    let unit_name = name
        .map(str::to_string)
        .unwrap_or_else(|| derive_unit_name(url));

    let manifest = compute_unit_manifest(&unit_name, namespace, url, &blake3);
    let yaml = serde_yaml::to_string(&manifest).context("rendering YAML")?;

    if let Some(path) = output {
        std::fs::write(path, &yaml).with_context(|| format!("writing {}", path.display()))?;
        eprintln!("tatara deploy: wrote manifest to {}", path.display());
    } else {
        print!("{yaml}");
    }

    eprintln!("tatara deploy: ready. apply with:\n  kubectl -n {namespace} apply -f -");
    Ok(ExitCode::SUCCESS)
}

fn is_success(code: &ExitCode) -> bool {
    // ExitCode doesn't expose its inner u8 publicly; format!-roundtrip
    // is the cleanest way to inspect.
    let s = format!("{code:?}");
    s.contains('0')
}

fn derive_unit_name(url: &str) -> String {
    // Strip query/fragment, take last `/`-segment, drop extension.
    let stem = url
        .split(['?', '#'])
        .next()
        .unwrap_or(url)
        .trim_end_matches('/')
        .rsplit('/')
        .next()
        .unwrap_or("tatara-program");
    let stem = stem.split('.').next().unwrap_or(stem);
    let mut out = String::with_capacity(stem.len());
    for c in stem.chars() {
        if c.is_ascii_alphanumeric() || c == '-' {
            out.push(c.to_ascii_lowercase());
        } else {
            out.push('-');
        }
    }
    if out.is_empty() {
        "tatara-program".into()
    } else {
        out
    }
}

#[derive(Debug, serde::Serialize)]
struct ComputeUnit {
    api_version: &'static str,
    kind: &'static str,
    metadata: ComputeUnitMeta,
    spec: ComputeUnitSpec,
}

#[derive(Debug, serde::Serialize)]
struct ComputeUnitMeta {
    name: String,
    namespace: String,
    annotations: std::collections::BTreeMap<String, String>,
}

#[derive(Debug, serde::Serialize)]
struct ComputeUnitSpec {
    source: ComputeUnitSource,
    shape: &'static str,
}

#[derive(Debug, serde::Serialize)]
struct ComputeUnitSource {
    url: String,
    blake3: String,
}

fn compute_unit_manifest(name: &str, namespace: &str, url: &str, blake3: &str) -> ComputeUnit {
    let mut annotations = std::collections::BTreeMap::new();
    annotations.insert("tatara.pleme.io/source-url".to_string(), url.to_string());
    annotations.insert(
        "tatara.pleme.io/source-blake3".to_string(),
        blake3.to_string(),
    );
    ComputeUnit {
        api_version: "compute.pleme.io/v1alpha1",
        kind: "ComputeUnit",
        metadata: ComputeUnitMeta {
            name: name.to_string(),
            namespace: namespace.to_string(),
            annotations,
        },
        spec: ComputeUnitSpec {
            source: ComputeUnitSource {
                url: url.to_string(),
                blake3: blake3.to_string(),
            },
            // Default shape: program. wasm-operator picks the right
            // runtime template based on this hint. Other shapes
            // (job/function/service/controller) need additional flags
            // we'll add as the deploy story matures.
            shape: "program",
        },
    }
}

// ── helpers ──────────────────────────────────────────────────────

fn which(name: &str) -> Result<PathBuf> {
    let path_var = std::env::var_os("PATH").context("PATH not set")?;
    for entry in std::env::split_paths(&path_var) {
        let candidate = entry.join(name);
        if candidate.is_file() {
            return Ok(candidate);
        }
    }
    bail!("{name} not found on PATH")
}

fn tempfile_path(extension: &str) -> Result<PathBuf> {
    use std::time::{SystemTime, UNIX_EPOCH};
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let mut tmp = std::env::temp_dir();
    tmp.push(format!("tatara-{nanos}{extension}"));
    Ok(tmp)
}