tessera-command 0.5.12

The tesserax command: opens a recipe, then serves, fetches or runs tasks
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
//! `teleport`: copies tesserax over ssh or runs a command remotely.

use crate::source::Stop;
use crate::version;
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet};
use std::fs::{self, File};
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{SystemTime, UNIX_EPOCH};
use tessera_frontend::tasks::task::Shown;

const SSH: [&str; 4] = ["-o", "ConnectTimeout=15", "-o", "BatchMode=yes"];
const ROOT: &str = "$HOME/.cache/tessera/bin";
const SCHEMES: [&str; 6] = [
    "hf:",
    "kindling:",
    "catalog:",
    "git+",
    "http://",
    "https://",
];

/// `uname -sm`, platform and release asset of each machine kind.
pub const PLATFORMS: [(&str, &str, &str); 3] = [
    ("Darwin arm64", "aarch64-macos", "tesserax-darwin-arm64"),
    ("Linux aarch64", "aarch64-linux", "tesserax-linux-arm64"),
    ("Linux x86_64", "x86_64-linux", "tesserax-linux-x64"),
];

#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Mode {
    Copy(Vec<String>),
    Run { host: String, command: Vec<String> },
}

#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Args {
    pub(crate) from: Option<PathBuf>,
    pub(crate) root: String,
    pub(crate) mode: Mode,
}

/// A probed host: platform, asset, root and binary path.
struct Host {
    platform: &'static str,
    asset: &'static str,
    root: String,
    dest: String,
}

/// A build source: a local file or a release URL.
enum Build {
    File(PathBuf),
    Url(String),
}

/// One argument after local/remote path classification.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum PathArg {
    Keep(String),
    Local {
        prefix: String,
        path: PathBuf,
        suffix: String,
    },
}

enum StagedKind {
    Missing,
    File { sha: String },
    Dir,
}

struct Staged {
    local: PathBuf,
    slot_dir: String,
    remote: String,
    name: String,
    kind: StagedKind,
}

pub(crate) fn parse(rest: &[String]) -> Result<Args, Stop> {
    let mut from = None;
    let mut root = ROOT.to_string();
    let mut host: Option<String> = None;
    let mut hosts = Vec::new();
    let mut command = Vec::new();
    let mut i = 0;
    while i < rest.len() {
        let arg = &rest[i];
        match arg.as_str() {
            "--from" => {
                from = Some(rest.get(i + 1).ok_or(Stop::Usage)?.into());
                i += 2;
            }
            "--root" => {
                root = rest.get(i + 1).ok_or(Stop::Usage)?.clone();
                i += 2;
            }
            "--host" if host.is_none() && hosts.is_empty() => {
                host = Some(rest.get(i + 1).ok_or(Stop::Usage)?.clone());
                i += 2;
            }
            "--" if host.is_some() => {
                command = rest[i + 1..].to_vec();
                break;
            }
            _ if host.is_some() => {
                command = rest[i..].to_vec();
                break;
            }
            _ if arg.starts_with('-') => return Err(Stop::Usage),
            _ => {
                hosts.push(arg.clone());
                i += 1;
            }
        }
    }
    let mode = match host {
        Some(host) if !command.is_empty() => Mode::Run { host, command },
        None if !hosts.is_empty() => Mode::Copy(hosts),
        _ => return Err(Stop::Usage),
    };
    Ok(Args { from, root, mode })
}

/// Whether a `teleport` invocation runs a remote command.
#[cfg(feature = "tern")]
pub(crate) fn runs_remote(rest: &[String]) -> bool {
    matches!(
        parse(rest),
        Ok(Args {
            mode: Mode::Run { .. },
            ..
        })
    )
}

pub fn quote(text: &str) -> String {
    format!("'{}'", text.replace('\'', r"'\''"))
}

