netsky 0.1.7

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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! clap command tree for the `netsky` binary.

use clap::{Parser, Subcommand, ValueEnum};

use crate::cmd;
use netsky_io::IoCommand;

#[derive(Parser, Debug)]
#[command(name = "netsky", version, about = "Netsky constellation launcher.")]
pub struct Cli {
    #[command(subcommand)]
    pub command: Option<Command>,
}

#[derive(Subcommand, Debug)]
pub enum Command {
    /// Start the constellation.
    Up {
        /// Number of clones to start.
        #[arg(default_value_t = netsky_core::consts::DEFAULT_CLONE_COUNT)]
        n: u32,
        /// Runtime flavor for the constellation.
        #[arg(long = "type", value_enum, default_value_t = AgentType::Codex)]
        agent_type: AgentType,
    },
    /// Stop the constellation.
    Down {
        /// Kill agent sessions immediately without asking them to run /down.
        #[arg(long)]
        force: bool,
    },
    /// Restart the constellation.
    Restart {
        /// Number of clones to start.
        #[arg(default_value_t = netsky_core::consts::DEFAULT_CLONE_COUNT)]
        n: u32,
        /// Handoff file for the new agent0.
        #[arg(long)]
        handoff: Option<String>,
    },
    /// Run one agent.
    Agent {
        #[arg(value_name = "N")]
        n: u32,
        /// Runtime type for this agent.
        #[arg(long = "type", value_enum, default_value_t = AgentType::Codex)]
        agent_type: AgentType,
        /// Start from a clean session.
        #[arg(long)]
        fresh: bool,
    },
    /// Run one Codex turn.
    Codex {
        #[arg(value_name = "N")]
        n: u32,
        /// Start from a clean sidecar session.
        #[arg(long)]
        fresh: bool,
        /// Send a direct prompt.
        #[arg(long)]
        prompt: Option<String>,
        /// Drain one inbox envelope.
        #[arg(long)]
        drain: bool,
        /// Override the Codex model.
        #[arg(long)]
        model: Option<String>,
    },
    /// Attach to a tmux session.
    #[command(alias = "a")]
    Attach {
        #[arg(value_name = "TARGET")]
        target: String,
    },
    /// Start the watchdog.
    Agentinfinity,
    /// Run the agentinit gate.
    Agentinit {
        /// Target tmux session name.
        #[arg(default_value = netsky_core::consts::AGENTINFINITY_NAME)]
        session: String,
    },
    /// Run one watchdog tick.
    #[command(subcommand)]
    Watchdog(WatchdogCommand),
    /// Manage status ticks.
    #[command(subcommand)]
    Tick(TickCommand),
    /// Manage cron dispatch entries.
    #[command(subcommand)]
    Cron(CronCommand),
    /// Manage launchd plists.
    #[command(subcommand)]
    Launchd(LaunchdCommand),
    /// Inspect handoffs (subcommands: list | show [N|last] | prune | <N>).
    Handoffs {
        /// Selector: `list`, `show`, `prune`, `last`, a numeric index, or
        /// blank (defaults to `list`). Freeform forms stay supported as
        /// aliases of the new subcommand grammar.
        #[arg(value_name = "WHICH", default_value = "list")]
        which: String,
        /// For `show <ARG>`: the index (1-based) or `last`.
        #[arg(value_name = "ARG")]
        arg: Option<String>,
        /// Max entries in list mode; for `prune`, the number to keep
        /// (alias `--keep` reads more naturally for the prune verb).
        #[arg(short = 'n', long, alias = "keep", default_value_t = 50)]
        limit: usize,
        /// Print a JSON envelope instead of operator text.
        #[arg(long)]
        json: bool,
    },
    /// Send an escalation.
    Escalate {
        /// Subject line.
        subject: String,
        /// Optional body text.
        body: Option<String>,
    },
    /// Bootstrap ~/netsky from embedded files.
    Init {
        /// Refresh skills and prompts from the binary.
        #[arg(long)]
        update: bool,
        /// Target directory.
        #[arg(long, value_name = "DIR")]
        path: Option<std::path::PathBuf>,
    },
    /// Run the interactive onboarding wizard.
    Onboard,
    /// Print system status.
    Status {
        /// Print a JSON envelope instead of operator text.
        #[arg(long)]
        json: bool,
    },
    /// Query the observability store with SQL.
    Query {
        #[arg(value_name = "SQL")]
        sql: String,
        /// Print a JSON envelope instead of the operator table.
        #[arg(long)]
        json: bool,
    },
    /// Aggregate observability into daily reports.
    #[command(subcommand)]
    Analytics(cmd::analytics::AnalyticsCommand),
    /// Read unified local observability events.
    Events {
        /// Only include events newer than this duration, e.g. 10m, 2h, 1d.
        #[arg(long)]
        since: Option<String>,
        /// Only include events before this UTC timestamp.
        #[arg(long)]
        until: Option<String>,
        /// Filter to one agent id.
        #[arg(long)]
        agent: Option<String>,
        /// Filter to one event kind.
        #[arg(long)]
        kind: Option<String>,
        /// Limit the number of events printed.
        #[arg(long)]
        limit: Option<usize>,
        /// Print a JSON array instead of operator text.
        #[arg(long)]
        json: bool,
    },
    /// Inspect codified cybernetic gates.
    Gates {
        /// Print JSON instead of operator text.
        #[arg(long)]
        json: bool,
        /// Gate name to inspect.
        #[arg(value_name = "NAME")]
        name: Option<String>,
    },
    /// Ingest external observability sources.
    #[command(subcommand)]
    Ingest(cmd::ingest::IngestCommand),
    /// Manage the local task tracker.
    #[command(subcommand)]
    Task(cmd::task::TaskCommand),
    /// Run a health check.
    Doctor {
        /// Print only the one-line summary (for scripts that want a badge).
        #[arg(long, conflicts_with_all = ["quiet", "json"])]
        brief: bool,
        /// Silent on pass; exit code only (for boolean probes).
        #[arg(long, conflicts_with_all = ["brief", "json"])]
        quiet: bool,
        /// Print a JSON envelope instead of operator text.
        #[arg(long, conflicts_with_all = ["brief", "quiet"])]
        json: bool,
    },
    /// Print the morning summary.
    Morning {
        /// Include a send-requested note.
        #[arg(long)]
        send: bool,
        /// Print a JSON envelope instead of operator text.
        #[arg(long, conflicts_with = "send")]
        json: bool,
    },
    /// Arm a quiet sentinel.
    Quiet {
        /// Quiet window in seconds.
        #[arg(value_name = "SECONDS")]
        seconds: u64,
        /// Optional reason text.
        #[arg(long)]
        reason: Option<String>,
    },
    /// Prepare a quiet sentinel before a long ScheduleWakeup nap.
    Nap {
        /// Nap window in seconds.
        #[arg(value_name = "SECONDS")]
        seconds: u64,
        /// Optional reason text.
        #[arg(long)]
        reason: Option<String>,
    },
    /// Run a resilience drill.
    Drill {
        #[arg(value_name = "N")]
        n: u8,
    },
    /// Run netsky tests.
    Test {
        /// Test suite to run.
        #[arg(default_value = "all")]
        suite: String,
    },
    /// Salvage a mid-crash session transcript into notes.
    #[command(subcommand)]
    Session(SessionCommand),
    /// Configure channel sources.
    #[command(subcommand)]
    Setup(SetupCommand),
    /// Manage the pre-push hook.
    #[command(subcommand)]
    Hooks(HooksCommand),
    /// Manage agent envelopes.
    #[command(subcommand)]
    Channel(ChannelCommand),
    /// Run the I/O stack.
    #[command(subcommand, visible_alias = "comms")]
    Io(IoCommand),
    /// Inspect netsky configuration across layers.
    #[command(subcommand)]
    Config(ConfigCommand),
    /// Observability namespace (alias of status / analytics / events / gates / session).
    ///
    /// Each subcommand dispatches to the same handler as its top-level form.
    /// The namespace exists to keep the cold subset reachable under one
    /// roof; both forms stay valid to preserve operator muscle memory.
    #[command(subcommand, hide = true)]
    Observe(ObserveCommand),
    /// Dev namespace (alias of init / agentinit / cron).
    ///
    /// Each subcommand dispatches to the same handler as its top-level form.
    #[command(subcommand, hide = true)]
    Dev(DevCommand),
    /// Admin namespace (alias of down / onboard).
    ///
    /// Each subcommand dispatches to the same handler as its top-level form.
    #[command(subcommand, hide = true)]
    Admin(AdminCommand),
}

