netsky 0.1.3

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
//! 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 = "the netsky viable system launcher",
    long_about = "netsky — the viable AI system launcher.\n\n\
        The constellation runs in tmux sessions named agent0, agent1, \
        ..., agentN, plus the agentinfinity watchdog. Running agents \
        survive restarts; netsky itself is idempotent."
)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Option<Command>,
}

#[derive(Subcommand, Debug)]
pub enum Command {
    /// Bring up agent0 + N clones + agentinfinity watchdog.
    Up {
        /// Number of clones (agent0 + this many). Default: 0
        /// (agent0-only; clones spawn on-demand via `netsky agent <N>`).
        #[arg(default_value_t = netsky_core::consts::DEFAULT_CLONE_COUNT)]
        n: u32,
        /// Runtime flavor for every spawned agent in the constellation.
        /// Default: claude. `--type codex` swaps the whole constellation
        /// (agent0 + clones) to codex. Per-agent overrides still possible
        /// via `netsky agent N --type <other>` after the constellation is
        /// up, or via `AGENT_RUNTIME=<flavor>` in the shell environment.
        #[arg(long = "type", value_enum, default_value_t = AgentType::Claude)]
        agent_type: AgentType,
    },
    /// Tear down agent0 + clones (leaves agentinfinity + ticker alone).
    Down,
    /// Atomic constellation respawn.
    Restart {
        /// Number of clones (agent0 + this many). Default: 0
        /// (agent0-only; callers that want a wider constellation
        /// post-restart pass an explicit N).
        #[arg(default_value_t = netsky_core::consts::DEFAULT_CLONE_COUNT)]
        n: u32,
        /// Path to a handoff file. Its content is delivered to the new
        /// agent0 over the bus after /up completes. Pass `/dev/null` for none.
        #[arg(long)]
        handoff: Option<String>,
    },
    /// Spawn or drive a single agent. N=0 → agent0, N>0 → clone.
    Agent {
        #[arg(value_name = "N")]
        n: u32,
        /// Runtime type for this agent invocation.
        #[arg(long = "type", value_enum, default_value_t = AgentType::Claude)]
        agent_type: AgentType,
        /// Kill an existing session first, forcing a clean context.
        /// agent0 uses this to clear a polluted clone for a fresh brief.
        #[arg(long)]
        fresh: bool,
    },
    /// Codex sidecar path. One turn per invocation, then exit.
    Codex {
        #[arg(value_name = "N")]
        n: u32,
        /// Kill the sidecar state first, forcing a fresh thread.
        #[arg(long)]
        fresh: bool,
        /// Deliver this prompt directly instead of draining the inbox.
        #[arg(long)]
        prompt: Option<String>,
        /// Drain one pending envelope from the agent inbox.
        #[arg(long)]
        drain: bool,
        /// Codex model override.
        #[arg(long)]
        model: Option<String>,
    },
    /// Attach to an agent's tmux session. Target: N, `infinity`, `inf`, `ticker`.
    #[command(alias = "a")]
    Attach {
        #[arg(value_name = "TARGET")]
        target: String,
    },
    /// Ensure the agentinfinity watchdog is up.
    Agentinfinity,
    /// Agentinit bootstrap gate. Polls agentinfinity's readiness marker
    /// and dismisses the dev-channels TOS on its pane.
    Agentinit {
        /// Target tmux session name (the freshly-spawned agentinfinity).
        #[arg(default_value = netsky_core::consts::AGENTINFINITY_NAME)]
        session: String,
    },
    /// Watchdog tick (invoked by launchd).
    #[command(subcommand)]
    Watchdog(WatchdogCommand),
    /// Tick controls (arm/disarm, request, ticker session).
    #[command(subcommand)]
    Tick(TickCommand),
    /// Launchd plist management.
    #[command(subcommand)]
    Launchd(LaunchdCommand),
    /// View the handoff archive.
    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,
    },
    /// Shell-side iMessage escalation (floor page).
    Escalate {
        /// One-line subject.
        subject: String,
        /// Optional multi-line body.
        body: Option<String>,
    },
    /// One-command health check.
    Doctor {
        #[arg(long)]
        brief: bool,
        #[arg(long)]
        quiet: bool,
    },
    /// Overnight summary: doctor + commits + iteration log.
    Morning {
        /// Also surface a "send requested" note (placeholder — agent0
        /// pipes the output into an iMessage reply tool call).
        #[arg(long)]
        send: bool,
    },
    /// Arm a quiet-sentinel that suppresses hang detection for SECONDS.
    /// Call before a long ScheduleWakeup (>1200s) or a /loop stop so
    /// agentinfinity's 1800s pane-stable detector doesn't false-alarm.
    Quiet {
        /// Window in seconds (must be >= 1).
        #[arg(value_name = "SECONDS")]
        seconds: u64,
        /// Optional one-line reason written into the sentinel body for
        /// post-mortem debugging (not parsed by the watchdog).
        #[arg(long)]
        reason: Option<String>,
    },
    /// Run a drill. 1 = planned restart path. 2 = crash recovery path.
    Drill {
        #[arg(value_name = "N")]
        n: u8,
    },
    /// Run unit + agent-behavior tests.
    Test {
        /// Limit to a test suite (e.g. `unit`, `agent`).
        #[arg(default_value = "all")]
        suite: String,
    },
    /// First-run setup for channel sources (email OAuth, etc).
    #[command(subcommand)]
    Setup(SetupCommand),
    /// Manage the repo-tracked pre-push hook that enforces `bin/check`.
    #[command(subcommand)]
    Hooks(HooksCommand),
    /// Shell-facing agent-bus primitives. Drain an agent's inbox to stdout
    /// or send an envelope into another agent's inbox. Used by runtimes
    /// that cannot receive MCP server-pushed notifications (codex).
    #[command(subcommand)]
    Channel(ChannelCommand),
    /// The I/O stack and MCP source runner.
    #[command(subcommand)]
    Io(IoCommand),
}

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

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

