rsclaw 2026.5.20

AI Agent Engine Compatible with OpenClaw
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
use anyhow::Result;

use super::style::*;
use crate::{
    cli::{UpdateArgs, UpdateCommand},
    config,
};

pub async fn cmd_update(sub: UpdateCommand) -> Result<()> {
    match sub {
        UpdateCommand::Run(args) => do_update(&args).await?,
        UpdateCommand::Status => update_status().await?,
        UpdateCommand::Wizard => {
            banner(&format!(
                "rsclaw update wizard v{}",
                option_env!("RSCLAW_BUILD_VERSION").unwrap_or("dev")
            ));
            warn_msg("update wizard: not yet implemented");
            println!("  {}", dim("use `rsclaw update run` for now"));
        }
    }
    Ok(())
}

/// Compare two dot-separated numeric versions (CalVer "2026.5.20"), segment
/// by segment as integers. String comparison is wrong for CalVer
/// ("2026.5.9" would sort after "2026.5.10"), and a plain `==` check treats a
/// published version that is *older* than the local build as "different,
/// therefore an update" — which silently downgrades dev builds. Non-numeric
/// segments (e.g. a "dev" build) parse as 0, so they never read as newer and a
/// dev build still updates to a real release.
fn version_cmp(a: &str, b: &str) -> std::cmp::Ordering {
    let parse = |s: &str| {
        s.split('.')
            .map(|p| p.parse::<u64>().unwrap_or(0))
            .collect::<Vec<u64>>()
    };
    parse(a).cmp(&parse(b))
}

const RSCLAW_VERSION_URL: &str = "https://app.rsclaw.ai/api/version";

/// Apply GITHUB_PROXY env to a URL: proxy + "/" + url
fn proxy_url(url: &str) -> String {
    if let Ok(proxy) = std::env::var("GITHUB_PROXY") {
        let proxy = proxy.trim_end_matches('/');
        if !proxy.is_empty() {
            return format!("{}/{}", proxy, url);
        }
    }
    url.to_owned()
}

fn build_update_client(timeout_secs: u64) -> Result<reqwest::Client> {
    Ok(reqwest::Client::builder()
        .user_agent("rsclaw/dev")
        .timeout(std::time::Duration::from_secs(timeout_secs))
        .build()?)
}

