rsclaw-runtime 2026.6.26

rsclaw composition root: AppState/RPC handlers (a2a, cmd, cron, gateway, hooks, server, ws) + process entry point
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
use anyhow::Result;

use super::style::{banner, bold, dim, green, red, yellow};
use rsclaw_cli::DoctorArgs;
use rsclaw_config as config;

const VERSION: &str = match option_env!("RSCLAW_BUILD_VERSION") {
    Some(v) => v,
    None => "dev",
};

// ---------------------------------------------------------------------------
// Issue -- a detected problem with an optional auto-fix
// ---------------------------------------------------------------------------

struct Issue {
    message: String,
    /// A short description of what --fix will do.
    fix_hint: Option<&'static str>,
    /// The actual fix to apply. Returns a description of what was done.
    fix_fn: Option<Box<dyn FnOnce() -> Result<String>>>,
}

impl Issue {
    fn warn(msg: impl Into<String>) -> Self {
        Self {
            message: msg.into(),
            fix_hint: None,
            fix_fn: None,
        }
    }

    fn fixable(
        msg: impl Into<String>,
        hint: &'static str,
        f: impl FnOnce() -> Result<String> + 'static,
    ) -> Self {
        Self {
            message: msg.into(),
            fix_hint: Some(hint),
            fix_fn: Some(Box::new(f)),
        }
    }
}

// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------

