netsky 0.1.6

netsky CLI: the viable system launcher and subcommand dispatcher
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
//! `netsky doctor [--brief|--quiet]` — one-command health smoke test.
//!
//! Runs a batch of non-destructive read-only checks grouped by section.
//! Exits 0 on green + yellow, 1 on red. `--brief` prints only the summary
//! line; `--quiet` is exit-code only.
//!
//! PUSH vs PULL: the escalation marker is the push signal ("system is
//! unwell, come look now"); doctor is the pull signal ("what is the
//! current state").

use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};

use netsky_core::config::Config;
use netsky_core::consts::{
    AGENT0_NAME, AGENTINFINITY_NAME, CLAUDE, DISK_MIN_MB_DEFAULT, ENV_DISK_MIN_MB,
    ENV_TICKER_INTERVAL, LAUNCHD_LABEL, NETSKY_BIN, TICKER_INTERVAL_DEFAULT_S, TICKER_LOG_PATH,
    TICKER_SESSION, TMUX_BIN,
};
use netsky_core::paths::{
    agent0_hang_marker, agent0_inbox_dir, agentinfinity_ready_marker, agentinit_escalation_marker,
    agentinit_failures_file, handoff_archive_dir, home, is_netsky_source_tree, resolve_netsky_dir,
    ticker_missing_count_file,
};
use netsky_sh::{tmux, which};

#[derive(Clone, Copy, PartialEq, Eq)]
enum Verdict {
    Green,
    Yellow,
    Red,
}

struct Doc {
    brief: bool,
    quiet: bool,
    red: u32,
    yellow: u32,
}

pub fn run(brief: bool, quiet: bool) -> netsky_core::Result<()> {
    let mut d = Doc {
        brief,
        quiet,
        red: 0,
        yellow: 0,
    };

    d.section("tmux");
    for sess in [AGENT0_NAME, AGENTINFINITY_NAME] {
        if tmux::session_is_alive(sess) {
            d.check(sess, Verdict::Green, "session alive");
        } else if tmux::has_session(sess) {
            d.check(sess, Verdict::Red, "session pane exited");
        } else {
            d.check(sess, Verdict::Red, "session MISSING");
        }
    }
    check_ticker(&mut d);

    d.section("channels");
    check_inbox(&mut d);
    check_clone_inboxes(&mut d);

    d.section("markers");
    check_markers(&mut d);

    d.section("watchdog");
    check_watchdog(&mut d);

    d.section("disk");
    check_disk(&mut d);

    d.section("archives");
    check_archives(&mut d);

    d.section("binaries");
    for bin in [CLAUDE, NETSKY_BIN, TMUX_BIN] {
        match which(bin) {
            Some(p) => d.check(bin, Verdict::Green, &p.display().to_string()),
            None => d.check(
                bin,
                Verdict::Red,
                "not on PATH — see ONBOARDING.md or run /onboard",
            ),
        }
    }

    d.section("config");
    check_config(&mut d);

    d.section("hooks");
    check_hooks(&mut d);

    d.section("launchctl");
    check_launchctl(&mut d);

    let red = d.red;
    let yellow = d.yellow;
    d.summary(red, yellow);

    if red > 0 {
        netsky_core::bail!("doctor: red")
    } else {
        Ok(())
    }
}

// ---- checks ---------------------------------------------------------------

fn check_inbox(d: &mut Doc) {
    let inbox = agent0_inbox_dir();
    let name = "agent0 inbox";
    match inbox_status(&inbox) {
        InboxStatus::Present(n) => {
            let (v, det) = inbox_verdict(n);
            d.check(name, v, &det);
        }
        InboxStatus::Missing => d.check(
            name,
            Verdict::Red,
            &format!("directory missing: {}", inbox.display()),
        ),
    }
}