async fn do_update(args: &UpdateArgs) -> Result<()> {
    // In --json mode, suppress all human-readable banners/progress so the
    // caller gets a single parseable JSON object at the end. This was a
    // mid-flow `println!(json!(...))` before, which interleaved with the
    // human output and broke any process trying to consume the result.
    let quiet = args.json;

    if !quiet {
        banner(&format!(
            "rsclaw update v{}",
            option_env!("RSCLAW_BUILD_VERSION").unwrap_or("dev")
        ));
    }

    let timeout_secs = args.timeout.unwrap_or(30);
    let client = build_update_client(timeout_secs)?;

    // Best-effort cleanup of a stale `.old` backup left by a previous
    // update run — without this they accumulate forever.
    if let Ok(current_exe) = std::env::current_exe() {
        let stale_backup = current_exe.with_extension("old");
        if stale_backup.exists() {
            let _ = std::fs::remove_file(&stale_backup);
        }
    }

    // 1. Check latest release — try app.rsclaw.ai first, fallback GitHub
    if !quiet {
        println!("  {} checking for updates...", dim("[..]"));
    }

    // Try app.rsclaw.ai first (object or array), fallback GitHub releases list
    // (array). A valid release must have tag_name and assets so we can download
    // the binary.
    let release: serde_json::Value = {
        let mut data = None;
        let sources = [
            RSCLAW_VERSION_URL.to_owned(),
            proxy_url(&format!(
                "https://api.github.com/repos/{}/releases?per_page=10",
                "rsclaw-ai/rsclaw"
            )),
        ];
        for url in &sources {
            if let Ok(resp) = client.get(url).send().await {
                if resp.status().is_success() {
                    let body = resp.bytes().await.unwrap_or_default();
                    if let Some(found) = parse_release_body(&body) {
                        // Only accept if it has assets; otherwise try next source.
                        if found["assets"].is_array() {
                            data = Some(found);
                            break;
                        }
                    }
                }
            }
        }
        data.unwrap_or_default()
    };

    let latest_version = release["tag_name"]
        .as_str()
        .unwrap_or("")
        .trim_start_matches('v')
        .to_owned();
    let current = option_env!("RSCLAW_BUILD_VERSION").unwrap_or("dev");

    if !quiet {
        kv("Current:", current);
        kv("Latest:", &latest_version);
    }

    if latest_version.is_empty() {
        if quiet {
            println!(
                "{}",
                serde_json::json!({
                    "currentVersion": current,
                    "status": "version-check-failed",
                })
            );
        } else {
            println!("  {} could not determine latest version", yellow("[!]"));
        }
        return Ok(());
    }

    // Only update when the published version is strictly newer. Equal means
    // up to date; older means this is a local/dev build ahead of the last
    // release — never downgrade it.
    if version_cmp(&latest_version, current) != std::cmp::Ordering::Greater {
        if quiet {
            println!(
                "{}",
                serde_json::json!({
                    "currentVersion": current,
                    "latestVersion": latest_version,
                    "updateAvailable": false,
                    "status": "up-to-date",
                })
            );
        } else {
            println!("  {} already up to date", green("[ok]"));
        }
        return Ok(());
    }

    if args.dry_run {
        if quiet {
            println!(
                "{}",
                serde_json::json!({
                    "currentVersion": current,
                    "latestVersion": latest_version,
                    "updateAvailable": true,
                    "dryRun": true,
                    "status": "dry-run",
                })
            );
        } else {
            println!(
                "  {} would update to {latest_version} (dry run)",
                dim("[..]")
            );
        }
        return Ok(());
    }

    // 2. Determine platform asset name candidates (try gnu first, then musl)
    let (os, arch) = (std::env::consts::OS, std::env::consts::ARCH);
    let candidates: Vec<&str> = match (os, arch) {
        ("macos", "aarch64") => vec!["aarch64-apple-darwin"],
        ("macos", "x86_64") => vec!["x86_64-apple-darwin"],
        ("linux", "x86_64") => vec!["x86_64-unknown-linux-gnu", "x86_64-unknown-linux-musl"],
        ("linux", "aarch64") => vec!["aarch64-unknown-linux-gnu", "aarch64-unknown-linux-musl"],
        ("windows", "x86_64") => vec!["x86_64-pc-windows-msvc"],
        ("windows", "aarch64") => vec!["aarch64-pc-windows-msvc"],
        _ => anyhow::bail!("unsupported platform: {os}-{arch}"),
    };

    // 3. Find matching asset URL (both sources use GitHub releases format)
    let assets = release["assets"].as_array();
    let mut asset_name = candidates[0];
    let download_url = assets.and_then(|arr| {
        for candidate in &candidates {
            if let Some(url) = arr.iter().find_map(|a| {
                let name = a["name"].as_str().unwrap_or("");
                if name.contains(candidate) {
                    a["browser_download_url"].as_str().map(|s| s.to_owned())
                } else {
                    None
                }
            }) {
                asset_name = candidate;
                return Some(url);
            }
        }
        None
    });

    let Some(url) = download_url else {
        // No pre-built binary, suggest building from source
        if quiet {
            println!(
                "{}",
                serde_json::json!({
                    "currentVersion": current,
                    "latestVersion": latest_version,
                    "updateAvailable": true,
                    "status": "no-prebuilt-binary",
                    "platform": format!("{os}-{arch}"),
                    "fromSource": "cd /path/to/rsclaw && git pull && cargo build --release",
                })
            );
        } else {
            println!("  {} no pre-built binary for {os}-{arch}", yellow("[!]"));
            println!("  Update from source:");
            println!("    cd /path/to/rsclaw && git pull && cargo build --release");
        }
        return Ok(());
    };

    // 4. Download binary
    if !quiet {
        println!("  {} downloading {asset_name}...", dim("[..]"));
    }
    let download = if url.contains("github.com") || url.contains("githubusercontent.com") {
        proxy_url(&url)
    } else {
        url.clone()
    };
    let downloaded = client.get(&download).send().await?.bytes().await?;

    if downloaded.is_empty() {
        anyhow::bail!("downloaded binary is empty");
    }

    // 4b. SHA256 verification.
    //
    // The release publishes a SHA256SUMS.txt asset with one
    // "<hex-digest>  <filename>" line per binary. Without verification a
    // hostile GITHUB_PROXY (or any MITM if TLS validation ever broke)
    // could substitute an arbitrary binary that we'd then chmod 755 over
    // the live executable. Verify before touching disk.
    let sum_url = release["assets"].as_array().and_then(|arr| {
        arr.iter().find_map(|a| {
            let name = a["name"].as_str().unwrap_or("");
            if name.eq_ignore_ascii_case("SHA256SUMS.txt")
                || name.eq_ignore_ascii_case("SHA256SUMS")
            {
                a["browser_download_url"].as_str().map(|s| s.to_owned())
            } else {
                None
            }
        })
    });
    if let Some(su) = sum_url {
        let su_dl = if su.contains("github.com") || su.contains("githubusercontent.com") {
            proxy_url(&su)
        } else {
            su.clone()
        };
        let sums = client
            .get(&su_dl)
            .send()
            .await?
            .text()
            .await
            .unwrap_or_default();
        let asset_filename = url.rsplit('/').next().unwrap_or("");
        let expected = sums.lines().find_map(|line| {
            let mut parts = line.split_whitespace();
            let hex = parts.next()?;
            let name = parts.next()?;
            // SHA256SUMS files often write "*name" for binary-mode lines and
            // sometimes prefix with "./" for path-relative entries. Strip
            // both, then require a strict basename match. Earlier code
            // also accepted `asset_filename.ends_with(name)` which made
            // a SHA256SUMS entry "linux.tar.gz" spuriously match
            // "rsclaw-vX-Y-x86_64-linux.tar.gz" — a security-relevant
            // wildcard.
            let name = name.trim_start_matches('*').trim_start_matches("./");
            if name == asset_filename {
                Some(hex.to_lowercase())
            } else {
                None
            }
        });
        match expected {
            Some(expected_hex) => {
                use sha2::{Digest, Sha256};
                let mut hasher = Sha256::new();
                hasher.update(&downloaded);
                let actual_hex = format!("{:x}", hasher.finalize());
                if actual_hex != expected_hex {
                    anyhow::bail!(
                        "SHA256 mismatch for {asset_filename}: expected {expected_hex}, got {actual_hex}. Aborting update."
                    );
                }
                if !quiet {
                    println!("  {} SHA256 verified", green("[ok]"));
                }
            }
            None => {
                if !quiet {
                    println!(
                        "  {} no SHA256 entry for {asset_filename} in SHA256SUMS — proceeding without verify",
                        yellow("[!]")
                    );
                }
            }
        }
    } else if !quiet {
        println!(
            "  {} release has no SHA256SUMS asset — proceeding without verify",
            yellow("[!]")
        );
    }

    // 5. Extract binary from archive (tar.gz / zip) if needed.
    //
    // If the URL is an archive but extraction fails, FAIL HARD. The earlier
    // fallback ("could not extract, using raw download") wrote the
    // archive's gzipped/zipped bytes as the executable, then chmod +x'd
    // it — a pretty reliable way to brick the install.
    let binary_name = if std::env::consts::OS == "windows" {
        "rsclaw.exe"
    } else {
        "rsclaw"
    };
    let url_lower = download.to_lowercase();
    let looks_archived = url_lower.ends_with(".tar.gz")
        || url_lower.ends_with(".tgz")
        || url_lower.ends_with(".zip");
    let binary = if looks_archived {
        extract_binary(&downloaded, binary_name, &download)?
    } else {
        downloaded.to_vec()
    };

    // 6. Atomically replace the current executable.
    //
    // Write to <current>.new, fsync, chmod, then rename. Rename within the
    // same dir is atomic on POSIX and Windows (replace_file under-the-hood
    // for Rust). The previous flow `rename(current → .old) → write(current)`
    // left a corrupt or missing executable if `write` partial-failed.
    let current_exe = std::env::current_exe()?;
    let new_path = current_exe.with_extension("new");
    let backup = current_exe.with_extension("old");

    {
        use std::io::Write;
        let mut f = std::fs::File::create(&new_path)?;
        f.write_all(&binary)?;
        f.sync_all()?;
    }

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&new_path, std::fs::Permissions::from_mode(0o755))?;
    }

    // Move current → backup (so we have a rollback target) then rename
    // new → current. If the second rename fails, restore from backup.
    if backup.exists() {
        let _ = std::fs::remove_file(&backup);
    }
    std::fs::rename(&current_exe, &backup)?;
    if let Err(e) = std::fs::rename(&new_path, &current_exe) {
        // Restore previous executable.
        let _ = std::fs::rename(&backup, &current_exe);
        let _ = std::fs::remove_file(&new_path);
        anyhow::bail!("update: atomic swap failed: {e}");
    }

    if !quiet {
        println!("  {} updated to {latest_version}", green("[ok]"));
        kv("Binary:", &current_exe.display().to_string());
        kv("Backup:", &backup.display().to_string());
    }

    // 7. Restart gateway if running
    if !args.no_restart {
        let pid_file = config::loader::pid_file();
        if pid_file.exists() {
            if !quiet {
                println!("  {} restarting gateway...", dim("[..]"));
            }
            if let Ok(pid_str) = std::fs::read_to_string(&pid_file) {
                if let Ok(pid) = pid_str.trim().parse::<i32>() {
                    let _ = crate::sys::process_terminate(pid as u32);
                    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
                    #[allow(unused_mut)]
                    let mut upd = std::process::Command::new(&current_exe);
                    upd.arg("gateway").arg("start");
                    #[cfg(windows)]
                    {
                        use std::os::windows::process::CommandExt;
                        upd.creation_flags(0x08000000);
                    }
                    let _ = upd.spawn();
                    if !quiet {
                        println!("  {} gateway restarted", green("[ok]"));
                    }
                }
            }
        }
    }

    if quiet {
        println!(
            "{}",
            serde_json::json!({
                "currentVersion": current,
                "latestVersion": latest_version,
                "updateAvailable": true,
                "status": "updated",
                "binary": current_exe.display().to_string(),
                "backup": backup.display().to_string(),
            })
        );
    }

    if !quiet {
        println!();
    }
    Ok(())
}

