zc2 0.0.25

P2P compute broker with credit-based billing, WAL, and broker mesh support
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
//! `zc update [--from-source]` — self-update the running `zc` binary.
//!
//! Default mode downloads the latest prebuilt release asset for the running
//! platform (`zc-linux-x86_64`, `zc-linux-arm64`, ...) from the
//! `zakuro-ai/zc` GitHub releases and replaces
//! the currently-running binary in place. `--from-source` instead clones the
//! (private) `zakuro-ai/zc` repo, runs `cargo build --release`, and installs
//! the freshly-built binary over the current one.
//!
//! Binary replacement is done by writing the new bytes to a temp file in the
//! same directory as the current executable, chmod'ing it 0755, then
//! `rename()`-ing it over the running binary's path — this works on Linux
//! even while the original file is busy/executing.

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

const REPO_API_LATEST: &str = "https://api.github.com/repos/zakuro-ai/zc/releases/latest";
const REPO_CLONE_HOST: &str = "github.com/zakuro-ai/zc";
/// Release asset name for the host platform. Must match the names uploaded by
/// .github/workflows/release.yml.
fn asset_name() -> &'static str {
    match (cfg!(target_os = "macos"), cfg!(target_arch = "aarch64")) {
        (true, true) => "zc-darwin-arm64",
        (true, false) => "zc-darwin-x86_64",
        (false, true) => "zc-linux-arm64",
        (false, false) => "zc-linux-x86_64",
    }
}

/// Which update strategy to use.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    /// Download the latest prebuilt release binary.
    PrebuiltRelease,
    /// Clone the source repo and `cargo build --release`.
    FromSource,
}

/// Parse `zc update [--from-source]` args into a [`Mode`]. Pure/testable —
/// takes plain string slices, no process spawning.
pub fn parse_mode(args: &[String]) -> Mode {
    if args.iter().any(|a| a == "--from-source") {
        Mode::FromSource
    } else {
        Mode::PrebuiltRelease
    }
}

/// Resolve a GitHub auth token, in precedence order:
///   1. `try_gh()` — e.g. `gh auth token` via the GitHub CLI
///   2. `get_env("GH_PAT")`
///   3. `get_env("GITHUB_TOKEN")`
///
/// Both dependencies are injected so this is unit-testable without spawning
/// a real `gh` process or touching real process env vars.
pub fn resolve_token<F1, F2>(try_gh: F1, get_env: F2) -> Option<String>
where
    F1: FnOnce() -> Option<String>,
    F2: Fn(&str) -> Option<String>,
{
    if let Some(t) = try_gh() {
        if !t.trim().is_empty() {
            return Some(t.trim().to_string());
        }
    }
    if let Some(t) = get_env("GH_PAT") {
        if !t.trim().is_empty() {
            return Some(t.trim().to_string());
        }
    }
    if let Some(t) = get_env("GITHUB_TOKEN") {
        if !t.trim().is_empty() {
            return Some(t.trim().to_string());
        }
    }
    None
}

/// Real `gh auth token` lookup — returns `None` if `gh` isn't installed,
/// isn't authenticated, or the call otherwise fails.
fn gh_auth_token() -> Option<String> {
    let out = Command::new("gh").args(["auth", "token"]).output().ok()?;
    if !out.status.success() {
        return None;
    }
    let token = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if token.is_empty() {
        None
    } else {
        Some(token)
    }
}

fn real_env(key: &str) -> Option<String> {
    std::env::var(key).ok()
}

/// Entry point mirroring the other subcommand modules' `run_cli` convention
/// (see `vpn::run_cli`).
pub fn run_cli(args: &[String]) {
    match parse_mode(args) {
        Mode::PrebuiltRelease => update_from_release(),
        Mode::FromSource => update_from_source(),
    }
}

/// Atomically replace the file at `exe_path` with `bytes`: write to a temp
/// file alongside it, chmod 0755, then `rename()` over the target. `rename`
/// within the same filesystem works on Linux even while `exe_path` is the
/// currently-running binary.
fn replace_binary_atomic(exe_path: &Path, bytes: &[u8]) -> std::io::Result<()> {
    let dir = exe_path.parent().unwrap_or_else(|| Path::new("."));
    let tmp_path: PathBuf = dir.join(format!(".zc-update-{}.tmp", std::process::id()));
    std::fs::write(&tmp_path, bytes)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&tmp_path, std::fs::Permissions::from_mode(0o755))?;
    }
    std::fs::rename(&tmp_path, exe_path)?;
    Ok(())
}

fn current_exe_or_bail() -> Option<PathBuf> {
    match std::env::current_exe() {
        Ok(p) => Some(p),
        Err(e) => {
            eprintln!(
                "Error: could not determine the current executable path: {}",
                e
            );
            None
        }
    }
}

