netsky 0.1.4

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
//! 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 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::Claude)]
        agent_type: AgentType,
    },
    /// Stop the constellation.
    Down,
    /// 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::Claude)]
        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 launchd plists.
    #[command(subcommand)]
    Launchd(LaunchdCommand),
    /// Inspect handoffs.
    Handoffs {
        #[arg(value_name = "WHICH", default_value = "list")]
        which: String,
        /// Max entries in list mode.
        #[arg(short = 'n', long, default_value_t = 50)]
        limit: usize,
    },
    /// Send an escalation.
    Escalate {
        /// Subject line.
        subject: String,
        /// Optional body text.
        body: Option<String>,
    },
    /// Run a health check.
    Doctor {
        /// Print brief status.
        #[arg(long)]
        brief: bool,
        /// Suppress non-essential output.
        #[arg(long)]
        quiet: bool,
    },
    /// Print the morning summary.
    Morning {
        /// Include a send-requested note.
        #[arg(long)]
        send: bool,
    },
    /// Arm a quiet sentinel.
    Quiet {
        /// Quiet 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,
    },
    /// 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)]
    Io(IoCommand),
}

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

#[derive(Subcommand, Debug)]
pub enum WatchdogCommand {
    /// Run one watchdog tick.
    Tick,
}

#[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.
    TickerStart,
}

#[derive(Subcommand, Debug)]
pub enum LaunchdCommand {
    /// Install launchd plists.
    Install,
    /// Remove launchd plists.
    Uninstall,
    /// Print launchd status.
    Status,
    /// 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,
    },
    /// Send one agent envelope.
    Send {
        #[arg(value_name = "TARGET")]
        target: String,
        #[arg(value_name = "TEXT")]
        text: String,
        /// Sender identity.
        #[arg(long)]
        from: Option<String>,
    },
    /// Inspect quarantined envelopes.
    Quarantine {
        /// Agent name.
        #[arg(value_name = "AGENT")]
        agent: String,
        /// List quarantined paths.
        #[arg(long)]
        list: 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,
}

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) => cmd::down::run(),
        Some(Command::Restart { n, handoff }) => cmd::restart::run(n, handoff.as_deref()),
        Some(Command::Agent {
            n,
            agent_type,
            fresh,
        }) => 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::Tick)) => cmd::watchdog::tick(),
        Some(Command::Tick(sub)) => cmd::tick::run(sub),
        Some(Command::Launchd(sub)) => cmd::launchd::run(sub),
        Some(Command::Handoffs { which, limit }) => cmd::handoffs::run(&which, limit),
        Some(Command::Escalate { subject, body }) => cmd::escalate::run(&subject, body.as_deref()),
        Some(Command::Doctor { brief, quiet }) => cmd::doctor::run(brief, quiet),
        Some(Command::Morning { send }) => cmd::morning::run(send),
        Some(Command::Quiet { seconds, reason }) => cmd::quiet::run(seconds, reason.as_deref()),
        Some(Command::Drill { n }) => cmd::drill::run(n),
        Some(Command::Test { suite }) => cmd::test::run(&suite),
        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),
    }
}

/// 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"),
        _ => 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)),
            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,
            })),
            None
        );
        assert_eq!(
            command_requires_netsky_cwd(&Some(Command::Morning { send: 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
        );
    }
}