/// Runs a sh script on `host`, or here for `local`.
fn shell(host: &str, script: &str) -> Result<String, String> {
    let mut cmd = Command::new(if host == "local" { "sh" } else { "ssh" });
    if host == "local" {
        cmd.arg("-c").arg(script);
    } else {
        cmd.args(SSH)
            .arg(host)
            .arg(format!("sh -c {}", quote(script)));
    }
    let out = cmd.output().map_err(|e| format!("{host}: {e}"))?;
    if out.status.success() {
        return Ok(String::from_utf8_lossy(&out.stdout).trim().to_string());
    }
    let err = String::from_utf8_lossy(&out.stderr);
    let last = err.trim().lines().last().unwrap_or("failed").to_string();
    Err(format!("{host}: {last}"))
}

/// A file's SHA-256 on `host`, empty when missing.
fn hash(host: &str, path: &str) -> Result<String, String> {
    let f = quote(path);
    let sum = format!("(sha256sum {f} 2>/dev/null || shasum -a 256 {f} 2>/dev/null)");
    shell(host, &format!("{sum} | cut -c1-64"))
}

pub fn platform(uname: &str) -> Option<(&'static str, &'static str)> {
    let found = PLATFORMS.iter().find(|p| p.0 == uname.trim())?;
    Some((found.1, found.2))
}

fn probe(host: &str, root: &str) -> Result<Host, String> {
    let out = shell(host, &format!("uname -sm; echo \"{root}\""))?;
    let (uname, root) = out.split_once('\n').ok_or(format!("{host}: no uname"))?;
    let (platform, asset) = platform(uname).ok_or(format!("{host}: no build for {uname}"))?;
    let root = root.trim().to_string();
    let dest = format!("{}/{}/tesserax", root, version::id());
    Ok(Host {
        platform,
        asset,
        root,
        dest,
    })
}

/// The release asset URL and its sha256 from `SHA256SUMS`.
fn release(asset: &str) -> Result<(Build, String), String> {
    let tag = format!("v{}", env!("CARGO_PKG_VERSION"));
    let base = format!("{}/releases/download/{tag}", env!("CARGO_PKG_REPOSITORY"));
    let sums = Command::new("curl")
        .args(["-fsSL", "--max-time", "60", &format!("{base}/SHA256SUMS")])
        .output()
        .map_err(|e| e.to_string())?;
    for line in String::from_utf8_lossy(&sums.stdout).lines() {
        if let [sum, name] = line.split_whitespace().collect::<Vec<_>>()[..]
            && name == asset
        {
            return Ok((Build::Url(format!("{base}/{asset}")), sum.to_string()));
        }
    }
    Err(format!("no {asset} in release {tag}: pass --from <dir>"))
}

/// This binary, a `--from` file, or a release asset.
fn binary(platform: &str, asset: &str, from: Option<&Path>) -> Result<(Build, String), String> {
    let path = if platform == version::platform() {
        std::env::current_exe().map_err(|e| e.to_string())?
    } else {
        match from.map(|d| d.join(asset)).filter(|p| p.is_file()) {
            Some(path) => path,
            None => return release(asset),
        }
    };
    let sum = hash("local", &path.to_string_lossy())?;
    Ok((Build::File(path), sum))
}

/// Streams a local file to `remote` on `host`.
fn put_file(host: &str, local: &Path, remote: &str) -> Result<(), String> {
    if host == "local" {
        fs::copy(local, remote).map_err(|e| format!("{host}: {e}"))?;
        return Ok(());
    }
    let file = File::open(local).map_err(|e| format!("{}: {e}", local.display()))?;
    let status = Command::new("ssh")
        .args(SSH)
        .arg(host)
        .arg(format!("cat > {}", quote(remote)))
        .stdin(Stdio::from(file))
        .status()
        .map_err(|e| format!("{host}: {e}"))?;
    if !status.success() {
        return Err(format!("{host}: copy failed"));
    }
    Ok(())
}