/// Parse a release response body that may be an array or a single object.
/// Returns the first CLI release (tag starts with 'v' but not 'app-v').
fn parse_release_body(body: &[u8]) -> Option<serde_json::Value> {
    // Try array first (GitHub /releases endpoint)
    if let Ok(arr) = serde_json::from_slice::<Vec<serde_json::Value>>(body) {
        return arr.into_iter().find(|r| {
            r["tag_name"]
                .as_str()
                .is_some_and(|t| t.starts_with('v') && !t.starts_with("app-"))
        });
    }
    // Fall back to single object (app.rsclaw.ai/api/version)
    if let Ok(obj) = serde_json::from_slice::<serde_json::Value>(body) {
        if obj["tag_name"]
            .as_str()
            .is_some_and(|t| t.starts_with('v') && !t.starts_with("app-"))
        {
            return Some(obj);
        }
    }
    None
}

/// Extract a named file from a downloaded archive (tar.gz or zip).
/// If the data does not appear to be an archive, returns an error so
/// the caller can fall back to treating it as a raw binary.
fn extract_binary(data: &[u8], filename: &str, url: &str) -> Result<Vec<u8>> {
    let url_lower = url.to_lowercase();
    if url_lower.ends_with(".tar.gz") || url_lower.ends_with(".tgz") {
        let tar = flate2::read::GzDecoder::new(data);
        let mut archive = tar::Archive::new(tar);
        for entry in archive.entries()? {
            let mut entry = entry?;
            let path = entry.path()?;
            if path.file_name().map(|n| n == filename).unwrap_or(false) {
                let mut buf = Vec::new();
                std::io::Read::read_to_end(&mut entry, &mut buf)?;
                return Ok(buf);
            }
        }
        anyhow::bail!("{filename} not found in tar.gz archive");
    }

    if url_lower.ends_with(".zip") {
        let reader = std::io::Cursor::new(data);
        let mut archive = zip::ZipArchive::new(reader)?;
        for i in 0..archive.len() {
            let mut file = archive.by_index(i)?;
            let name = file.name();
            if std::path::Path::new(name)
                .file_name()
                .map(|n| n == filename)
                .unwrap_or(false)
            {
                let mut buf = Vec::new();
                std::io::copy(&mut file, &mut buf)?;
                return Ok(buf);
            }
        }
        anyhow::bail!("{filename} not found in zip archive");
    }

    anyhow::bail!("unsupported archive format: {url}");
}