/// Can we create (and remove) a file in `dir`? Used to decide whether we can
/// update the running binary in place, or must fall back to ~/.local/bin.
fn dir_writable(dir: &Path) -> bool {
    let probe = dir.join(format!(".zc-write-probe-{}", std::process::id()));
    match std::fs::File::create(&probe) {
        Ok(_) => {
            let _ = std::fs::remove_file(&probe);
            true
        }
        Err(_) => false,
    }
}

fn local_bin_zc() -> PathBuf {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
    PathBuf::from(home).join(".local").join("bin").join("zc")
}

/// Choose a user-writable install target. Prefer replacing the running binary in
/// place; if its directory isn't writable (e.g. root-owned /usr/local/bin), fall
/// back to ~/.local/bin/zc so the update never needs sudo. Returns
/// `(path, installed_to_local_bin)`.
fn resolve_install_target() -> (PathBuf, bool) {
    if let Ok(exe) = std::env::current_exe() {
        if let Some(dir) = exe.parent() {
            if dir_writable(dir) {
                return (exe, false);
            }
        }
    }
    (local_bin_zc(), true)
}

/// Append `line` to `path` unless it's already present. Returns Ok(true) if it
/// was added, Ok(false) if it was already there.
fn append_line_once(path: &Path, line: &str) -> std::io::Result<bool> {
    let existing = std::fs::read_to_string(path).unwrap_or_default();
    if existing.lines().any(|l| l.trim() == line.trim()) {
        return Ok(false);
    }
    use std::io::Write;
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)?;
    let sep = if existing.is_empty() || existing.ends_with('\n') {
        ""
    } else {
        "\n"
    };
    writeln!(
        f,
        "{}# added by `zc update` — put ~/.local/bin on PATH\n{}",
        sep, line
    )?;
    Ok(true)
}

/// The shell rc file to persist a PATH change into, inferred from $SHELL.
fn shell_rc_path() -> Option<PathBuf> {
    let home = std::env::var("HOME").ok()?;
    let shell = std::env::var("SHELL").unwrap_or_default();
    let file = if shell.contains("zsh") {
        ".zshrc"
    } else if shell.contains("bash") {
        ".bashrc"
    } else {
        ".profile"
    };
    Some(PathBuf::from(home).join(file))
}

/// After a ~/.local/bin install, make sure that dir is on PATH: append the
/// export to the shell rc if missing, and tell the user how to pick it up.
fn ensure_local_bin_on_path(installed: &Path) {
    let bin_dir = installed
        .parent()
        .map(|p| p.display().to_string())
        .unwrap_or_default();
    let on_path = std::env::var("PATH")
        .map(|p| p.split(':').any(|d| d == bin_dir))
        .unwrap_or(false);

    if on_path {
        println!("Installed to {}.", installed.display());
        println!("Run `hash -r` (or open a new terminal) so your shell uses the new binary.");
        return;
    }

    let export = "export PATH=\"$HOME/.local/bin:$PATH\"".to_string();
    let appended = shell_rc_path().and_then(|rc| {
        let ok = append_line_once(&rc, &export).unwrap_or(false);
        ok.then_some(rc)
    });

    println!("Installed to {}.", installed.display());
    match appended {
        Some(rc) => {
            println!("Added ~/.local/bin to your PATH in {}.", rc.display());
            println!(
                "Open a new terminal (or `source {}`) and run `zc`.",
                rc.display()
            );
        }
        None => {
            println!("Add ~/.local/bin to your PATH so `zc` is found:");
            println!("    {}", export);
        }
    }
    // An older zc elsewhere on PATH (e.g. /usr/local/bin) is now shadowed by the
    // prepended dir; remove it if you like: `sudo rm /usr/local/bin/zc`.
}