/// Puts a build at `part` on `host`.
fn upload(host: &str, build: &Build, part: &str) -> Result<(), String> {
    match build {
        Build::Url(url) => {
            let get = format!(
                "curl -fsSL --max-time 900 -o {} {}",
                quote(part),
                quote(url)
            );
            shell(host, &get).map(drop)
        }
        Build::File(local) => put_file(host, local, part),
    }
}

/// Installs a build at `dest` unless already there.
fn place(host: &str, build: &Build, dest: &str, want: &str) -> Result<&'static str, String> {
    if hash(host, dest)? == want {
        return Ok("present");
    }
    let part = format!("{dest}.part");
    let (d, p) = (quote(dest), quote(&part));
    shell(host, &format!("mkdir -p \"$(dirname {d})\" && rm -f {p}"))?;
    upload(host, build, &part)?;
    if hash(host, &part)? != want {
        return Err(format!("{host}: sha256 differs after copy"));
    }
    shell(host, &format!("chmod 755 {p} && mv -f {p} {d}"))?;
    Ok("copied")
}

/// One installed host.
struct Sent {
    platform: &'static str,
    state: &'static str,
    dest: String,
    version: String,
}

/// Installs one probed host and checks its `--version` line.
fn send(name: &str, host: &Host, build: &Build, want: &str) -> Result<Sent, String> {
    let state = place(name, build, &host.dest, want)?;
    let line = shell(name, &format!("{} --version", quote(&host.dest)))?;
    if version::COMMIT.is_some_and(|c| !line.contains(c)) {
        return Err(format!("{name}: commit differs: {line}"));
    }
    Ok(Sent {
        platform: host.platform,
        state,
        dest: host.dest.clone(),
        version: line,
    })
}

fn each<I: Sync, T: Send>(items: &[I], f: impl Fn(&I) -> T + Sync) -> Vec<T> {
    std::thread::scope(|s| {
        let jobs: Vec<_> = items.iter().map(|i| s.spawn(|| f(i))).collect();
        let done = jobs.into_iter().map(|j| j.join());
        done.map(|r| r.expect("teleport thread")).collect()
    })
}

fn expand_home(raw: &str) -> String {
    let Some(home) = tessera_frontend::frontend_settings::home_dir() else {
        return raw.to_string();
    };
    let home = home.to_string_lossy();
    if raw == "~" {
        home.into_owned()
    } else if let Some(tail) = raw.strip_prefix("~/") {
        format!("{home}/{tail}")
    } else {
        raw.to_string()
    }
}

/// Splits an existing local path from an optional `:suffix`.
fn split_existing(raw: &str) -> Option<(PathBuf, String)> {
    let expanded = expand_home(raw);
    if Path::new(&expanded).exists() {
        return Some((PathBuf::from(expanded), String::new()));
    }
    for (at, _) in expanded.rmatch_indices(':') {
        let head = &expanded[..at];
        if !head.is_empty() && Path::new(head).exists() {
            return Some((PathBuf::from(head), expanded[at..].to_string()));
        }
    }
    None
}

/// Classifies one command argument as local, remote, or literal.
pub(crate) fn classify_arg(arg: &str) -> Result<PathArg, String> {
    let (prefix, val) = if arg.starts_with('-') {
        match arg.split_once('=') {
            Some((k, v)) => (format!("{k}="), v),
            None => return Ok(PathArg::Keep(arg.to_string())),
        }
    } else {
        (String::new(), arg)
    };
    if let Some(rest) = val.strip_prefix("remote:") {
        if rest.is_empty() {
            return Err("empty remote: path".into());
        }
        return Ok(PathArg::Keep(format!("{prefix}{rest}")));
    }
    if let Some(spec) = val.strip_prefix("local:") {
        if spec.is_empty() {
            return Err("empty local: path".into());
        }
        let (path, suffix) = split_existing(spec)
            .unwrap_or_else(|| (PathBuf::from(expand_home(spec)), String::new()));
        return Ok(PathArg::Local {
            prefix,
            path,
            suffix,
        });
    }
    if SCHEMES.iter().any(|s| val.starts_with(s)) {
        return Ok(PathArg::Keep(arg.to_string()));
    }
    let rel = val.starts_with("./") || val.starts_with("../") || val.starts_with("~/");
    if rel && let Some((path, suffix)) = split_existing(val) {
        return Ok(PathArg::Local {
            prefix,
            path,
            suffix,
        });
    }
    Ok(PathArg::Keep(arg.to_string()))
}

