troll 0.3.2

The port manager that guards the bridge: permanent claims, expiring leases, and a live view of who listens where.
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
use std::{ffi::OsString, net::IpAddr, path::PathBuf};

use clap::{Args, Parser, Subcommand, ValueEnum, value_parser};
use rmcp::schemars::{self, JsonSchema};
use serde::Deserialize;
use time::{OffsetDateTime, SignedDuration};
use troll_core::{Role, Web, parse_duration};
use troll_probe::Kind;

use crate::commands::timestamp::parse_leased_at;

#[derive(Parser)]
#[command(
    name = "troll",
    version,
    disable_version_flag = true,
    disable_help_subcommand = true,
    about
)]
pub struct Cli {
    /// Print the version
    #[arg(short = 'V', long, exclusive = true)]
    pub version: bool,

    /// Emit machine-readable JSON
    #[arg(long, global = true)]
    pub json: bool,

    /// Control terminal colour
    #[arg(long = "color", global = true, value_enum)]
    pub color: Option<Color>,

    /// Disable ANSI color everywhere
    #[arg(
        long = "no-ansi-colors",
        visible_aliases = ["no-color", "no-colors"],
        global = true
    )]
    pub no_color: bool,

    /// Print guidance for language models
    #[arg(long)]
    pub llm_guide: bool,

    /// Print the full guide
    #[arg(long = "full", requires = "llm_guide")]
    pub full: bool,

    #[command(subcommand)]
    pub command: Option<Command>,
}

#[derive(Args)]
pub struct WithCommand {
    /// Lease a temporary stack for comma-separated component names
    #[arg(long, value_name = "COMPONENTS", value_delimiter = ',')]
    pub group: Option<Vec<String>>,
    /// Duration for the acquired lease (defaults to lease_default)
    #[arg(long = "for", value_parser = parse_duration, value_name = "DURATION")]
    pub duration: Option<SignedDuration>,
    /// Allocate from a named pool configured under [pools] in config.toml
    #[arg(long, value_name = "NAME")]
    pub pool: Option<String>,
    /// Periodically renew the lease while the command runs (bounded by lease_max)
    #[arg(long)]
    pub heartbeat: bool,
    #[arg(last = true, required = true, value_name = "COMMAND", num_args = 1..)]
    pub arguments: Vec<OsString>,
}

#[derive(Subcommand)]
pub enum Command {
    /// Configure the lease range and claim troll's service port
    Init {
        /// Use defaults without prompting and keep any existing configuration
        #[arg(long)]
        yes: bool,
        /// Write the Linux user service unit without enabling it
        #[arg(long, requires = "yes")]
        service: bool,
    },
    /// Install one integration
    Setup {
        #[command(subcommand)]
        integration: Integration,
    },
    /// Check the registry, configuration and live listeners
    Doctor,
    /// Register a permanent port
    Claim(ClaimArgs),
    /// Edit a permanent claim in place
    Edit {
        #[arg(value_parser = value_parser!(u16).range(1..))]
        port: u16,
        #[command(flatten)]
        changes: EditArgs,
    },
    /// Reserve a port for a limited time
    Lease {
        #[command(flatten)]
        args: LeaseArgs,
        /// Lease one port per comma-separated component
        #[arg(long, value_name = "COMPONENTS", value_delimiter = ',')]
        group: Option<Vec<String>>,
    },
    /// Edit a lease in place
    LeaseEdit {
        #[arg(value_parser = value_parser!(u16).range(1..))]
        port: u16,
        /// Require this entry tag. If omitted, read the current tag and edit that version.
        #[arg(long)]
        tag: Option<String>,
        #[arg(long)]
        purpose: Option<String>,
        #[arg(long = "for",
            alias = "expires-in",
            value_parser = parse_duration,
            value_name = "DURATION")]
        duration: Option<SignedDuration>,
    },
    /// Renew a lease from the current time
    Renew {
        #[command(flatten)]
        target: LeaseTargetArgs,
        #[arg(long = "for", value_parser = parse_duration, value_name = "DURATION")]
        duration: Option<SignedDuration>,
    },
    /// Remove a permanent claim or a lease
    Release {
        #[command(flatten)]
        target: ReleaseTargetArgs,
        /// Release a service even if other projects depend on it
        #[arg(long, conflicts_with = "group")]
        force_shared: bool,
    },
    /// Inspect or restore apps and ports removed within the last 30 days
    History {
        #[command(subcommand)]
        action: Option<HistoryCommand>,
    },
    /// Manage red zones that exclude ports from new allocations
    Zone {
        #[command(subcommand)]
        action: ZoneCommand,
    },
    /// Reserve and manage a project's ports together
    App {
        #[command(subcommand)]
        action: AppCommand,
    },
    /// Print an app's component ports as environment assignments
    Env { app: String },
    /// Run a command with a leased port
    With {
        #[arg(long)]
        project: Option<String>,
        #[arg(long)]
        purpose: Option<String>,
        #[command(flatten)]
        command: WithCommand,
    },
    /// Check whether a port is listening, claimed or free
    Check {
        #[arg(value_parser = value_parser!(u16).range(1..))]
        port: u16,
    },
    /// Explain a port's registry state, listeners, red zones, and 30-day history
    Explain {
        #[arg(value_parser = value_parser!(u16).range(1..))]
        port: u16,
    },
    /// List the registry entries and live listeners
    List {
        #[arg(long, value_enum)]
        kind: Option<KindArg>,
        #[arg(long, value_enum)]
        role: Option<RoleArg>,
        /// Show divergence between registry entries and live listeners
        #[arg(long)]
        drift: bool,
    },
    /// Remove reclaimable leases
    Sweep {
        /// Report what would be removed
        #[arg(long)]
        dry_run: bool,
    },
    /// Preview or apply an import of legacy port claims
    ImportLegacy {
        dir: PathBuf,
        /// Preview the import (default)
        #[arg(long, conflicts_with = "apply")]
        dry_run: bool,
        /// Register unconflicted permanent candidates in one update
        #[arg(long)]
        apply: bool,
    },
    /// Serve the local HTTP API and run automatic sweeps
    Serve {
        /// Listening port (0 asks the operating system to choose)
        #[arg(long)]
        port: Option<u16>,
        /// Listening address (127.0.0.1 only)
        #[arg(long, default_value = "127.0.0.1", value_name = "ADDRESS")]
        bind: IpAddr,
    },
    /// Serve the Model Context Protocol over standard input and output
    #[command(after_help = "The MCP protocol is always JSON. --json has no effect.")]
    Mcp,
}