#[derive(Subcommand, Debug)]
pub enum ObserveCommand {
    /// Same as top-level `netsky status`.
    Status {
        /// Print a JSON envelope instead of operator text.
        #[arg(long)]
        json: bool,
    },
    /// Same as top-level `netsky analytics`.
    #[command(subcommand)]
    Analytics(cmd::analytics::AnalyticsCommand),
    /// Same as top-level `netsky events`.
    Events {
        #[arg(long)]
        since: Option<String>,
        #[arg(long)]
        until: Option<String>,
        #[arg(long)]
        agent: Option<String>,
        #[arg(long)]
        kind: Option<String>,
        #[arg(long)]
        limit: Option<usize>,
        #[arg(long)]
        json: bool,
    },
    /// Same as top-level `netsky gates`.
    Gates {
        #[arg(long)]
        json: bool,
        #[arg(value_name = "NAME")]
        name: Option<String>,
    },
    /// Same as top-level `netsky session`.
    #[command(subcommand)]
    Session(SessionCommand),
}

#[derive(Subcommand, Debug)]
pub enum DevCommand {
    /// Same as top-level `netsky init`.
    Init {
        #[arg(long)]
        update: bool,
        #[arg(long, value_name = "DIR")]
        path: Option<std::path::PathBuf>,
    },
    /// Same as top-level `netsky agentinit`.
    Agentinit {
        #[arg(default_value = netsky_core::consts::AGENTINFINITY_NAME)]
        session: String,
    },
    /// Same as top-level `netsky cron`.
    #[command(subcommand)]
    Cron(CronCommand),
}