fn check_clone_inboxes(d: &mut Doc) {
    let root = home().join(".claude/channels/agent");
    let Ok(entries) = fs::read_dir(&root) else {
        d.check(
            "clone inboxes",
            Verdict::Yellow,
            &format!("channel root missing: {}", root.display()),
        );
        return;
    };

    let mut counts = Vec::new();
    for entry in entries.filter_map(|e| e.ok()) {
        let path = entry.path();
        let Some(name) = path.file_name().and_then(|s| s.to_str()) else {
            continue;
        };
        if name == "agent0" || !is_clone_agent_name(name) {
            continue;
        }
        if let InboxStatus::Present(n) = inbox_status(&path.join("inbox")) {
            counts.push((name.to_string(), n));
        }
    }
    counts.sort();

    if counts.is_empty() {
        d.check("clone inboxes", Verdict::Green, "none present");
        return;
    }

    let total: usize = counts.iter().map(|(_, n)| *n).sum();
    let max = counts.iter().map(|(_, n)| *n).max().unwrap_or(0);
    let blocked: Vec<_> = counts.iter().filter(|(_, n)| *n > 0).collect();
    let detail = if blocked.is_empty() {
        format!("{} clone inbox(es) empty", counts.len())
    } else {
        let sample = blocked
            .iter()
            .take(4)
            .map(|(name, n)| format!("{name}:{n}"))
            .collect::<Vec<_>>()
            .join(", ");
        format!(
            "{total} pending across {} clone(s): {sample}",
            blocked.len()
        )
    };
    let verdict = if max > 4 {
        Verdict::Red
    } else if total > 0 {
        Verdict::Yellow
    } else {
        Verdict::Green
    };
    d.check("clone inboxes", verdict, &detail);
}

enum InboxStatus {
    Present(usize),
    Missing,
}

fn inbox_status(inbox: &Path) -> InboxStatus {
    match fs::read_dir(inbox) {
        Ok(entries) => InboxStatus::Present(pending_json_count(entries)),
        Err(_) => InboxStatus::Missing,
    }
}

fn pending_json_count(entries: fs::ReadDir) -> usize {
    entries
        .filter_map(|e| e.ok())
        .filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some("json"))
        .count()
}

fn inbox_verdict(n: usize) -> (Verdict, String) {
    match n {
        0 => (Verdict::Green, "empty (drained)".to_string()),
        1..=4 => (Verdict::Yellow, format!("{n} envelope(s) pending")),
        _ => (
            Verdict::Red,
            format!("{n} envelopes backing up — MCP poll stalled?"),
        ),
    }
}

fn is_clone_agent_name(name: &str) -> bool {
    name.strip_prefix("agent")
        .is_some_and(|n| !n.is_empty() && n.chars().all(|ch| ch.is_ascii_digit()))
}

fn check_markers(d: &mut Doc) {
    let ready = agentinfinity_ready_marker();
    if ready.exists() {
        d.check("agentinfinity-ready", Verdict::Green, "present");
    } else {
        d.check(
            "agentinfinity-ready",
            Verdict::Red,
            "marker missing; agentinit phase-2 never completed",
        );
    }

    let esc = agentinit_escalation_marker();
    if esc.exists() {
        d.check(
            "agentinit-escalation",
            Verdict::Red,
            &format!("ESCALATION FIRED — see {}", esc.display()),
        );
    } else {
        d.check(
            "agentinit-escalation",
            Verdict::Green,
            "absent (no escalation)",
        );
    }

    let hang = agent0_hang_marker();
    if hang.exists() {
        d.check(
            "agent0-hang-suspected",
            Verdict::Red,
            &format!("HANG SUSPECTED — see {}", hang.display()),
        );
    } else {
        d.check(
            "agent0-hang-suspected",
            Verdict::Green,
            "absent (pane is progressing)",
        );
    }

    let fails = agentinit_failures_file();
    match fs::read_to_string(&fails) {
        Ok(s) => {
            let n = s.lines().filter(|l| !l.trim().is_empty()).count();
            let (v, det) = match n {
                0 => (Verdict::Green, "empty".to_string()),
                1..=2 => (Verdict::Yellow, format!("{n} recent failure(s) in window")),
                _ => (
                    Verdict::Red,
                    format!("{n} failures in window (at/over threshold)"),
                ),
            };
            d.check("agentinit-failures", v, &det);
        }
        Err(_) => d.check("agentinit-failures", Verdict::Green, "no failures recorded"),
    }
}