fn slot_name(path: &Path) -> String {
    path.file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .or_else(|| {
            path.canonicalize()
                .ok()
                .and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
        })
        .filter(|n| !n.is_empty() && n != "." && n != "..")
        .unwrap_or_else(|| "item".into())
}

fn ensure_parent(path: &Path) -> Result<(), String> {
    if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
        fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
    }
    Ok(())
}

fn get_file(host: &str, remote: &str, local: &Path) -> Result<(), String> {
    ensure_parent(local)?;
    let mut part = local.as_os_str().to_os_string();
    part.push(".teleport.part");
    let part = PathBuf::from(part);
    if host == "local" {
        fs::copy(remote, &part).map_err(|e| format!("{}: {e}", local.display()))?;
    } else {
        let out = File::create(&part).map_err(|e| format!("{}: {e}", part.display()))?;
        let status = Command::new("ssh")
            .args(SSH)
            .arg(host)
            .arg(format!("cat {}", quote(remote)))
            .stdout(Stdio::from(out))
            .status()
            .map_err(|e| format!("{host}: {e}"))?;
        if !status.success() {
            let _ = fs::remove_file(&part);
            return Err(format!("{host}: fetch failed for {remote}"));
        }
    }
    fs::rename(&part, local).map_err(|e| format!("{}: {e}", local.display()))
}

fn copy_tree(from: &Path, to: &Path) -> Result<(), String> {
    fs::create_dir_all(to).map_err(|e| format!("{}: {e}", to.display()))?;
    let entries = fs::read_dir(from).map_err(|e| format!("{}: {e}", from.display()))?;
    for entry in entries {
        let entry = entry.map_err(|e| format!("{}: {e}", from.display()))?;
        let src = entry.path();
        let dst = to.join(entry.file_name());
        if src.is_dir() {
            copy_tree(&src, &dst)?;
        } else if src.is_file() {
            fs::copy(&src, &dst).map_err(|e| format!("{}: {e}", dst.display()))?;
        }
    }
    Ok(())
}

fn get_dir(host: &str, remote: &str, local: &Path) -> Result<(), String> {
    if host == "local" {
        return copy_tree(Path::new(remote), local);
    }
    fs::create_dir_all(local).map_err(|e| format!("{}: {e}", local.display()))?;
    let mut ssh = Command::new("ssh")
        .args(SSH)
        .arg(host)
        .arg(format!("tar -C {} -cf - .", quote(remote)))
        .stdout(Stdio::piped())
        .spawn()
        .map_err(|e| format!("{host}: {e}"))?;
    let pipe = ssh.stdout.take().ok_or("missing ssh stdout")?;
    let tar = Command::new("tar")
        .arg("-C")
        .arg(local)
        .args(["-xf", "-"])
        .stdin(Stdio::from(pipe))
        .status()
        .map_err(|e| format!("tar: {e}"))?;
    let ssh_ok = ssh.wait().map_err(|e| format!("{host}: {e}"))?.success();
    if !ssh_ok || !tar.success() {
        return Err(format!("{host}: dir fetch failed for {remote}"));
    }
    Ok(())
}