#[derive(Subcommand, Debug)]
pub enum AdminCommand {
    /// Same as top-level `netsky down`.
    Down {
        #[arg(long)]
        force: bool,
    },
    /// Same as top-level `netsky onboard`.
    Onboard,
}

#[derive(Subcommand, Debug)]
pub enum ConfigCommand {
    /// Show config plane by plane (netsky.toml, owner.toml+channels.toml, env, effective).
    Show {
        /// Print a JSON envelope instead of operator text.
        #[arg(long)]
        json: bool,
    },
    /// Parse every config file and report errors. Exit 1 on any parse failure.
    Check {
        /// Print a JSON envelope instead of operator text.
        #[arg(long)]
        json: bool,
    },
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub enum AgentType {
    Claude,
    Codex,
}

#[derive(Subcommand, Debug)]
pub enum WatchdogCommand {
    /// Start the watchdog (same as the top-level `netsky agentinfinity`).
    Start,
    /// Run one watchdog tick.
    Tick,
    /// Read durable watchdog JSONL events.
    Events {
        /// Only include events newer than this duration, e.g. 30m, 6h, 2d.
        #[arg(long)]
        since: Option<String>,
        /// Limit the number of events printed.
        #[arg(long)]
        limit: Option<usize>,
        /// Print a JSON array instead of operator text.
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand, Debug)]
pub enum TickCommand {
    /// Enable status ticks.
    Enable {
        #[arg(value_name = "SECONDS")]
        seconds: u64,
    },
    /// Disable status ticks.
    Disable,
    /// Request one status tick.
    Request,
    /// Run the ticker loop.
    Ticker,
    /// Start the ticker session (alias: ticker-start).
    #[command(alias = "ticker-start")]
    Start,
}

#[derive(Subcommand, Debug)]
pub enum CronCommand {
    /// Add one cron entry.
    Add {
        #[arg(value_name = "LABEL")]
        label: String,
        #[arg(value_name = "SCHEDULE")]
        schedule: String,
        #[arg(value_name = "TARGET")]
        target: String,
        #[arg(value_name = "PROMPT")]
        prompt: String,
        /// Print a JSON envelope instead of operator text.
        #[arg(long)]
        json: bool,
    },
    /// List cron entries.
    List {
        /// Print a JSON envelope instead of operator text.
        #[arg(long)]
        json: bool,
    },
    /// Remove one cron entry.
    Remove {
        #[arg(value_name = "LABEL")]
        label: String,
        /// Print a JSON envelope instead of operator text.
        #[arg(long)]
        json: bool,
    },
    /// Dispatch any due cron entries.
    Tick {
        /// Print a JSON envelope instead of operator text.
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand, Debug)]
pub enum LaunchdCommand {
    /// Install launchd plists.
    Install,
    /// Remove launchd plists.
    Uninstall,
    /// Print launchd status.
    Status {
        /// Print a JSON envelope instead of operator text.
        #[arg(long)]
        json: bool,
    },
    /// Reinstall launchd plists.
    Reinstall,
}

#[derive(Subcommand, Debug)]
pub enum SetupCommand {
    /// Set up Gmail OAuth.
    Email {
        /// Primary account address.
        account: Option<String>,
    },
}

#[derive(Subcommand, Debug)]
pub enum ChannelCommand {
    /// Drain an agent inbox.
    Drain {
        /// Agent name.
        #[arg(value_name = "AGENT")]
        agent: String,
        /// Print a JSON envelope summarizing deliveries instead of the
        /// `<channel ...>` wrapper stream. Mutually exclusive with the
        /// text stream consumed by codex agents.
        #[arg(long)]
        json: bool,
    },
    /// Deliver an agent inbox into a tmux resident session.
    ///
    /// Streams envelopes into a live pane via send-keys; operator-only
    /// (no --json mode — the output is paste framing, not a report).
    Watch {
        /// Agent name.
        #[arg(value_name = "AGENT")]
        agent: String,
        /// Target tmux session or pane.
        #[arg(long, value_name = "SESSION")]
        tmux: String,
    },
    /// Send one agent envelope.
    Send {
        #[arg(value_name = "TARGET")]
        target: String,
        #[arg(value_name = "TEXT")]
        text: String,
        /// Sender identity.
        #[arg(long)]
        from: Option<String>,
        /// Envelope kind.
        #[arg(long)]
        kind: Option<String>,
        /// Envelope thread.
        #[arg(long)]
        thread: Option<String>,
        /// Print a JSON envelope instead of operator text.
        #[arg(long)]
        json: bool,
    },
    /// Forward a codex agent outbox into agent0 inbox.
    ///
    /// Long-running loop; operator-only (no --json mode — this is a
    /// 500ms poll daemon, not a report).
    ForwardOutbox {
        /// Agent name.
        #[arg(value_name = "AGENT")]
        agent: String,
    },
    /// Acknowledge one agent envelope.
    Ack {
        #[arg(value_name = "MESSAGE_ID")]
        message_id: String,
        /// Acknowledgement status.
        #[arg(long, value_enum)]
        status: AckStatus,
        /// Optional human note.
        #[arg(long)]
        note: Option<String>,
        /// Print a JSON envelope instead of operator text.
        #[arg(long)]
        json: bool,
    },
    /// Inspect quarantined envelopes.
    Quarantine {
        /// Agent name.
        #[arg(value_name = "AGENT")]
        agent: String,
        /// List quarantined paths.
        #[arg(long)]
        list: bool,
        /// Print a JSON envelope instead of operator text.
        #[arg(long)]
        json: bool,
    },
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub enum AckStatus {
    Received,
    Started,
    Done,
    Blocker,
}

impl AckStatus {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Received => "received",
            Self::Started => "started",
            Self::Done => "done",
            Self::Blocker => "blocker",
        }
    }
}