fn check_watchdog(d: &mut Doc) {
    let log = Path::new(TICKER_LOG_PATH);
    if !log.exists() {
        d.check(
            "watchdog.out.log",
            Verdict::Red,
            &format!("log not present at {}", log.display()),
        );
        return;
    }
    let age = age_seconds(log).unwrap_or(u64::MAX);
    let (v, det) = match age {
        a if a <= 300 => (Verdict::Green, format!("{a}s ago")),
        a if a <= 600 => (Verdict::Yellow, format!("{a}s ago (>5min)")),
        a => (
            Verdict::Red,
            format!("{a}s ago (>10min — watchdog stalled?)"),
        ),
    };
    d.check("watchdog.out.log mtime", v, &det);

    if let Some(last) = last_line(log) {
        let truncated: String = last.chars().take(70).collect();
        d.check("watchdog last entry", Verdict::Green, &truncated);
    }

    // Tick-rate over last 10 minutes.
    let interval = std::env::var(ENV_TICKER_INTERVAL)
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(TICKER_INTERVAL_DEFAULT_S);
    let expected = 600u64.saturating_div(interval).max(1);
    let half = expected / 2;
    if let Ok(content) = fs::read_to_string(log) {
        let cutoff_s = unix_now().saturating_sub(600);
        let count = content
            .lines()
            .filter(|l| tick_line_after(l, cutoff_s))
            .count() as u64;
        let detail = format!("{count} tick(s) in last 10min (expected ~{expected})");
        let v = if count >= half {
            Verdict::Green
        } else if count > 0 {
            Verdict::Yellow
        } else {
            Verdict::Red
        };
        d.check("watchdog tick-rate", v, &detail);
    }
}

fn check_ticker(d: &mut Doc) {
    if tmux::has_session(TICKER_SESSION) {
        d.check(TICKER_SESSION, Verdict::Green, "session alive");
        return;
    }

    let missing = fs::read_to_string(ticker_missing_count_file())
        .ok()
        .and_then(|s| s.trim().parse::<u32>().ok())
        .unwrap_or(0);
    let detail = match missing {
        0 => "session missing; watchdog will self-heal on the next miss".to_string(),
        1 => "missing for 1 tick; watchdog will respawn on the second miss".to_string(),
        n => format!("missing for {n} ticks; watchdog self-heal pending"),
    };
    d.check(TICKER_SESSION, Verdict::Yellow, &detail);
}

fn check_disk(d: &mut Doc) {
    let min_mb = std::env::var(ENV_DISK_MIN_MB)
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(DISK_MIN_MB_DEFAULT);

    let avail_mb = match Command::new("df").args(["-Pk", "/tmp"]).output() {
        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
            .lines()
            .nth(1)
            .and_then(|line| line.split_whitespace().nth(3))
            .and_then(|s| s.parse::<u64>().ok())
            .map(|kb| kb / 1024),
        _ => None,
    };
    match avail_mb {
        Some(mb) if mb >= min_mb * 2 => d.check(
            "/tmp free",
            Verdict::Green,
            &format!("{mb}MB (threshold {min_mb}MB)"),
        ),
        Some(mb) if mb >= min_mb => d.check(
            "/tmp free",
            Verdict::Yellow,
            &format!("{mb}MB (close to {min_mb}MB threshold)"),
        ),
        Some(mb) => d.check(
            "/tmp free",
            Verdict::Red,
            &format!("{mb}MB < {min_mb}MB threshold"),
        ),
        None => d.check("/tmp free", Verdict::Yellow, "df parse failed"),
    }
}