/// Uploads `local` into the remote content-addressed cache if missing.
fn cache_file(host: &str, files_root: &str, local: &Path) -> Result<(String, String), String> {
    let sha = hash("local", &local.to_string_lossy())?;
    if sha.is_empty() {
        return Err(format!("{}: could not hash file", local.display()));
    }
    let name = slot_name(local);
    let cached = format!("{files_root}/{sha}/{name}");
    if hash(host, &cached)? != sha {
        let part = format!("{cached}.part");
        let (d, p, c) = (
            quote(&format!("{files_root}/{sha}")),
            quote(&part),
            quote(&cached),
        );
        shell(host, &format!("mkdir -p {d} && rm -f {p}"))?;
        put_file(host, local, &part)?;
        if hash(host, &part)? != sha {
            return Err(format!("{host}: sha256 differs after upload"));
        }
        shell(host, &format!("mv -f {p} {c}"))?;
    }
    Ok((cached, sha))
}

fn walk_files(root: &Path, dir: &Path, out: &mut Vec<(String, PathBuf)>) -> Result<(), String> {
    let entries = fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
    for entry in entries {
        let entry = entry.map_err(|e| format!("{}: {e}", dir.display()))?;
        let path = entry.path();
        let kind = entry
            .file_type()
            .map_err(|e| format!("{}: {e}", path.display()))?;
        if kind.is_dir() {
            walk_files(root, &path, out)?;
        } else if path.is_file() {
            let rel = path
                .strip_prefix(root)
                .map_err(|e| e.to_string())?
                .to_string_lossy()
                .into_owned();
            out.push((rel, path));
        }
    }
    Ok(())
}

fn stage_dir(host: &str, files_root: &str, local: &Path, remote: &str) -> Result<(), String> {
    let mut files = Vec::new();
    walk_files(local, local, &mut files)?;
    let mut dirs = BTreeSet::new();
    dirs.insert(remote.to_string());
    let mut links = Vec::with_capacity(files.len());
    for (rel, path) in &files {
        let (cached, _) = cache_file(host, files_root, path)?;
        let dst = format!("{remote}/{rel}");
        if let Some((parent, _)) = dst.rsplit_once('/') {
            dirs.insert(parent.to_string());
        }
        links.push((cached, dst));
    }
    let mut script = String::new();
    for dir in dirs {
        script.push_str(&format!("mkdir -p {}\n", quote(&dir)));
    }
    for (src, dst) in links {
        script.push_str(&format!("ln -sf {} {}\n", quote(&src), quote(&dst)));
    }
    shell(host, &script).map(drop)
}

fn stage_arg(
    host: &str,
    files_root: &str,
    run_dir: &str,
    idx: usize,
    arg: PathArg,
    staged: &mut Vec<Staged>,
) -> Result<String, String> {
    let PathArg::Local {
        prefix,
        path,
        suffix,
    } = arg
    else {
        let PathArg::Keep(lit) = arg else {
            unreachable!()
        };
        return Ok(lit);
    };
    let slot_dir = format!("{run_dir}/{idx}");
    let name = slot_name(&path);
    let remote = format!("{slot_dir}/{name}");
    let kind = if path.is_file() {
        let (cached, sha) = cache_file(host, files_root, &path)?;
        let (sd, c, r) = (quote(&slot_dir), quote(&cached), quote(&remote));
        shell(
            host,
            &format!("mkdir -p {sd} && (cp --reflink=auto {c} {r} 2>/dev/null || cp {c} {r})"),
        )?;
        StagedKind::File { sha }
    } else if path.is_dir() {
        stage_dir(host, files_root, &path, &remote)?;
        StagedKind::Dir
    } else {
        shell(host, &format!("mkdir -p {}", quote(&slot_dir)))?;
        StagedKind::Missing
    };
    staged.push(Staged {
        local: path,
        slot_dir,
        remote: remote.clone(),
        name,
        kind,
    });
    Ok(format!("{prefix}{remote}{suffix}"))
}