#[derive(Subcommand, Debug)]
pub enum TickCommand {
    /// Enable status-tick pings to agent0 every N seconds.
    Enable {
        #[arg(value_name = "SECONDS")]
        seconds: u64,
    },
    /// Disable status-tick pings.
    Disable,
    /// Request a single tick.
    Request,
    /// Tmux-based ticker session entry point (the loop itself).
    Ticker,
    /// Idempotently spawn the ticker session.
    TickerStart,
}

#[derive(Subcommand, Debug)]
pub enum LaunchdCommand {
    Install,
    Uninstall,
    Status,
    /// Uninstall then install. Used during upgrades.
    Reinstall,
}

#[derive(Subcommand, Debug)]
pub enum SetupCommand {
    /// Run the Gmail OAuth "installed app" flow for a primary account.
    /// First-run UX replacement for `netsky io access email oauth-init <addr>`.
    Email {
        /// Primary account address. When omitted, netsky prompts
        /// interactively from the known accounts.
        account: Option<String>,
    },
}

#[derive(Subcommand, Debug)]
pub enum ChannelCommand {
    /// Drain an agent's inbox to stdout as `<channel ...>` envelopes.
    /// Consumed envelopes move to `<agent>/delivered/`. Safe to retry;
    /// an empty inbox prints nothing and exits 0.
    Drain {
        /// Agent name: `agent0`, `agent42`, `agentinfinity`.
        #[arg(value_name = "AGENT")]
        agent: String,
    },
    /// Write a single envelope into the target agent's inbox.
    /// `from` defaults to `agent$AGENT_N`; pass `--from` to override.
    Send {
        #[arg(value_name = "TARGET")]
        target: String,
        #[arg(value_name = "TEXT")]
        text: String,
        /// Sender identity. Defaults to `agent${AGENT_N}` from the env.
        #[arg(long)]
        from: Option<String>,
    },
    /// Inspect envelopes moved to `<agent>/poison/` by drain's hostile-input
    /// guard. v0 exposes `--list` only; rehabilitation is manual (move the
    /// file back into `inbox/` by hand after review).
    Quarantine {
        /// Agent whose quarantine directory to inspect.
        #[arg(value_name = "AGENT")]
        agent: String,
        /// List quarantined envelope paths on stdout.
        #[arg(long)]
        list: bool,
    },
}

#[derive(Subcommand, Debug)]
pub enum HooksCommand {
    /// Install `.git/hooks/pre-push` as a symlink to the tracked canonical hook.
    /// Idempotent. With an existing drifted hook, prints a diff and exits
    /// cleanly unless `--force` is passed.
    Install {
        /// Overwrite an existing drifted `.git/hooks/pre-push`.
        #[arg(long)]
        force: bool,
    },
    /// Remove `.git/hooks/pre-push` (leaves the canonical hook intact).
    Uninstall,
    /// Print hook presence, drift state, and bypass-env 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
        );
    }
}