fn check_archives(d: &mut Doc) {
    let archive = handoff_archive_dir();
    if archive.exists() {
        if fs::metadata(&archive).is_ok_and(|m| !m.permissions().readonly()) {
            let n = fs::read_dir(&archive)
                .map(|es| {
                    es.filter_map(|e| e.ok())
                        .filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some("json"))
                        .count()
                })
                .unwrap_or(0);
            d.check(
                "handoff archive",
                Verdict::Green,
                &format!("{n} envelope(s); writable"),
            );
        } else {
            d.check("handoff archive", Verdict::Red, "exists but not writable");
        }
    } else if let Some(parent) = archive.parent()
        && fs::metadata(parent).is_ok_and(|m| !m.permissions().readonly())
    {
        d.check(
            "handoff archive",
            Verdict::Green,
            "not yet created (parent writable; created on next restart)",
        );
    } else {
        d.check("handoff archive", Verdict::Red, "parent dir not writable");
    }
}

fn check_config(d: &mut Doc) {
    // NETSKY_DIR resolution. Binary-only installs are green and get a
    // note so the operator knows the source tree is optional.
    let dir = resolve_netsky_dir();
    if is_netsky_source_tree(&dir) {
        d.check("netsky dir", Verdict::Green, &dir.display().to_string());
    } else {
        d.check(
            "netsky dir",
            Verdict::Green,
            &format!(
                "binary mode at {} (prompts, addenda, and notes live under ~/.netsky)",
                dir.display()
            ),
        );
    }

    // netsky.toml presence + parse health. Missing is GREEN (steady
    // state today; loader treats it as "use env + defaults"). Present-
    // but-malformed is RED — a parse error means env precedence still
    // works but anyone editing the file is going to be confused.
    let toml_path = netsky_core::config::netsky_toml_path();
    match Config::load_from(&toml_path) {
        Ok(None) => d.check(
            "netsky.toml",
            Verdict::Green,
            &format!("absent at {} (env + defaults active)", toml_path.display()),
        ),
        Ok(Some(cfg)) => {
            let owner = cfg
                .owner
                .as_ref()
                .and_then(|o| o.name.as_deref())
                .unwrap_or("(no [owner].name)");
            let machine = cfg
                .netsky
                .as_ref()
                .and_then(|n| n.machine_id.as_deref())
                .unwrap_or("(no [netsky].machine_id)");
            let addendum = cfg
                .addendum
                .as_ref()
                .and_then(|a| a.agent0.as_deref())
                .unwrap_or("(no [addendum].agent0; defaults to 0.md)");
            d.check(
                "netsky.toml",
                Verdict::Green,
                &format!(
                    "loaded from {} (owner={owner}, machine={machine}, addendum.agent0={addendum})",
                    toml_path.display()
                ),
            );
        }
        Err(e) => d.check(
            "netsky.toml",
            Verdict::Red,
            &format!("parse failed at {}: {e}", toml_path.display()),
        ),
    }
}

fn check_hooks(d: &mut Doc) {
    let root = match Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .output()
    {
        Ok(o) if o.status.success() => {
            let s = String::from_utf8_lossy(&o.stdout).trim().to_string();
            if s.is_empty() {
                return;
            }
            Path::new(&s).to_path_buf()
        }
        _ => return,
    };
    let canonical = root.join(".githooks/pre-push");
    if !canonical.exists() {
        // Not a netsky-style repo; silently skip.
        return;
    }
    let hook = root.join(".git/hooks/pre-push");
    match crate::cmd::hooks::classify(&hook) {
        crate::cmd::hooks::HookState::CanonicalLink => {
            // classify() is pure topology — the symlink points where we
            // want. Health requires the canonical also exist and be
            // executable. A missing/non-exec canonical is a silent
            // "hook present but will crash on invocation" hole.
            if !canonical.exists() {
                d.check(
                    "pre-push hook",
                    Verdict::Yellow,
                    "symlink ok but canonical missing",
                );
            } else if !fs::metadata(&canonical)
                .map(|m| m.permissions().mode() & 0o111 != 0)
                .unwrap_or(false)
            {
                d.check(
                    "pre-push hook",
                    Verdict::Yellow,
                    "symlink ok but canonical not executable",
                );
            } else {
                d.check("pre-push hook", Verdict::Green, "canonical symlink");
            }
        }
        crate::cmd::hooks::HookState::Absent => {
            d.check(
                "pre-push hook",
                Verdict::Red,
                "absent — run `netsky hooks install`",
            );
        }
        crate::cmd::hooks::HookState::Drift => {
            d.check(
                "pre-push hook",
                Verdict::Red,
                "drifted — run `netsky hooks install --force`",
            );
        }
    }
    if std::env::var("SKIP_PREPUSH_CHECK").is_ok_and(|v| v == "1") {
        d.check(
            "SKIP_PREPUSH_CHECK",
            Verdict::Yellow,
            "set in env; hook will be bypassed",
        );
    }
}