#[derive(Subcommand, Debug)]
pub enum SessionCommand {
    /// Read a dead session's claude JSONL and append a retroactive
    /// block to notes/<YYYY>/<MM>/<DD>/agent0.md. Target is a session
    /// id, `latest`, or a full path to a .jsonl file.
    Salvage {
        #[arg(value_name = "TARGET")]
        target: String,
        /// Print a JSON envelope instead of operator text.
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand, Debug)]
pub enum HooksCommand {
    /// Install the pre-push hook.
    Install {
        /// Overwrite a drifted hook.
        #[arg(long)]
        force: bool,
    },
    /// Remove the pre-push hook.
    Uninstall,
    /// Print hook status.
    Status {
        /// Print a JSON envelope instead of operator text.
        #[arg(long)]
        json: bool,
    },
}

pub fn dispatch(cli: Cli) -> netsky_core::Result<()> {
    // Hard-exit gate for user-invoked constellation orchestration. Only
    // applies to commands that orchestrate agents directly; read-only,
    // launchd-spawned, and config-editing commands stay permissive so
    // they keep working from anywhere (which is critical for `doctor`
    // and `escalate` invoked under the watchdog tick from cwd `/`).
    if let Some(name) = command_requires_netsky_cwd(&cli.command) {
        netsky_core::paths::require_netsky_cwd(name)?;
    }
    match cli.command {
        None => {
            // Bare `netsky` = help.
            use clap::CommandFactory;
            Cli::command().print_help()?;
            println!();
            Ok(())
        }
        Some(Command::Up { n, agent_type }) => cmd::up::run(n, agent_type),
        Some(Command::Down { force }) => cmd::down::run(force),
        Some(Command::Restart { n, handoff }) => cmd::restart::run(n, handoff.as_deref()),
        Some(Command::Agent {
            n,
            agent_type,
            fresh,
        }) => {
            if n == 0 {
                cmd::agent::run(n, fresh)
            } else {
                match agent_type {
                    AgentType::Claude => cmd::agent::run(n, fresh),
                    AgentType::Codex => cmd::agent::run_codex_resident(n, fresh),
                }
            }
        }
        Some(Command::Codex {
            n,
            fresh,
            prompt,
            drain,
            model,
        }) => cmd::codex_agent::run(n, prompt.as_deref(), drain, model.as_deref(), fresh),
        Some(Command::Attach { target }) => cmd::attach::run(&target),
        Some(Command::Agentinfinity) => cmd::agentinfinity::run(),
        Some(Command::Agentinit { session }) => cmd::agentinit::run(&session),
        Some(Command::Watchdog(WatchdogCommand::Start)) => cmd::agentinfinity::run(),
        Some(Command::Watchdog(WatchdogCommand::Tick)) => cmd::watchdog::tick(),
        Some(Command::Watchdog(WatchdogCommand::Events { since, limit, json })) => {
            cmd::watchdog_events::run(since.as_deref(), limit, json)
        }
        Some(Command::Tick(sub)) => cmd::tick::run(sub),
        Some(Command::Cron(sub)) => cmd::cron::run(sub),
        Some(Command::Launchd(sub)) => cmd::launchd::run(sub),
        Some(Command::Handoffs {
            which,
            arg,
            limit,
            json,
        }) => cmd::handoffs::run(&which, arg.as_deref(), limit, json),
        Some(Command::Escalate { subject, body }) => cmd::escalate::run(&subject, body.as_deref()),
        Some(Command::Init { update, path }) => cmd::init::run(path, update),
        Some(Command::Onboard) => cmd::onboard::run(),
        Some(Command::Status { json }) => cmd::status::run(json),
        Some(Command::Query { sql, json }) => cmd::query::run(&sql, json),
        Some(Command::Analytics(sub)) => cmd::analytics::run(sub),
        Some(Command::Events {
            since,
            until,
            agent,
            kind,
            limit,
            json,
        }) => cmd::events::run(
            since.as_deref(),
            until.as_deref(),
            agent.as_deref(),
            kind.as_deref(),
            limit,
            json,
        ),
        Some(Command::Gates { json, name }) => cmd::gates::run(json, name.as_deref()),
        Some(Command::Ingest(sub)) => cmd::ingest::run(sub),
        Some(Command::Task(sub)) => cmd::task::run(sub),
        Some(Command::Doctor { brief, quiet, json }) => cmd::doctor::run(brief, quiet, json),
        Some(Command::Morning { send, json }) => cmd::morning::run(send, json),
        Some(Command::Quiet { seconds, reason }) => cmd::quiet::run(seconds, reason.as_deref()),
        Some(Command::Nap { seconds, reason }) => cmd::nap::run(seconds, reason.as_deref()),
        Some(Command::Drill { n }) => cmd::drill::run(n),
        Some(Command::Test { suite }) => cmd::test::run(&suite),
        Some(Command::Session(SessionCommand::Salvage { target, json })) => {
            cmd::session::salvage(&target, json)
        }
        Some(Command::Setup(sub)) => cmd::setup::run(sub),
        Some(Command::Hooks(sub)) => cmd::hooks::run(sub),
        Some(Command::Channel(sub)) => cmd::channel::run(sub),
        Some(Command::Io(sub)) => cmd::io::run(sub),
        Some(Command::Config(sub)) => cmd::config::run(sub),
        Some(Command::Observe(sub)) => match sub {
            ObserveCommand::Status { json } => cmd::status::run(json),
            ObserveCommand::Analytics(sub) => cmd::analytics::run(sub),
            ObserveCommand::Events {
                since,
                until,
                agent,
                kind,
                limit,
                json,
            } => cmd::events::run(
                since.as_deref(),
                until.as_deref(),
                agent.as_deref(),
                kind.as_deref(),
                limit,
                json,
            ),
            ObserveCommand::Gates { json, name } => cmd::gates::run(json, name.as_deref()),
            ObserveCommand::Session(SessionCommand::Salvage { target, json }) => {
                cmd::session::salvage(&target, json)
            }
        },
        Some(Command::Dev(sub)) => match sub {
            DevCommand::Init { update, path } => cmd::init::run(path, update),
            DevCommand::Agentinit { session } => cmd::agentinit::run(&session),
            DevCommand::Cron(sub) => cmd::cron::run(sub),
        },
        Some(Command::Admin(sub)) => match sub {
            AdminCommand::Down { force } => cmd::down::run(force),
            AdminCommand::Onboard => cmd::onboard::run(),
        },
    }
}