fn sync_siblings(host: &str, s: &Staged, skip: Option<&str>) -> Result<(), String> {
    let sd = quote(&s.slot_dir);
    let list = shell(host, &format!("ls -1A {sd} 2>/dev/null || true"))?;
    let base = s.local.parent().unwrap_or_else(|| Path::new(""));
    for entry in list.lines().filter(|l| !l.is_empty()) {
        if skip == Some(entry) {
            continue;
        }
        let remote = format!("{}/{entry}", s.slot_dir);
        let is_file = shell(
            host,
            &format!("test -f {} && echo y || true", quote(&remote)),
        )?;
        if is_file == "y" {
            let local = if base.as_os_str().is_empty() {
                PathBuf::from(entry)
            } else {
                base.join(entry)
            };
            get_file(host, &remote, &local)?;
        }
    }
    Ok(())
}

fn sync_slot(host: &str, marker: &str, s: &Staged) -> Result<(), String> {
    match &s.kind {
        StagedKind::Missing => {
            let r = quote(&s.remote);
            let kind = shell(
                host,
                &format!("if [ -f {r} ]; then echo f; elif [ -d {r} ]; then echo d; fi"),
            )?;
            match kind.as_str() {
                "f" => get_file(host, &s.remote, &s.local),
                "d" => get_dir(host, &s.remote, &s.local),
                _ => sync_siblings(host, s, None),
            }
        }
        StagedKind::File { sha } => {
            let now = hash(host, &s.remote)?;
            if !now.is_empty() && now != *sha {
                get_file(host, &s.remote, &s.local)?;
            }
            sync_siblings(host, s, Some(&s.name))
        }
        StagedKind::Dir => {
            let found = shell(
                host,
                &format!(
                    "find {} -type f -newer {} 2>/dev/null || true",
                    quote(&s.remote),
                    quote(marker)
                ),
            )?;
            let prefix = format!("{}/", s.remote);
            for path in found.lines().filter(|l| !l.is_empty()) {
                if let Some(rel) = path.strip_prefix(&prefix) {
                    get_file(host, path, &s.local.join(rel))?;
                }
            }
            Ok(())
        }
    }
}

fn exec_remote(host: &str, bin: &str, args: &[String]) -> Result<u8, String> {
    let status = if host == "local" {
        Command::new(bin)
            .args(args)
            .status()
            .map_err(|e| format!("{host}: {e}"))?
    } else {
        let mut parts = Vec::with_capacity(1 + args.len());
        parts.push(quote(bin));
        for arg in args {
            parts.push(quote(arg));
        }
        let line = parts.join(" ");
        let mut cmd = Command::new("ssh");
        cmd.args(SSH);
        if std::io::stdin().is_terminal() && std::io::stdout().is_terminal() {
            cmd.arg("-t");
        }
        cmd.arg(host)
            .arg(format!("sh -c {}", quote(&line)))
            .status()
            .map_err(|e| format!("{host}: {e}"))?
    };
    Ok(status.code().unwrap_or(1) as u8)
}

fn run_id() -> String {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos());
    format!("{}-{nanos}", std::process::id())
}