fn update_from_release() {
    use std::time::Duration;

    println!("Checking latest zc release...");

    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_connect(Some(Duration::from_secs(10)))
            .timeout_global(Some(Duration::from_secs(30)))
            .build(),
    );

    // The releases API works unauthenticated for public releases; if a token
    // is resolvable, use it anyway (needed if the repo/releases are private).
    let token = resolve_token(gh_auth_token, real_env);

    let mut req = agent
        .get(REPO_API_LATEST)
        .header("User-Agent", "zc-update")
        .header("Accept", "application/vnd.github+json");
    if let Some(t) = &token {
        req = req.header("Authorization", format!("Bearer {}", t));
    }

    let resp = match req.call() {
        Ok(r) => r,
        Err(e) => {
            eprintln!("Failed to reach GitHub releases API: {}", e);
            eprintln!("Fallback: try building from source instead — `zc update --from-source`.");
            return;
        }
    };

    if resp.status().as_u16() != 200 {
        eprintln!("GitHub releases API returned HTTP {}", resp.status());
        eprintln!("Fallback: try building from source instead — `zc update --from-source`.");
        return;
    }

    let body = match resp.into_body().read_to_string() {
        Ok(s) => s,
        Err(e) => {
            eprintln!("Failed to read releases API response: {}", e);
            return;
        }
    };

    let data: serde_json::Value = match serde_json::from_str(&body) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("Failed to parse releases API response: {}", e);
            return;
        }
    };

    let version = data
        .get("tag_name")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown")
        .to_string();

    let asset_url = data
        .get("assets")
        .and_then(|v| v.as_array())
        .and_then(|assets| {
            assets
                .iter()
                .find(|a| a.get("name").and_then(|n| n.as_str()) == Some(asset_name()))
        })
        .and_then(|a| a.get("browser_download_url"))
        .and_then(|u| u.as_str());

    let asset_url = match asset_url {
        Some(u) => u.to_string(),
        None => {
            eprintln!("No {} asset found on release {}.", asset_name(), version);
            eprintln!("Fallback: try building from source instead — `zc update --from-source`.");
            return;
        }
    };

    println!("Downloading {} ({})...", asset_name(), version);

    let mut dl_req = agent.get(&asset_url).header("User-Agent", "zc-update");
    if let Some(t) = &token {
        dl_req = dl_req.header("Authorization", format!("Bearer {}", t));
    }
    let dl_resp = match dl_req.call() {
        Ok(r) => r,
        Err(e) => {
            eprintln!("Failed to download release asset: {}", e);
            eprintln!("Fallback: try building from source instead — `zc update --from-source`.");
            return;
        }
    };

    if dl_resp.status().as_u16() != 200 {
        eprintln!("Download failed: HTTP {}", dl_resp.status());
        eprintln!("Fallback: try building from source instead — `zc update --from-source`.");
        return;
    }

    let bytes = match dl_resp.into_body().read_to_vec() {
        Ok(b) => b,
        Err(e) => {
            eprintln!("Failed to read downloaded binary: {}", e);
            return;
        }
    };

    let (exe_path, to_local_bin) = resolve_install_target();
    if let Some(parent) = exe_path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }

    println!("Installing to {}...", exe_path.display());
    if let Err(e) = replace_binary_atomic(&exe_path, &bytes) {
        eprintln!("Failed to install the new binary: {}", e);
        return;
    }
    if to_local_bin {
        ensure_local_bin_on_path(&exe_path);
    }

    println!("updated to {}", version);
}