pub async fn cmd_doctor(args: DoctorArgs) -> Result<()> {
    banner(&format!("rsclaw v{VERSION} \u{2014} doctor"));

    let mut issues: Vec<Issue> = Vec::new();
    let mut passed: usize = 0;

    // -- 1. Config load -------------------------------------------------------
    let cfg = match config::load_quiet() {
        Ok(c) => {
            println!(
                "  {} config loaded \u{2014} {} agent(s)",
                green("[ok]"),
                c.agents.list.len()
            );
            passed += 1;
            Some(c)
        }
        Err(e) => {
            let err_str = format!("{e:#}");
            if err_str.contains("JSON5 parse error") || err_str.contains("expected") {
                issues.push(Issue::fixable(
                    format!("config error: {err_str}"),
                    "attempt auto-repair of config JSON syntax",
                    || repair_config_json(),
                ));
            } else if err_str.contains("invalid type") {
                issues.push(Issue::fixable(
                    format!("config error: {err_str}"),
                    "fix type mismatches in config",
                    || fix_config_type_mismatches(),
                ));
            } else {
                issues.push(Issue::warn(format!("config error: {err_str}")));
            }
            None
        }
    };

    // -- 2. State directory ---------------------------------------------------
    let base_dir = config::loader::base_dir();
    if !base_dir.is_dir() {
        let path = base_dir.clone();
        issues.push(Issue::fixable(
            format!("state directory missing: {}", base_dir.display()),
            "create state directory",
            move || {
                std::fs::create_dir_all(&path)?;
                Ok(format!("created {}", path.display()))
            },
        ));
    } else {
        println!("  {} state directory exists", green("[ok]"));
        passed += 1;
    }

    // -- 3. Stale PID file ----------------------------------------------------
    let pid_file = config::loader::pid_file();
    if pid_file.exists() {
        let stale = std::fs::read_to_string(&pid_file)
            .ok()
            .and_then(|s| s.trim().parse::<u32>().ok())
            .map(|pid| !process_exists(pid))
            .unwrap_or(true);

        if stale {
            let path = pid_file.clone();
            issues.push(Issue::fixable(
                format!(
                    "stale PID file (gateway not running): {}",
                    pid_file.display()
                ),
                "delete stale PID file",
                move || {
                    std::fs::remove_file(&path)?;
                    Ok(format!("removed {}", path.display()))
                },
            ));
        } else {
            println!("  {} gateway running (PID file valid)", green("[ok]"));
            passed += 1;
        }
    }

    // -- 4. Config file permissions -------------------------------------------
    if let Some(cfg_path) = config::loader::detect_config_path() {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            if let Ok(meta) = std::fs::metadata(&cfg_path) {
                let mode = meta.permissions().mode();
                if mode & 0o044 != 0 {
                    let path = cfg_path.clone();
                    let safe_mode = mode & !0o044;
                    issues.push(Issue::fixable(
                        format!(
                            "config file is world/group-readable ({:04o}): {}",
                            mode & 0o777,
                            cfg_path.display()
                        ),
                        "chmod to owner-only",
                        move || {
                            let mut perms = std::fs::metadata(&path)?.permissions();
                            perms.set_mode(safe_mode);
                            std::fs::set_permissions(&path, perms)?;
                            Ok(format!(
                                "chmod {:04o} {}",
                                safe_mode & 0o777,
                                path.display()
                            ))
                        },
                    ));
                } else {
                    println!(
                        "  {} config permissions {:04o}",
                        green("[ok]"),
                        mode & 0o777
                    );
                    passed += 1;
                }
            }
        }
        #[cfg(windows)]
        {
            // Windows: user profile dirs (%LOCALAPPDATA%) are owner-only by default.
            // Check that the config file is not in a world-readable location.
            if let Ok(meta) = std::fs::metadata(&cfg_path) {
                if !meta.permissions().readonly() {
                    println!(
                        "  {} config file exists: {}",
                        green("[ok]"),
                        cfg_path.display()
                    );
                    passed += 1;
                }
            }
        }
    }

    // -- 5. Agent / model checks (advisory only) ------------------------------
    if let Some(ref c) = cfg {
        // agents.list empty is fine 鈥?a default "main" agent is auto-synthesized.
        if !c.agents.list.is_empty() {
            println!(
                "  {} {} agent(s) configured",
                green("[ok]"),
                c.agents.list.len()
            );
            passed += 1;
        }

        let has_default_model = c
            .agents
            .defaults
            .model
            .as_ref()
            .and_then(|m| m.primary_head())
            .is_some();
        for a in &c.agents.list {
            let has_model = a.model.as_ref().and_then(|m| m.primary_head()).is_some();
            if !has_model && !has_default_model {
                issues.push(Issue::warn(format!(
                    "agent '{}' has no model \u{2014} set agents.defaults.model.primary or agent-level model",
                    a.id
                )));
            }
        }

        let has_provider = c
            .model
            .models
            .as_ref()
            .map(|m| !m.providers.is_empty())
            .unwrap_or(false);
        if !has_provider {
            issues.push(Issue::warn(
                "no model providers configured \u{2014} set models.providers in config".to_owned(),
            ));
        }

        if c.gateway.auth_token.is_none() {
            let config_path = config::loader::base_dir().join("rsclaw.json5");
            issues.push(Issue {
                message: "gateway.auth.token not set \u{2014} gateway accepts all connections without auth".to_owned(),
                fix_hint: Some("auto-generate a 64-char auth token"),
                fix_fn: Some(Box::new(move || {
                    let token = super::setup::generate_auth_token();
                    let content = std::fs::read_to_string(&config_path)?;
                    let mut val: serde_json::Value = json5::from_str(&content)?;
                    if val.pointer("/gateway/auth").is_none() {
                        val["gateway"]["auth"] = serde_json::json!({"token": &token});
                    } else {
                        val["gateway"]["auth"]["token"] = serde_json::json!(&token);
                    }
                    std::fs::write(&config_path, serde_json::to_string_pretty(&val)?)?;
                    Ok(format!("generated auth token: {}", &token[..8]))
                })),
            });
        }
    }

    // -- 6. Tools check -------------------------------------------------------
    {
        let (avail, total) = super::tools::tools_count();
        let summary = super::tools::tools_summary_line();
        if avail == total {
            println!(
                "  {} tools {}/{} — {}",
                green("[ok]"),
                avail,
                total,
                summary
            );
            passed += 1;
        } else {
            let missing: Vec<&str> = super::tools::tools_missing();
            println!(
                "  {} tools {}/{} — {}",
                yellow("[warn]"),
                avail,
                total,
                summary
            );
            issues.push(Issue::warn(format!(
                "missing tools: {}. Install with `rsclaw tools install {}`",
                missing.join(", "),
                if missing.len() == 1 {
                    missing[0].to_string()
                } else {
                    "all".to_string()
                }
            )));
        }
    }

    // -- 7. Plugins check ----------------------------------------------------
    {
        let plugins_dir = config::loader::base_dir().join("plugins");
        match rsclaw_plugin::manifest::scan_plugins(&plugins_dir) {
            Ok(plugins) if !plugins.is_empty() => {
                let mut broken = Vec::new();
                for p in &plugins {
                    // WASM plugins use the embedded wasmtime runtime — no
                    // external binary on PATH. Mirrors `plugins doctor`.
                    if p.is_wasm() {
                        continue;
                    }
                    if which::which(&p.runtime).is_err() {
                        broken.push(format!("{} (runtime `{}` not found)", p.name, p.runtime));
                    }
                }
                if broken.is_empty() {
                    println!("  {} {} plugin(s) OK", green("[ok]"), plugins.len());
                    passed += 1;
                } else {
                    println!(
                        "  {} {} plugin(s), {} broken",
                        yellow("[warn]"),
                        plugins.len(),
                        broken.len()
                    );
                    for b in &broken {
                        issues.push(Issue::warn(format!("plugin {b}")));
                    }
                }
            }
            Ok(_) => {
                println!("  {} no plugins installed", dim("[--]"));
            }
            Err(_) => {
                println!("  {} plugins directory not accessible", dim("[--]"));
            }
        }
    }

    // -- env vars referenced in config ----------------------------------------
    println!();
    println!("  {} env vars referenced in rsclaw.json5", bold("Env:"));
    if let Some(cfg_path) = config::loader::detect_config_path() {
        match std::fs::read_to_string(&cfg_path) {
            Ok(raw) => {
                let needed = config::env_resolution::scan_var_refs(&raw);
                if needed.is_empty() {
                    println!("  {} no ${{VAR}} or env SecretRef references", dim("[--]"));
                } else {
                    let env_path = config::loader::base_dir().join(".env");
                    let file_vars = config::env_file::read(&env_path).unwrap_or_default();
                    let mut missing: Vec<&String> = Vec::new();
                    let mut drift: Vec<&String> = Vec::new();
                    for var in &needed {
                        let in_shell = std::env::var(var).is_ok();
                        let file_v = file_vars.get(var);
                        let shell_v = std::env::var(var).ok();
                        match (in_shell, file_v.is_some()) {
                            (false, false) => missing.push(var),
                            (true, true) if shell_v.as_deref() != file_v.map(String::as_str) => {
                                drift.push(var);
                            }
                            _ => passed += 1,
                        }
                    }
                    if !missing.is_empty() {
                        for v in &missing {
                            issues.push(Issue::warn(format!(
                                "env var '{v}' referenced in config but not set anywhere (provider will be disabled)"
                            )));
                        }
                    }
                    if !drift.is_empty() {
                        for v in &drift {
                            issues.push(Issue::warn(format!(
                                "env var '{v}' has different values in shell vs .env (next gateway start will sync shell -> .env)"
                            )));
                        }
                    }
                    println!(
                        "  {} {} var(s) referenced -- {} ok, {} missing, {} drift",
                        dim("[--]"),
                        needed.len(),
                        passed.min(needed.len()),
                        missing.len(),
                        drift.len(),
                    );
                }
            }
            Err(e) => {
                println!("  {} could not read config: {e}", yellow("[!!]"));
            }
        }
    }

    // -- Summary & apply fixes ------------------------------------------------
    let fixable_count = issues.iter().filter(|i| i.fix_fn.is_some()).count();
    let issue_count = issues.len();

    println!();
    if issues.is_empty() {
        println!("  {}", green(&format!("{passed} checks passed, 0 issues")));
        return Ok(());
    }

    for issue in &issues {
        if let Some(hint) = issue.fix_hint {
            eprintln!(
                "  {} {} {}",
                yellow("[warn]"),
                issue.message,
                dim(&format!("(fix: {hint})"))
            );
        } else {
            eprintln!("  {} {}", yellow("[warn]"), issue.message);
        }
    }

    println!();
    println!(
        "  {}",
        bold(&format!(
            "{passed} checks passed, {issue_count} issue(s) ({fixable_count} fixable)"
        ))
    );

    if args.fix {
        println!();
        for issue in issues {
            if let Some(fix) = issue.fix_fn {
                match fix() {
                    Ok(done) => println!("  {} {done}", green("[fixed]")),
                    Err(e) => eprintln!("  {} {}: {e:#}", red("[fix-failed]"), issue.message),
                }
            }
        }
    } else if fixable_count > 0 {
        eprintln!(
            "  {}",
            dim(&format!(
                "run `rsclaw doctor --fix` to apply {fixable_count} auto-fix(es)"
            ))
        );
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Attempt to repair broken JSON5 config by fixing common syntax issues:
/// - Missing commas between properties
/// - Trailing commas before closing braces
/// - Unquoted string values that should be quoted
fn repair_config_json() -> Result<String> {
    let Some(cfg_path) = config::loader::detect_config_path() else {
        anyhow::bail!("no config file found");
    };
    let raw = std::fs::read_to_string(&cfg_path)?;

    // Backup first
    let backup = cfg_path.with_extension("json5.bak");
    std::fs::copy(&cfg_path, &backup)?;

    let repaired = repair_json5_syntax(&raw);

    // Try parsing the repaired version
    match json5::from_str::<serde_json::Value>(&repaired) {
        Ok(mut val) => {
            // Also fix type mismatches while we're at it
            fix_types_recursive(&mut val);
            std::fs::write(&cfg_path, serde_json::to_string_pretty(&val)?)?;
            Ok(format!(
                "repaired and reformatted config (backup at {})",
                backup.display()
            ))
        }
        Err(e) => {
            // Repaired version still broken -- try writing it anyway (might be closer to
            // valid)
            std::fs::write(&cfg_path, &repaired)?;
            anyhow::bail!(
                "partial repair applied but config still has errors: {e}. \
                 Backup at {}. Please fix manually.",
                backup.display()
            )
        }
    }
}

/// Fix common JSON5 syntax issues in raw text.
fn repair_json5_syntax(raw: &str) -> String {
    let mut lines: Vec<String> = raw.lines().map(|l| l.to_string()).collect();
    let mut i = 0;

    while i < lines.len() {
        let trimmed = lines[i].trim().to_owned();

        if trimmed.is_empty() || trimmed.starts_with("//") {
            i += 1;
            continue;
        }

        // Fix: line ends with a value and next line starts a new key -- insert comma
        if !trimmed.ends_with(',')
            && !trimmed.ends_with('{')
            && !trimmed.ends_with('[')
            && !trimmed.ends_with(':')
            && trimmed != "}"
            && trimmed != "]"
            && trimmed != "},"
            && trimmed != "],"
        {
            let next_trimmed = lines[i + 1..]
                .iter()
                .find(|l| {
                    let t = l.trim();
                    !t.is_empty() && !t.starts_with("//")
                })
                .map(|l| l.trim().to_owned());

            if let Some(ref nt) = next_trimmed {
                let needs_comma = nt.starts_with('"')
                    || nt.starts_with('\'')
                    || nt
                        .chars()
                        .next()
                        .is_some_and(|c| c.is_alphanumeric() || c == '_');
                if needs_comma {
                    lines[i] = format!("{},", lines[i].trim_end());
                }
            }
        }

        i += 1;
    }

    lines.join("\n")
}

/// Fix string-valued booleans/numbers in the config JSON.
/// e.g. `"true"` -> `true`, `"false"` -> `false`, `"18888"` -> `18888`
fn fix_config_type_mismatches() -> Result<String> {
    let Some(cfg_path) = config::loader::detect_config_path() else {
        anyhow::bail!("no config file found");
    };
    let raw = std::fs::read_to_string(&cfg_path)?;
    let mut val: serde_json::Value = json5::from_str(&raw)?;
    let count = fix_types_recursive(&mut val);
    if count == 0 {
        return Ok("no mismatches found".to_string());
    }
    std::fs::write(&cfg_path, serde_json::to_string_pretty(&val)?)?;
    Ok(format!(
        "fixed {count} type mismatch(es) in {}",
        cfg_path.display()
    ))
}

fn fix_types_recursive(val: &mut serde_json::Value) -> usize {
    let mut count = 0;
    match val {
        serde_json::Value::Object(map) => {
            let keys: Vec<String> = map.keys().cloned().collect();
            for key in keys {
                if let Some(v) = map.get_mut(&key) {
                    if let serde_json::Value::String(s) = v {
                        if s == "true" {
                            *v = serde_json::Value::Bool(true);
                            count += 1;
                        } else if s == "false" {
                            *v = serde_json::Value::Bool(false);
                            count += 1;
                        } else if key == "port"
                            && let Ok(n) = s.parse::<u64>()
                        {
                            *v = serde_json::json!(n);
                            count += 1;
                        } else if key == "model" && s.contains('/') {
                            // "model": "provider/name" -> "model": { "primary": "provider/name" }
                            *v = serde_json::json!({ "primary": s.clone() });
                            count += 1;
                        }
                    } else {
                        count += fix_types_recursive(v);
                    }
                }
            }
        }
        serde_json::Value::Array(arr) => {
            for item in arr {
                count += fix_types_recursive(item);
            }
        }
        _ => {}
    }
    count
}

/// Check if a process with the given PID is running.
fn process_exists(pid: u32) -> bool {
    rsclaw_platform::process_alive(pid)
}