#[derive(Args)]
pub struct ClaimArgs {
    #[arg(value_parser = value_parser!(u16).range(1..))]
    pub port: u16,
    #[arg(long)]
    pub project: String,
    #[arg(long)]
    pub service: String,
    #[arg(long, value_name = "ADDRESS")]
    pub bind: Option<IpAddr>,
    #[arg(long, value_enum, default_value = "app")]
    pub role: RoleArg,
    #[arg(long)]
    pub container: Option<String>,
    #[arg(long, value_delimiter = ',')]
    pub used_by: Option<Vec<String>>,
    #[command(flatten)]
    pub web: WebArgs,
    /// Name this port's component within the project
    #[arg(long)]
    pub component: Option<String>,
}

#[derive(Args, Default)]
pub struct WebArgs {
    /// Local web path (such as /admin)
    #[arg(long, value_name = "PATH")]
    pub web: Option<String>,
    /// Scheme for the local web link
    #[arg(long, value_enum)]
    pub web_scheme: Option<WebScheme>,
}

impl WebArgs {
    pub(crate) fn apply(self, current: Option<&Web>) -> Option<Web> {
        if self.web.is_none() && self.web_scheme.is_none() {
            return None;
        }
        let mut web = current.cloned().unwrap_or_default();
        if let Some(path) = self.web {
            web.path = path;
        }
        if let Some(scheme) = self.web_scheme {
            web.scheme = match scheme {
                WebScheme::Http => "http",
                WebScheme::Https => "https",
            }
            .into();
        }
        Some(web)
    }
}

#[derive(Clone, Copy, Deserialize, JsonSchema, ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum WebScheme {
    Http,
    Https,
}

#[derive(Args)]
pub struct EditArgs {
    /// Require this entry tag. If omitted, read the current tag and edit that version.
    #[arg(long)]
    pub tag: Option<String>,
    #[arg(long)]
    pub service: Option<String>,
    #[arg(long, value_enum)]
    pub role: Option<RoleArg>,
    #[arg(long, value_name = "ADDRESS")]
    pub bind: Option<IpAddr>,
    #[arg(long, value_delimiter = ',')]
    pub used_by: Option<Vec<String>>,
    /// Remove all dependent projects from a service
    #[arg(long, conflicts_with = "used_by")]
    pub clear_used_by: bool,
    #[arg(long)]
    pub container: Option<String>,
    /// Clear the container name
    #[arg(long, conflicts_with = "container")]
    pub clear_container: bool,
    #[command(flatten)]
    pub web: WebArgs,
    /// Remove the web link
    #[arg(long, conflicts_with_all = ["web", "web_scheme"])]
    pub no_web: bool,
    #[arg(id = "new_component", long = "component", value_name = "NAME")]
    pub component: Option<String>,
    /// Remove the component label
    #[arg(long, conflicts_with = "new_component")]
    pub no_component: bool,
}