/// Returns the command name (for the error message) when the command
/// orchestrates the constellation directly and must run from inside a
/// netsky checkout. Returns None for read-only, launchd-spawned, or
/// config-editing commands.
///
/// Gated set is deliberately narrow:
/// - `up` / `down` / `restart`: spawn or tear down agent tmux sessions
///   that read repo files (skills, prompts, mcp config).
/// - `agent`: spawns a single agent the same way.
/// - `drill`: runs scripted constellation flows that exercise the same paths.
///
/// Not gated:
/// - `watchdog` / `agentinit`: launchd-spawned with cwd `/`. Resilience
///   primitives that must work regardless of cwd. Plist
///   `WorkingDirectory` will pin them to NETSKY_DIR in a follow-up.
/// - `escalate`: the failsafe owner-page path; runs under launchd ticks.
/// - `doctor` / `morning` / `handoffs` / `attach` / `launchd status` /
///   `hooks status`: read-only diagnostics, must work from anywhere so
///   the operator can investigate a misconfigured machine.
/// - `setup` / `hooks install|uninstall` / `launchd install|uninstall|reinstall` /
///   `tick *` / `agentinfinity` / `test`: edit user config or run
///   subprocesses; deferred to follow-up alongside per-command audits.
fn command_requires_netsky_cwd(cmd: &Option<Command>) -> Option<&'static str> {
    match cmd {
        Some(Command::Up { .. }) => Some("up"),
        Some(Command::Down { .. }) => Some("down"),
        Some(Command::Restart { .. }) => Some("restart"),
        Some(Command::Agent { .. }) => Some("agent"),
        Some(Command::Codex { .. }) => Some("codex"),
        Some(Command::Drill { .. }) => Some("drill"),
        // Namespace forms inherit the gate of their wrapped command.
        Some(Command::Admin(AdminCommand::Down { .. })) => Some("down"),
        _ => None,
    }
}

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

    #[test]
    fn gated_commands_return_their_name() {
        assert_eq!(
            command_requires_netsky_cwd(&Some(Command::Up {
                n: 0,
                agent_type: AgentType::Claude,
            })),
            Some("up")
        );
        assert_eq!(
            command_requires_netsky_cwd(&Some(Command::Down { force: false })),
            Some("down")
        );
        assert_eq!(
            command_requires_netsky_cwd(&Some(Command::Restart {
                n: 0,
                handoff: None,
            })),
            Some("restart")
        );
        assert_eq!(
            command_requires_netsky_cwd(&Some(Command::Agent {
                n: 1,
                agent_type: AgentType::Claude,
                fresh: false,
            })),
            Some("agent")
        );
        assert_eq!(
            command_requires_netsky_cwd(&Some(Command::Agent {
                n: 1,
                agent_type: AgentType::Codex,
                fresh: false,
            })),
            Some("agent")
        );
        assert_eq!(
            command_requires_netsky_cwd(&Some(Command::Codex {
                n: 1,
                fresh: false,
                prompt: None,
                drain: true,
                model: None,
            })),
            Some("codex")
        );
        assert_eq!(
            command_requires_netsky_cwd(&Some(Command::Drill { n: 1 })),
            Some("drill")
        );
    }

    #[test]
    fn ungated_commands_pass() {
        // Bare netsky (no subcommand) is the help path; never gated.
        assert_eq!(command_requires_netsky_cwd(&None), None);
        // Read-only diagnostics.
        assert_eq!(
            command_requires_netsky_cwd(&Some(Command::Doctor {
                brief: false,
                quiet: true,
                json: false,
            })),
            None
        );
        assert_eq!(
            command_requires_netsky_cwd(&Some(Command::Morning {
                send: false,
                json: false,
            })),
            None
        );
        // Watchdog runs under launchd from cwd `/`; never gated.
        assert_eq!(
            command_requires_netsky_cwd(&Some(Command::Watchdog(WatchdogCommand::Tick))),
            None
        );
        // Escalate is the failsafe page; runs under launchd ticks.
        assert_eq!(
            command_requires_netsky_cwd(&Some(Command::Escalate {
                subject: "x".into(),
                body: None,
            })),
            None
        );
    }

    #[test]
    fn parses_channel_ack() {
        use clap::Parser;

        let cli = Cli::parse_from([
            "netsky",
            "channel",
            "ack",
            "message-1",
            "--status",
            "done",
            "--note",
            "landed",
        ]);
        let Some(Command::Channel(ChannelCommand::Ack {
            message_id,
            status,
            note,
            ..
        })) = cli.command
        else {
            panic!("expected channel ack command");
        };
        assert_eq!(message_id, "message-1");
        assert_eq!(status, AckStatus::Done);
        assert_eq!(note.as_deref(), Some("landed"));
    }

    #[test]
    fn parses_cron_add() {
        use clap::Parser;

        let cli = Cli::parse_from([
            "netsky",
            "cron",
            "add",
            "morning-brief",
            "0 7 * * *",
            "agent0",
            "/morning-brief",
        ]);
        let Some(Command::Cron(CronCommand::Add {
            label,
            schedule,
            target,
            prompt,
            ..
        })) = cli.command
        else {
            panic!("expected cron add command");
        };
        assert_eq!(label, "morning-brief");
        assert_eq!(schedule, "0 7 * * *");
        assert_eq!(target, "agent0");
        assert_eq!(prompt, "/morning-brief");
    }

    #[test]
    fn parses_channel_send_kind_and_thread() {
        use clap::Parser;

        let cli = Cli::parse_from([
            "netsky",
            "channel",
            "send",
            "agent0",
            "/morning-brief",
            "--from",
            "agentcron",
            "--kind",
            "cron",
            "--thread",
            "morning-brief",
        ]);
        let Some(Command::Channel(ChannelCommand::Send {
            target,
            text,
            from,
            kind,
            thread,
            ..
        })) = cli.command
        else {
            panic!("expected channel send command");
        };
        assert_eq!(target, "agent0");
        assert_eq!(text, "/morning-brief");
        assert_eq!(from.as_deref(), Some("agentcron"));
        assert_eq!(kind.as_deref(), Some("cron"));
        assert_eq!(thread.as_deref(), Some("morning-brief"));
    }

    #[test]
    fn parses_drive_empty_trash() {
        use clap::Parser;
        use netsky_io::{DriveCmd, IoCommand};

        let cli = Cli::parse_from([
            "netsky",
            "io",
            "drive",
            "empty-trash",
            "cody@dkdc.dev",
            "--confirm",
        ]);
        let Some(Command::Io(IoCommand::Drive(DriveCmd::EmptyTrash { account, confirm }))) =
            cli.command
        else {
            panic!("expected drive empty-trash command");
        };
        assert_eq!(account, "cody@dkdc.dev");
        assert!(confirm);
    }

    #[test]
    fn parses_io_serve_agent() {
        use clap::Parser;
        use netsky_io::{IoCommand, SourceKind};

        let cli = Cli::parse_from(["netsky", "io", "serve", "-s", "agent"]);
        let Some(Command::Io(IoCommand::Serve { source })) = cli.command else {
            panic!("expected io serve command");
        };
        assert_eq!(source, SourceKind::Agent);
    }

    #[test]
    fn parses_comms_alias_serve_agent() {
        use clap::Parser;
        use netsky_io::{IoCommand, SourceKind};

        let cli = Cli::parse_from(["netsky", "comms", "serve", "-s", "agent"]);
        let Some(Command::Io(IoCommand::Serve { source })) = cli.command else {
            panic!("expected comms alias to parse as io serve command");
        };
        assert_eq!(source, SourceKind::Agent);
    }

    #[test]
    fn parses_down_force() {
        use clap::Parser;

        let cli = Cli::parse_from(["netsky", "down", "--force"]);
        let Some(Command::Down { force }) = cli.command else {
            panic!("expected down command");
        };
        assert!(force);
    }
}