fn check_launchctl(d: &mut Doc) {
    if which("launchctl").is_none() {
        return;
    }
    let target = format!("gui/{}/{LAUNCHD_LABEL}", unsafe { getuid() });
    let loaded = Command::new("launchctl")
        .args(["print", &target])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if loaded {
        d.check(LAUNCHD_LABEL, Verdict::Green, "plist loaded");
    } else {
        d.check(
            LAUNCHD_LABEL,
            Verdict::Yellow,
            "plist not loaded (tmux-ticker is primary; this is fallback)",
        );
    }
}

// ---- printing -------------------------------------------------------------

impl Doc {
    fn section(&self, label: &str) {
        if !self.brief && !self.quiet {
            println!();
            println!("{label}");
        }
    }
    fn check(&mut self, name: &str, v: Verdict, detail: &str) {
        match v {
            Verdict::Green => {}
            Verdict::Yellow => self.yellow += 1,
            Verdict::Red => self.red += 1,
        }
        if self.brief || self.quiet {
            return;
        }
        let badge = match v {
            Verdict::Green => "ok",
            Verdict::Yellow => "warn",
            Verdict::Red => "FAIL",
        };
        println!("  [{badge:>4}] {name:<34} {detail}");
    }
    fn summary(&self, red: u32, yellow: u32) {
        if self.quiet {
            return;
        }
        if !self.brief {
            println!();
            print!("summary: ");
        }
        if red > 0 {
            println!("RED — {red} fail, {yellow} warn");
        } else if yellow > 0 {
            println!("YELLOW — {yellow} warn");
        } else {
            println!("GREEN — all checks passed");
        }
    }
}

// ---- util ---------------------------------------------------------------

fn age_seconds(path: &Path) -> Option<u64> {
    let mtime = fs::metadata(path).ok()?.modified().ok()?;
    SystemTime::now()
        .duration_since(mtime)
        .ok()
        .map(|d| d.as_secs())
}

fn last_line(path: &Path) -> Option<String> {
    fs::read_to_string(path)
        .ok()
        .and_then(|s| s.lines().last().map(|s| s.to_string()))
}

fn unix_now() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// True when a log line of the form `[watchdog-tick <ISO-TS>] ...` has a
/// timestamp at or after `cutoff_s` (unix seconds). ISO-8601 strings in
/// the log sort lexicographically in chronological order, so we compare
/// against the ISO form of the cutoff without parsing each tick line.
fn tick_line_after(line: &str, cutoff_s: u64) -> bool {
    let Some(rest) = line.strip_prefix("[watchdog-tick ") else {
        return false;
    };
    let Some(end) = rest.find(']') else {
        return false;
    };
    let ts = &rest[..end];
    let cutoff_iso = chrono::DateTime::<chrono::Utc>::from_timestamp(cutoff_s as i64, 0)
        .map(|dt| dt.format("%Y-%m-%dT%H:%M:%SZ").to_string());
    match cutoff_iso {
        Some(c) => ts >= c.as_str(),
        None => false,
    }
}

#[allow(non_snake_case)]
unsafe fn getuid() -> u32 {
    unsafe extern "C" {
        fn getuid() -> u32;
    }
    unsafe { getuid() }
}