#[derive(Args)]
pub struct LeaseArgs {
    #[arg(long)]
    pub project: String,
    #[arg(long)]
    pub purpose: String,
    #[arg(long = "for", value_parser = parse_duration, value_name = "DURATION")]
    pub duration: Option<SignedDuration>,
    #[arg(long, value_parser = value_parser!(u32).range(1..))]
    pub pid: Option<u32>,
    #[arg(long, value_name = "ADDRESS")]
    pub bind: Option<IpAddr>,
    /// Allocate from a named pool configured under [pools] in config.toml
    #[arg(long, value_name = "NAME")]
    pub pool: Option<String>,
}

#[derive(Args)]
#[group(skip)]
pub struct LeaseTargetArgs {
    #[arg(required_unless_present = "group", value_parser = value_parser!(u16).range(1..))]
    pub port: Option<u16>,
    /// Target a lease group by its ID
    #[arg(long, conflicts_with = "port", value_name = "ID")]
    pub group: Option<String>,
    /// Target only the lease with this start time from your own lease reply
    #[arg(long, conflicts_with = "group", value_parser = parse_leased_at, value_name = "RFC 3339")]
    pub leased_at: Option<OffsetDateTime>,
}

#[derive(Args)]
pub struct ReleaseTargetArgs {
    #[command(flatten)]
    pub lease: LeaseTargetArgs,
    /// Release a permanent claim only if this entry tag still matches
    #[arg(long, conflicts_with_all = ["group", "leased_at"])]
    pub if_tag: Option<String>,
}

#[derive(Subcommand)]
pub enum HistoryCommand {
    /// List removed apps and ports kept from the last 30 days
    List,
    /// Show details for one history entry
    Show { id: String },
    /// Restore a removed app, claim, or lease back into the registry
    Restore { id: String },
}

#[derive(Subcommand)]
pub enum ZoneCommand {
    /// Add a red zone
    Add {
        label: String,
        #[arg(long, required = true, value_delimiter = ',', value_name = "PORTS")]
        ports: Vec<String>,
        #[arg(long)]
        reason: Option<String>,
        #[arg(long)]
        disabled: bool,
    },
    /// List zones and any allocation conflicts
    List,
    /// Enable a zone and report any allocation conflicts
    Enable { label: String },
    /// Disable a zone
    Disable { label: String },
    /// Edit the port list or reason for a zone
    Edit {
        label: String,
        #[arg(long, value_delimiter = ',', value_name = "PORTS")]
        ports: Option<Vec<String>>,
        #[arg(long)]
        reason: Option<String>,
        #[arg(long, conflicts_with = "reason")]
        no_reason: bool,
    },
    /// Remove a zone
    Remove {
        label: String,
        /// Require the current zone tag to match
        #[arg(long)]
        if_tag: Option<String>,
    },
}

#[derive(Subcommand)]
pub enum AppCommand {
    /// Reserve the ports of a new app
    Reserve(AppAllocationArgs),
    /// List apps and their ports
    List,
    /// Show an app and its ports
    Show { app: String },
    /// Add ports to an existing app
    Add(AppAllocationArgs),
    /// Release one component's port
    Remove {
        app: String,
        component: String,
        /// Release a service even if other projects depend on it
        #[arg(long)]
        force_shared: bool,
        /// Require the current component tag to match
        #[arg(long)]
        if_tag: Option<String>,
    },
    /// Edit a component's port in place
    Edit {
        app: String,
        component: String,
        #[command(flatten)]
        changes: EditArgs,
    },
    /// Release every port in an app
    Release {
        app: String,
        /// The app name, typed again to confirm release
        #[arg(long)]
        confirm: String,
        /// Require the current app tag to match
        #[arg(long)]
        if_tag: Option<String>,
    },
}

#[derive(Args)]
pub struct AppAllocationArgs {
    pub app: String,
    /// Comma-separated names, with :service for supporting services
    #[arg(long, required = true, value_delimiter = ',')]
    pub components: Vec<String>,
    /// Pin a component to a port (repeatable)
    #[arg(long = "port", value_name = "COMPONENT=PORT")]
    pub pins: Vec<String>,
    #[arg(long, value_name = "ADDRESS")]
    pub bind: Option<IpAddr>,
}

#[derive(Clone, Copy, ValueEnum)]
pub enum Color {
    Auto,
    Always,
    Never,
}

#[derive(Subcommand)]
pub enum Integration {
    /// Prepare the Claude Code plugin marketplace
    Claude {
        /// Replace files whose contents differ
        #[arg(long)]
        force: bool,
    },
    /// Prepare the Codex plugin marketplace
    Codex {
        /// Replace files whose contents differ
        #[arg(long)]
        force: bool,
    },
    /// Write the Linux systemd user unit
    Service {
        /// Replace an existing unit whose contents differ
        #[arg(long)]
        force: bool,
    },
}