/// Stages local paths, runs `bin` on `host`, and fetches outputs.
pub(crate) fn run_with_bin(
    host: &str,
    root: &str,
    bin: &str,
    command: &[String],
) -> Result<(), Stop> {
    let classified: Vec<PathArg> = command
        .iter()
        .map(|a| classify_arg(a))
        .collect::<Result<_, _>>()
        .map_err(Stop::Failed)?;
    let has_local = classified
        .iter()
        .any(|a| matches!(a, PathArg::Local { .. }));
    if !has_local {
        let args: Vec<String> = classified
            .into_iter()
            .map(|a| match a {
                PathArg::Keep(s) => s,
                PathArg::Local { .. } => unreachable!(),
            })
            .collect();
        let code = exec_remote(host, bin, &args).map_err(Stop::Failed)?;
        return if code == 0 {
            Ok(())
        } else {
            Err(Stop::Code(code))
        };
    }
    let files_root = format!("{root}/teleport/files");
    let run_dir = format!("{root}/teleport/runs/{}", run_id());
    let marker = format!("{run_dir}/.start");
    let mut staged = Vec::new();
    let mut rewritten = Vec::with_capacity(classified.len());
    for (idx, arg) in classified.into_iter().enumerate() {
        match stage_arg(host, &files_root, &run_dir, idx, arg, &mut staged) {
            Ok(a) => rewritten.push(a),
            Err(e) => {
                let _ = shell(host, &format!("rm -rf {}", quote(&run_dir)));
                return Err(Stop::Failed(e));
            }
        }
    }
    if staged.iter().any(|s| matches!(s.kind, StagedKind::Dir))
        && let Err(e) = shell(host, &format!("touch {}", quote(&marker)))
    {
        let _ = shell(host, &format!("rm -rf {}", quote(&run_dir)));
        return Err(Stop::Failed(e));
    }
    let exec_res = exec_remote(host, bin, &rewritten);
    let mut sync_err = None;
    for slot in &staged {
        if let Err(e) = sync_slot(host, &marker, slot) {
            sync_err = Some(e);
            break;
        }
    }
    let _ = shell(host, &format!("rm -rf {}", quote(&run_dir)));
    let code = exec_res.map_err(Stop::Failed)?;
    if let Some(e) = sync_err {
        return Err(Stop::Failed(e));
    }
    if code == 0 {
        Ok(())
    } else {
        Err(Stop::Code(code))
    }
}

fn run_host(host: &str, root: &str, from: Option<&Path>, command: &[String]) -> Result<(), Stop> {
    let probed = probe(host, root).map_err(Stop::Failed)?;
    let (build, want) = binary(probed.platform, probed.asset, from).map_err(Stop::Failed)?;
    let sent = send(host, &probed, &build, &want).map_err(Stop::Failed)?;
    if sent.state == "copied" {
        eprintln!(
            "teleport: copied {} to {}:{}",
            sent.platform, host, sent.dest
        );
    }
    run_with_bin(host, &probed.root, &sent.dest, command)
}

fn copy_hosts(hosts: &[String], root: &str, from: Option<&Path>) -> Result<(), Stop> {
    let probes = each(hosts, |h| probe(h, root));
    let mut builds = BTreeMap::new();
    for host in probes.iter().flatten() {
        if !builds.contains_key(host.asset) {
            let found = binary(host.platform, host.asset, from);
            builds.insert(host.asset, found);
        }
    }
    let pairs: Vec<_> = hosts.iter().zip(&probes).collect();
    let lines = each(&pairs, |(name, probed)| {
        let host = probed.as_ref().map_err(String::clone)?;
        let (build, want) = builds[host.asset].as_ref().map_err(String::clone)?;
        send(name, host, build, want)
    });
    let mut rows: Vec<Value> = Vec::new();
    let mut failed = 0;
    for (name, line) in hosts.iter().zip(lines.iter()) {
        match line {
            Ok(sent) => {
                rows.push(json!({
                    "host": name,
                    "platform": sent.platform,
                    "state": sent.state,
                    "path": sent.dest,
                    "version": sent.version,
                }));
            }
            Err(e) => {
                failed += 1;
                rows.push(json!({"host": name, "error": e}));
            }
        }
    }
    if !crate::task::terminal().show(Shown::Hosts(&rows)) {
        for (name, line) in hosts.iter().zip(lines.iter()) {
            match line {
                Ok(sent) => println!(
                    "{}  {}  {}  {}  {}",
                    name, sent.platform, sent.state, sent.dest, sent.version
                ),
                Err(e) => println!("error {e}"),
            }
        }
    }
    if failed > 0 {
        let total = hosts.len();
        return Err(Stop::Failed(format!("{failed} of {total} hosts failed")));
    }
    Ok(())
}

pub fn run(rest: &[String]) -> Result<(), Stop> {
    let args = parse(rest)?;
    match args.mode {
        Mode::Copy(hosts) => copy_hosts(&hosts, &args.root, args.from.as_deref()),
        Mode::Run { host, command } => run_host(&host, &args.root, args.from.as_deref(), &command),
    }
}