fn update_from_source() {
    let token = match resolve_token(gh_auth_token, real_env) {
        Some(t) => t,
        None => {
            eprintln!("no GitHub token found; run `gh auth login` or set GH_PAT/GITHUB_TOKEN");
            return;
        }
    };

    let (exe_path, to_local_bin) = resolve_install_target();
    if let Some(parent) = exe_path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }

    let tmp_dir = std::env::temp_dir().join(format!("zc-update-src-{}", std::process::id()));
    if let Err(e) = std::fs::create_dir_all(&tmp_dir) {
        eprintln!("Failed to create temp dir {}: {}", tmp_dir.display(), e);
        return;
    }

    println!("Cloning zakuro-ai/zc (source build)...");
    let clone_url = format!("https://x-access-token:{}@{}", token, REPO_CLONE_HOST);
    let clone_status = Command::new("git")
        .args(["clone", "--depth", "1", &clone_url, "."])
        .current_dir(&tmp_dir)
        .status();

    match clone_status {
        Ok(s) if s.success() => {}
        Ok(s) => {
            eprintln!("git clone failed (exit {}).", s);
            let _ = std::fs::remove_dir_all(&tmp_dir);
            return;
        }
        Err(e) => {
            eprintln!("Failed to run git clone: {}", e);
            let _ = std::fs::remove_dir_all(&tmp_dir);
            return;
        }
    }

    println!("Building (cargo build --release)... this can take a few minutes.");
    let build_output = Command::new("cargo")
        .args(["build", "--release"])
        .current_dir(&tmp_dir)
        .output();

    let build_output = match build_output {
        Ok(o) => o,
        Err(e) => {
            eprintln!("Failed to run cargo build: {}", e);
            let _ = std::fs::remove_dir_all(&tmp_dir);
            return;
        }
    };

    if !build_output.status.success() {
        let stderr = String::from_utf8_lossy(&build_output.stderr);
        let tail: String = stderr
            .lines()
            .rev()
            .take(30)
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
            .collect::<Vec<_>>()
            .join("\n");
        eprintln!("cargo build --release failed. Build output (tail):");
        eprintln!("{}", tail);
        let _ = std::fs::remove_dir_all(&tmp_dir);
        return;
    }

    let mut built_bin: Option<PathBuf> = None;
    for c in ["zc", "zc2"] {
        let p = tmp_dir.join("target/release").join(c);
        if p.is_file() {
            built_bin = Some(p);
            break;
        }
    }
    let built_bin = match built_bin {
        Some(p) => p,
        None => {
            eprintln!("Build finished but no zc binary found under target/release/.");
            let _ = std::fs::remove_dir_all(&tmp_dir);
            return;
        }
    };

    let bytes = match std::fs::read(&built_bin) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("Failed to read built binary: {}", e);
            let _ = std::fs::remove_dir_all(&tmp_dir);
            return;
        }
    };

    println!("Installing to {}...", exe_path.display());
    if let Err(e) = replace_binary_atomic(&exe_path, &bytes) {
        eprintln!("Failed to install the new binary: {}", e);
        let _ = std::fs::remove_dir_all(&tmp_dir);
        return;
    }
    if to_local_bin {
        ensure_local_bin_on_path(&exe_path);
    }

    // Best-effort version string from the built binary itself.
    let version = Command::new(&exe_path)
        .arg("--version")
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .unwrap_or_else(|| "source build".to_string());

    let _ = std::fs::remove_dir_all(&tmp_dir);

    println!("updated to {}", version);
}

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

    #[test]
    fn append_line_once_is_idempotent() {
        let dir = std::env::temp_dir().join(format!("zc-rc-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let rc = dir.join("rc");
        let line = "export PATH=\"$HOME/.local/bin:$PATH\"";
        assert!(super::append_line_once(&rc, line).unwrap()); // added
        assert!(!super::append_line_once(&rc, line).unwrap()); // already present
        let body = std::fs::read_to_string(&rc).unwrap();
        assert_eq!(body.matches(line).count(), 1);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn parse_mode_default_is_prebuilt_release() {
        let args: Vec<String> = vec![];
        assert_eq!(parse_mode(&args), Mode::PrebuiltRelease);
    }

    #[test]
    fn parse_mode_other_flags_still_prebuilt_release() {
        let args: Vec<String> = vec!["--verbose".to_string()];
        assert_eq!(parse_mode(&args), Mode::PrebuiltRelease);
    }

    #[test]
    fn parse_mode_from_source_flag_selects_source_build() {
        let args: Vec<String> = vec!["--from-source".to_string()];
        assert_eq!(parse_mode(&args), Mode::FromSource);
    }

    #[test]
    fn parse_mode_from_source_among_other_args() {
        let args: Vec<String> = vec!["--verbose".to_string(), "--from-source".to_string()];
        assert_eq!(parse_mode(&args), Mode::FromSource);
    }

    #[test]
    fn resolve_token_prefers_gh() {
        let t = resolve_token(
            || Some("gh-token".to_string()),
            |k| match k {
                "GH_PAT" => Some("pat-token".to_string()),
                "GITHUB_TOKEN" => Some("gh-env-token".to_string()),
                _ => None,
            },
        );
        assert_eq!(t.as_deref(), Some("gh-token"));
    }

    #[test]
    fn resolve_token_falls_back_to_gh_pat() {
        let t = resolve_token(
            || None,
            |k| match k {
                "GH_PAT" => Some("pat-token".to_string()),
                "GITHUB_TOKEN" => Some("gh-env-token".to_string()),
                _ => None,
            },
        );
        assert_eq!(t.as_deref(), Some("pat-token"));
    }

    #[test]
    fn resolve_token_falls_back_to_github_token() {
        let t = resolve_token(
            || None,
            |k| match k {
                "GH_PAT" => None,
                "GITHUB_TOKEN" => Some("gh-env-token".to_string()),
                _ => None,
            },
        );
        assert_eq!(t.as_deref(), Some("gh-env-token"));
    }

    #[test]
    fn resolve_token_none_found() {
        let t = resolve_token(|| None, |_k| None);
        assert_eq!(t, None);
    }

    #[test]
    fn resolve_token_skips_blank_values() {
        // A blank gh token or blank env var should not shadow a real one
        // further down the precedence chain.
        let t = resolve_token(
            || Some("   ".to_string()),
            |k| match k {
                "GH_PAT" => Some("".to_string()),
                "GITHUB_TOKEN" => Some("real-token".to_string()),
                _ => None,
            },
        );
        assert_eq!(t.as_deref(), Some("real-token"));
    }
}