#[derive(Clone, Copy, ValueEnum)]
pub enum RoleArg {
    App,
    Service,
}

impl From<RoleArg> for Role {
    fn from(role: RoleArg) -> Self {
        match role {
            RoleArg::App => Self::App,
            RoleArg::Service => Self::Service,
        }
    }
}

#[derive(Clone, Copy, ValueEnum)]
pub enum KindArg {
    Ours,
    System,
    ThirdParty,
}

impl From<KindArg> for Kind {
    fn from(kind: KindArg) -> Self {
        match kind {
            KindArg::Ours => Self::Ours,
            KindArg::System => Self::System,
            KindArg::ThirdParty => Self::ThirdParty,
        }
    }
}

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

    #[test]
    fn console_command_tree_parses_edits_and_app_component_pins() {
        Cli::command().debug_assert();
        let cli = Cli::try_parse_from([
            "troll",
            "edit",
            "8100",
            "--tag",
            "abc",
            "--clear-used-by",
            "--web",
            "/admin",
            "--web-scheme",
            "https",
            "--no-component",
        ])
        .unwrap();
        let Some(Command::Edit { port, changes }) = cli.command else {
            panic!("expected edit")
        };
        assert_eq!(port, 8100);
        assert_eq!(changes.tag.as_deref(), Some("abc"));
        assert!(changes.clear_used_by && changes.no_component);
        assert_eq!(changes.web.web.as_deref(), Some("/admin"));
        assert!(matches!(changes.web.web_scheme, Some(WebScheme::Https)));

        let cli =
            Cli::try_parse_from(["troll", "lease-edit", "20000", "--expires-in", "2h"]).unwrap();
        assert!(
            matches!(cli.command, Some(Command::LeaseEdit { duration: Some(duration), .. })
            if duration == SignedDuration::hours(2))
        );

        let cli = Cli::try_parse_from([
            "troll",
            "app",
            "reserve",
            "demo",
            "--components",
            "api,db:service",
            "--port",
            "api=8100",
            "--port",
            "db=8101",
        ])
        .unwrap();
        let Some(Command::App {
            action: AppCommand::Reserve(args),
        }) = cli.command
        else {
            panic!("expected app reserve")
        };
        assert_eq!(args.components, ["api", "db:service"]);
        assert_eq!(args.pins, ["api=8100", "db=8101"]);
    }

    #[test]
    fn console_command_tree_rejects_conflicting_or_missing_arguments() {
        for args in [
            &["edit", "8100", "--used-by", "demo", "--clear-used-by"][..],
            &["edit", "8100", "--no-web", "--web", "/"],
            &["edit", "8100", "--no-web", "--web-scheme", "http"],
            &[
                "app",
                "edit",
                "demo",
                "api",
                "--component",
                "ui",
                "--no-component",
            ],
            &["zone", "edit", "mine", "--reason", "new", "--no-reason"],
            &["zone", "add", "mine"],
            &["app", "release", "demo"],
            &["release"],
            &["renew", "8100", "--group", "g-123"],
            &[
                "renew",
                "--group",
                "g-123",
                "--leased-at",
                "2026-01-01T00:00:00Z",
            ],
            &["release", "--group", "g-123", "--force-shared"],
            &["lease-edit", "0"],
            &["lease-edit", "8100", "--for", "0h"],
        ] {
            let result = Cli::try_parse_from(std::iter::once("troll").chain(args.iter().copied()));
            assert_eq!(
                result.err().expect("usage error").exit_code(),
                2,
                "{args:?}"
            );
        }
    }

    #[test]
    fn group_commands_parse_without_a_port() {
        let cli = Cli::try_parse_from([
            "troll",
            "lease",
            "--project",
            "demo",
            "--purpose",
            "preview",
            "--group",
            "api,db",
        ])
        .unwrap();
        let Some(Command::Lease {
            group: Some(components),
            ..
        }) = cli.command
        else {
            panic!("expected grouped lease")
        };
        assert_eq!(components, ["api", "db"]);

        let cli =
            Cli::try_parse_from(["troll", "renew", "--group", "g-123", "--for", "2h"]).unwrap();
        let Some(Command::Renew { target, duration }) = cli.command else {
            panic!("expected renew")
        };
        assert_eq!(target.group.as_deref(), Some("g-123"));
        assert!(target.port.is_none());
        assert_eq!(duration, Some(SignedDuration::hours(2)));

        let cli = Cli::try_parse_from(["troll", "release", "--group", "g-123"]).unwrap();
        let Some(Command::Release { target, .. }) = cli.command else {
            panic!("expected release")
        };
        assert_eq!(target.lease.group.as_deref(), Some("g-123"));
        assert!(target.lease.port.is_none());
    }
}