async fn update_status() -> Result<()> {
    banner(&format!(
        "rsclaw update status v{}",
        option_env!("RSCLAW_BUILD_VERSION").unwrap_or("dev")
    ));

    let client = build_update_client(10)?;

    kv(
        "Current:",
        option_env!("RSCLAW_BUILD_VERSION").unwrap_or("dev"),
    );

    // Try app.rsclaw.ai first (object or array), fallback GitHub releases list
    // (array)
    let mut latest_tag: Option<String> = None;
    let sources = [
        RSCLAW_VERSION_URL.to_owned(),
        proxy_url(&format!(
            "https://api.github.com/repos/{}/releases?per_page=10",
            "rsclaw-ai/rsclaw"
        )),
    ];
    for url in &sources {
        if let Ok(resp) = client.get(url).send().await {
            if resp.status().is_success() {
                let body = resp.bytes().await.unwrap_or_default();
                if let Some(release) = parse_release_body(&body) {
                    if let Some(tag) = release["tag_name"].as_str() {
                        if tag.starts_with('v') && !tag.starts_with("app-") {
                            latest_tag = Some(tag.to_owned());
                            break;
                        }
                    }
                }
            }
        }
    }

    match latest_tag {
        Some(tag) => {
            let latest = tag.trim_start_matches('v');
            kv("Latest:", latest);
            let current = option_env!("RSCLAW_BUILD_VERSION").unwrap_or("dev");
            if version_cmp(latest, current) == std::cmp::Ordering::Greater {
                println!("  {} update available: {latest}", yellow("[!]"));
                println!("  Run: rsclaw update");
            } else {
                println!("  {} up to date", green("[ok]"));
            }
        }
        None => {
            println!("  {} could not check for updates", yellow("[!]"));
        }
    }
    println!();
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::cmp::Ordering;

    use super::version_cmp;

    #[test]
    fn newer_release_is_greater() {
        assert_eq!(version_cmp("2026.5.20", "2026.5.18"), Ordering::Greater);
    }

    #[test]
    fn segments_compare_numerically_not_lexically() {
        // String comparison would rank "9" after "10"; numeric must not.
        assert_eq!(version_cmp("2026.5.10", "2026.5.9"), Ordering::Greater);
    }

    #[test]
    fn equal_versions_are_equal() {
        assert_eq!(version_cmp("2026.5.18", "2026.5.18"), Ordering::Equal);
    }

    #[test]
    fn local_build_ahead_of_release_is_less_so_no_downgrade() {
        // The reported bug: latest (release) older than current (local build).
        assert_eq!(version_cmp("2026.5.18", "2026.5.20"), Ordering::Less);
    }

    #[test]
    fn dev_build_is_behind_any_release() {
        assert_eq!(version_cmp("dev", "2026.5.18"), Ordering::Less);
    }
}