heddle-cli-args 0.28.6

Heddle's command-line argument surface.
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
// SPDX-License-Identifier: Apache-2.0
//! Hosted-client command arguments.

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

const DEFAULT_CLAIM_TIMEOUT: &str = "15m";
pub const DEFAULT_CLAIM_WEB_ORIGIN: &str = "https://app.heddle.sh";

/// Arguments for `heddle promote`.
#[derive(Args, Clone, Debug)]
#[command(after_help = "\
Promote moves a personal hosted spool to the shared root namespace:

  spool/<your-handle>/<name>  →  spool/<name>

The server requires the root slug to be free, a claimed/verified account, and
an owner grant on the personal spool. Denials print the recovery step.

Examples:
  heddle promote spool/willow-ibis-8e7264/notes
  heddle promote willow-ibis-8e7264/notes --server api.preview.heddle.sh
  heddle promote https://api.preview.heddle.sh/willow-ibis-8e7264/notes
")]
pub struct PromoteArgs {
    /// Personal spool to lift to root (`spool/<handle>/<name>`, `<handle>/<name>`, or a hosted URL).
    #[arg(value_name = "PATH")]
    pub path: String,

    #[command(flatten)]
    pub server: super::HostedServerArgs,
}

/// Offer the current agent-rooted account for a human to claim.
#[derive(Args, Clone, Debug)]
pub struct ClaimArgs {
    /// Hosted Heddle server. Omit to use the configured default
    /// (`api.heddle.sh` when none is stored).
    #[arg(long)]
    pub server: Option<String>,

    /// HTTPS origin used to build the human claim link. Highest precedence;
    /// must be https (scheme, host, optional port). When omitted, a
    /// server-advertised origin is used only if it shares the hosted
    /// server's registrable domain. `https://app.heddle.sh` is the fallback
    /// only for `api.heddle.sh`.
    #[arg(long, value_name = "ORIGIN")]
    pub web_origin: Option<String>,

    /// How long to keep the claim listener resident (`s`, `m`, `h`, or `d`).
    #[arg(
        long,
        default_value = DEFAULT_CLAIM_TIMEOUT,
        value_name = "DURATION",
        value_parser = parse_claim_timeout
    )]
    pub timeout: std::time::Duration,
}

fn parse_claim_timeout(value: &str) -> Result<std::time::Duration, String> {
    let value = value.trim();
    let (amount, multiplier) = match value.as_bytes().last().copied() {
        Some(b's') => (&value[..value.len() - 1], 1),
        Some(b'm') => (&value[..value.len() - 1], 60),
        Some(b'h') => (&value[..value.len() - 1], 60 * 60),
        Some(b'd') => (&value[..value.len() - 1], 24 * 60 * 60),
        Some(byte) if byte.is_ascii_digit() => (value, 1),
        _ => {
            return Err("expected a positive duration such as 30s, 15m, 2h, or 1d".to_string());
        }
    };
    let amount = amount
        .parse::<u64>()
        .map_err(|_| "claim timeout must be a positive whole number".to_string())?;
    let seconds = amount
        .checked_mul(multiplier)
        .ok_or_else(|| "claim timeout is too large".to_string())?;
    if seconds == 0 {
        return Err("claim timeout must be greater than zero".to_string());
    }
    Ok(std::time::Duration::from_secs(seconds))
}

/// Preset operation ceilings for `heddle auth derive-agent`.
///
/// Each variant expands to a curated set of safe agent operations. `reviewer`
/// and `ci-landing` are strict subsets of the safe ceiling; `contributor` is
/// the full safe ceiling (the named form of the default `--allow`-less
/// derivation). `--scope`/`--allow` stay usable alongside a template and, when
/// combined, may only *narrow* it (they intersect the template's set).
#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
pub enum AgentTemplateArg {
    /// Native read operations, including spool, thread, content, and review views.
    Reviewer,
    /// Reviewer operations plus thread, content, context, discussion, review,
    /// spool creation, and CI evidence writes.
    Contributor,
    /// Reviewer operations plus LandThread and PublishContent.
    #[value(name = "ci-landing")]
    CiLanding,
}

#[derive(Subcommand, Clone, Debug)]
pub enum AuthCommands {
    /// Authenticate with a Heddle server.
    ///
    /// Reuses a valid stored credential, remints a registered node-key
    /// account, consumes `--invite` to create one, or opens the browser
    /// on a TTY. Non-interactive sessions without an account fail closed.
    Login {
        /// Heddle server address. Omit to use the configured default
        /// (`api.heddle.sh` when none is stored).
        #[arg(long)]
        server: Option<String>,

        /// Open the authorization URL in the system browser.
        #[arg(long)]
        open_browser: bool,

        /// Host of the web page where you approve this login, such as
        /// `pr-17-tapestry.example.workers.dev`. Not the API server: that is
        /// `--server`. Accepts a bare host or an `https://` origin; no port,
        /// path, or wildcard. Used only by browser pairing. Omit to use the
        /// server's default web host.
        #[arg(
            long,
            value_name = "WEB_HOST",
            value_parser = config::web_origin::PairingWebOrigin::parse,
            conflicts_with_all = ["credential", "invite"],
        )]
        host: Option<config::web_origin::PairingWebOrigin>,

        /// Invite consumed only when this machine has no hosted account yet.
        #[arg(long, conflicts_with = "credential")]
        invite: Option<String>,

        /// Install a verified `.hcred` credential file without a browser.
        /// The server is taken from the file.
        #[arg(long, value_name = "HCRED_PATH", conflicts_with_all = ["server", "open_browser", "invite"])]
        credential: Option<std::path::PathBuf>,
    },

    /// Remove stored credentials for a server
    Logout {
        /// Heddle server address
        #[arg(long)]
        server: Option<String>,
    },

    /// Show current authentication status
    Status {
        /// Heddle server address
        #[arg(long)]
        server: Option<String>,
    },

    /// Create or list signup invites owned by the signed-in account.
    ///
    /// Signup-only: this mints an account-creation code. It does not grant
    /// another principal access to a spool. Use `heddle grant` to add a
    /// collaborator.
    #[command(args_conflicts_with_subcommands = true)]
    #[command(after_help = "\
Signup-only. `heddle auth invite` creates an account-creation code.
It does not grant spool access. Add a collaborator with:

  heddle grant create --spool <path|url> --principal <handle> --role writer
")]
    Invite {
        /// Bind the new invite to an email address.
        #[arg(long)]
        email: Option<String>,

        /// Heddle server address. Omit to use the configured default
        /// (`api.heddle.sh` when none is stored).
        #[arg(long, global = true)]
        server: Option<String>,

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

    /// Inspect or explicitly replace the deployment descriptor root pin
    Trust {
        #[command(subcommand)]
        command: AuthTrustCommands,
    },

    /// Derive a scoped, short-lived agent token offline.
    /// Advanced: not a first-screen noun.
    DeriveAgent {
        /// Server whose stored credential is the parent.
        #[arg(long)]
        server: String,

        /// Delegation name recorded in the Biscuit chain.
        #[arg(long)]
        agent_id: Option<String>,

        /// Child lifetime in seconds (clamped by the parent expiry).
        #[arg(long = "ttl", default_value_t = 3600)]
        ttl_secs: u64,

        /// Resource scope (`spool:name`, `spool:handle/name`, or a bare spool path).
        #[arg(long = "scope")]
        scopes: Vec<String>,

        /// Narrow the template operation set (repeatable, using native names such as `RecordEvidence`).
        #[arg(long = "allow")]
        allowed_operations: Vec<String>,

        /// Preset operation ceiling: `reviewer` for reads, `contributor` for
        /// native writes, or `ci-landing` for LandThread and PublishContent.
        /// A combined `--allow` may only narrow the template.
        #[arg(long, value_enum)]
        template: Option<AgentTemplateArg>,

        /// Derive a CI-verdict runner: `ci-verdict:write` on the required
        /// `spool:` scope(s), without source writes.
        #[arg(long, conflicts_with_all = ["template", "allowed_operations"])]
        runner: bool,

        /// Write a single self-verifying `<name>.hcred` credential file to this
        /// path instead of installing the child into the keystore.
        #[arg(long, value_name = "HCRED_PATH")]
        out: Option<std::path::PathBuf>,
    },

    /// Create a service token for CI/scripts with explicit native capabilities.
    /// Advanced: not a first-screen noun.
    CreateServiceToken {
        /// Display name for the service account (e.g. "github-ci-main")
        name: String,
        /// Native delegation scope, e.g. "spool:heddle/platform read write"
        #[arg(long)]
        scope: String,
        /// Heddle server address
        #[arg(long)]
        server: Option<String>,
        /// Write the `.hcred` credential file to this path
        /// (default: ~/.heddle/service-tokens/<name>.hcred)
        #[arg(long, value_name = "HCRED_PATH")]
        out: Option<std::path::PathBuf>,
    },
}

#[derive(Subcommand, Clone, Debug)]
pub enum AuthInviteCommands {
    /// List signup invites owned by the signed-in account.
    List,
}

/// Hosted role granted on a spool.
///
/// Native Spool grants use the three explicit resource roles.
#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
pub enum GrantRoleArg {
    Reader,
    Writer,
    Administrator,
}

impl GrantRoleArg {
    /// Native v2 Spool role token.
    pub fn as_resource_role_name(self) -> &'static str {
        match self {
            Self::Reader => "reader",
            Self::Writer => "writer",
            Self::Administrator => "administrator",
        }
    }
}

/// Grant another principal access to a hosted spool.
///
/// Separate from `heddle auth invite`, which is signup-only.
#[derive(Subcommand, Clone, Debug)]
pub enum GrantCommands {
    /// Grant a principal a role on a hosted spool.
    #[command(after_help = "\
Adds a collaborator to an existing hosted spool. This is not a signup
invite — `heddle auth invite` only creates an account-creation code.

Roles: reader, writer, administrator. A delegate can grant only authority
they currently hold; owner-only cryptographic powers are separate.

Examples:
  heddle grant create --spool spool/willow-ibis-8e7264/notes --principal alice --role writer
  heddle grant create --spool https://api.preview.heddle.sh/notes --principal alice --role reader
")]
    Create(GrantCreateArgs),

    /// List grants on a hosted spool.
    #[command(after_help = "\
`--spool` is the same bare path create and delete use
(`spool/<handle>/<name>`, `<handle>/<name>`, or a hosted URL).
Do not prefix `repo:`.

Examples:
  heddle grant list --spool spool/willow-ibis-8e7264/notes
  heddle grant list --spool notes --server api.preview.heddle.sh
")]
    List(GrantListArgs),

    /// Remove a grant by its stable record ID shown by `heddle grant list`.
    #[command(after_help = "\
The acting account or delegate must currently have grant administration on
this Spool. A grant's role does not change the authority needed to remove it.

Examples:
  heddle grant delete <grant-id> --spool spool/willow-ibis-8e7264/notes
")]
    Delete(GrantDeleteArgs),
}

/// Arguments for `heddle grant create`.
#[derive(Args, Clone, Debug)]
pub struct GrantCreateArgs {
    /// Spool to grant on (`spool/<handle>/<name>`, `<handle>/<name>`, or a hosted URL).
    #[arg(long, value_name = "PATH|URL")]
    pub spool: String,

    /// Principal to grant (handle or account).
    #[arg(long, value_name = "HANDLE|ACCOUNT")]
    pub principal: String,

    /// Role to grant.
    #[arg(long, value_enum)]
    pub role: GrantRoleArg,

    #[command(flatten)]
    pub server: super::HostedServerArgs,
}

/// Arguments for `heddle grant list`.
#[derive(Args, Clone, Debug)]
pub struct GrantListArgs {
    /// Spool whose grants to list (`spool/<handle>/<name>`, `<handle>/<name>`, or a hosted URL).
    #[arg(long, value_name = "PATH|URL")]
    pub spool: String,

    #[command(flatten)]
    pub server: super::HostedServerArgs,
}

/// Arguments for `heddle grant delete`.
#[derive(Args, Clone, Debug)]
pub struct GrantDeleteArgs {
    /// Grant record ID shown as `GRANT_ID` by `heddle grant list`.
    #[arg(value_name = "GRANT_ID")]
    pub id: String,

    /// Spool the grant is on (`spool/<handle>/<name>`, `<handle>/<name>`, or a hosted URL).
    #[arg(long, value_name = "PATH|URL")]
    pub spool: String,

    #[command(flatten)]
    pub server: super::HostedServerArgs,
}

#[derive(Subcommand, Clone, Debug)]
pub enum AuthTrustCommands {
    /// Show the descriptor root pin controlling a server connection
    Show(AuthTrustShowArgs),
    /// Atomically replace an automatic descriptor root pin
    Replace(AuthTrustReplaceArgs),
}

#[derive(Args, Clone, Debug)]
pub struct AuthTrustShowArgs {
    /// Heddle server authority
    #[arg(long)]
    pub server: String,
}

#[derive(Args, Clone, Debug)]
pub struct AuthTrustReplaceArgs {
    /// Heddle server authority
    #[arg(long)]
    pub server: String,
    /// Current descriptor root public key required for compare-and-swap
    #[arg(long, value_name = "64_HEX")]
    pub expect_current_public_key: String,
    /// New descriptor root key id confirmed out of band
    #[arg(long)]
    pub key_id: String,
    /// New descriptor root public key confirmed out of band
    #[arg(long, value_name = "64_HEX")]
    pub public_key: String,
}

#[cfg(test)]
mod tests {
    use clap::Parser;

    use crate::cli::{
        AuthCommands, AuthInviteCommands, AuthTrustCommands, Cli, Commands, GrantCommands,
        GrantRoleArg,
    };

    #[test]
    fn trust_replace_parses_compare_and_swap_inputs() {
        let old_key = "11".repeat(32);
        let new_key = "22".repeat(32);
        let cli = Cli::try_parse_from([
            "heddle",
            "auth",
            "trust",
            "replace",
            "--server",
            "api.example",
            "--expect-current-public-key",
            &old_key,
            "--key-id",
            "next-key",
            "--public-key",
            &new_key,
        ])
        .expect("trust replacement parses");

        let Commands::Auth {
            command:
                AuthCommands::Trust {
                    command: AuthTrustCommands::Replace(args),
                },
        } = cli.command
        else {
            panic!("expected auth trust replace");
        };
        assert_eq!(args.server, "api.example");
        assert_eq!(args.expect_current_public_key, old_key);
        assert_eq!(args.key_id, "next-key");
        assert_eq!(args.public_key, new_key);
    }

    #[test]
    fn login_parses_credential_path() {
        let cli = Cli::try_parse_from([
            "heddle",
            "auth",
            "login",
            "--credential",
            "/run/secrets/agent.hcred",
        ])
        .expect("credential login flag parses");

        let Commands::Auth {
            command:
                AuthCommands::Login {
                    server,
                    credential,
                    open_browser,
                    host,
                    invite,
                },
        } = cli.command
        else {
            panic!("expected auth login");
        };
        assert_eq!(host, None);
        assert_eq!(server, None, "server comes from the credential file");
        assert_eq!(
            credential.as_deref(),
            Some(std::path::Path::new("/run/secrets/agent.hcred"))
        );
        assert!(!open_browser);
        assert_eq!(invite, None);
    }

    #[test]
    fn login_credential_conflicts_with_browser_flags() {
        for conflicting in [
            vec![
                "--credential",
                "/run/secrets/agent.hcred",
                "--server",
                "api.heddle.sh",
            ],
            vec!["--credential", "/run/secrets/agent.hcred", "--open-browser"],
            vec![
                "--credential",
                "/run/secrets/agent.hcred",
                "--invite",
                "code",
            ],
        ] {
            let mut args = vec!["heddle", "auth", "login"];
            args.extend(conflicting);
            assert!(
                Cli::try_parse_from(args).is_err(),
                "--credential must not combine with the browser-login flags"
            );
        }
    }

    #[test]
    fn interactive_login_needs_no_flags() {
        Cli::try_parse_from(["heddle", "auth", "login"])
            .expect("interactive login may resolve the configured default server");
    }

    #[test]
    fn claim_is_one_top_level_resident_command() {
        let cli = Cli::try_parse_from([
            "heddle",
            "claim",
            "--server",
            "weft.example",
            "--web-origin",
            "https://heddle.example",
            "--timeout",
            "30m",
        ])
        .expect("claim flags parse");
        let Commands::Claim(args) = cli.command else {
            panic!("expected top-level claim");
        };
        assert_eq!(args.server.as_deref(), Some("weft.example"));
        assert_eq!(args.web_origin.as_deref(), Some("https://heddle.example"));
        assert_eq!(args.timeout, std::time::Duration::from_secs(30 * 60));
        assert!(Cli::try_parse_from(["heddle", "claim", "--timeout", "0s"]).is_err());
    }

    #[test]
    fn promote_parses_path_and_optional_server() {
        let cli = Cli::try_parse_from([
            "heddle",
            "promote",
            "spool/willow-ibis-8e7264/notes",
            "--server",
            "api.preview.heddle.sh",
        ])
        .expect("promote flags parse");
        let Commands::Promote(args) = cli.command else {
            panic!("expected top-level promote");
        };
        assert_eq!(args.path, "spool/willow-ibis-8e7264/notes");
        assert_eq!(args.server.server.as_deref(), Some("api.preview.heddle.sh"));
        assert!(Cli::try_parse_from(["heddle", "promote"]).is_err());
    }

    #[test]
    fn login_parses_an_optional_invite() {
        let cli = Cli::try_parse_from([
            "heddle",
            "auth",
            "login",
            "--server",
            "api.heddle.test",
            "--invite",
            "invite-secret",
        ])
        .expect("auth login --invite parses");
        let Commands::Auth {
            command:
                AuthCommands::Login {
                    server,
                    invite,
                    credential,
                    open_browser,
                    host,
                },
        } = cli.command
        else {
            panic!("expected auth login");
        };
        assert_eq!(server.as_deref(), Some("api.heddle.test"));
        assert_eq!(invite.as_deref(), Some("invite-secret"));
        assert_eq!(credential, None);
        assert!(!open_browser);
        assert_eq!(host, None);
    }

    #[test]
    fn login_host_is_the_web_approval_host_distinct_from_server() {
        let cli = Cli::try_parse_from([
            "heddle",
            "auth",
            "login",
            "--server",
            "api.staging.heddle.test",
            "--host",
            "PR-17-Tapestry.zephyr-forge.workers.dev",
            "--open-browser",
        ])
        .expect("auth login --host parses");
        let Commands::Auth {
            command: AuthCommands::Login { server, host, .. },
        } = cli.command
        else {
            panic!("expected auth login");
        };
        assert_eq!(server.as_deref(), Some("api.staging.heddle.test"));
        assert_eq!(
            host.as_ref().map(|origin| origin.as_str()),
            Some("https://pr-17-tapestry.zephyr-forge.workers.dev"),
            "--host normalises to the canonical https origin"
        );
    }

    #[test]
    fn login_host_rejects_non_origin_values_locally() {
        for invalid in [
            "http://preview.example.dev",
            "https://preview.example.dev:8443",
            "https://preview.example.dev/auth",
            "https://user@preview.example.dev",
            "https://*.example.dev",
            "localhost",
            "",
        ] {
            let error = Cli::try_parse_from(["heddle", "auth", "login", "--host", invalid])
                .err()
                .unwrap_or_else(|| panic!("--host {invalid:?} must be rejected"));
            assert_eq!(
                error.kind(),
                clap::error::ErrorKind::ValueValidation,
                "{invalid:?}: {error}"
            );
        }
    }

    #[test]
    fn login_host_conflicts_with_paths_that_never_pair() {
        for conflicting in [
            vec!["--credential", "/run/secrets/agent.hcred"],
            vec!["--invite", "code"],
        ] {
            let mut args = vec!["heddle", "auth", "login", "--host", "preview.example.dev"];
            args.extend(conflicting);
            let error = Cli::try_parse_from(args)
                .err()
                .unwrap_or_else(|| panic!("--host must not combine with credential or invite"));
            assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict);
        }
    }

    #[test]
    fn signup_invite_create_and_list_parse() {
        let create = Cli::try_parse_from([
            "heddle",
            "auth",
            "invite",
            "--server",
            "api.heddle.test",
            "--email",
            "alice@example.com",
        ])
        .expect("auth invite create flags parse");
        let Commands::Auth {
            command:
                AuthCommands::Invite {
                    email,
                    server,
                    command,
                },
        } = create.command
        else {
            panic!("expected auth invite");
        };
        assert_eq!(email.as_deref(), Some("alice@example.com"));
        assert_eq!(server.as_deref(), Some("api.heddle.test"));
        assert!(command.is_none());

        let list = Cli::try_parse_from([
            "heddle",
            "auth",
            "invite",
            "list",
            "--server",
            "api.heddle.test",
        ])
        .expect("auth invite list flags parse");
        let Commands::Auth {
            command:
                AuthCommands::Invite {
                    email,
                    server,
                    command: Some(AuthInviteCommands::List),
                },
        } = list.command
        else {
            panic!("expected auth invite list");
        };
        assert_eq!(email, None);
        assert_eq!(server.as_deref(), Some("api.heddle.test"));

        assert!(
            Cli::try_parse_from([
                "heddle",
                "auth",
                "invite",
                "--email",
                "alice@example.com",
                "list",
            ])
            .is_err(),
            "create-only --email must not be accepted by list"
        );
    }

    #[test]
    fn derive_agent_parses_repeatable_scopes_and_operation_narrowing() {
        let cli = Cli::try_parse_from([
            "heddle",
            "auth",
            "derive-agent",
            "--server",
            "api.heddle.test",
            "--ttl",
            "900",
            "--scope",
            "spool:acme/api",
            "--scope",
            "acme/tools",
            "--allow",
            "Push",
            "--allow",
            "GetState",
        ])
        .expect("derive-agent flags parse");

        let Commands::Auth {
            command:
                AuthCommands::DeriveAgent {
                    server,
                    ttl_secs,
                    scopes,
                    allowed_operations,
                    ..
                },
        } = cli.command
        else {
            panic!("expected auth derive-agent");
        };
        assert_eq!(server, "api.heddle.test");
        assert_eq!(ttl_secs, 900);
        assert_eq!(scopes, ["spool:acme/api", "acme/tools"]);
        assert_eq!(allowed_operations, ["Push", "GetState"]);

        assert!(
            Cli::try_parse_from([
                "heddle",
                "auth",
                "derive-agent",
                "--server",
                "api.heddle.test",
                "--stdout",
            ])
            .is_err(),
            "token-only child export is unsafe because it cannot carry its proof key"
        );
    }

    #[test]
    fn derive_agent_parses_the_runner_persona_and_rejects_wider_overrides() {
        let cli = Cli::try_parse_from([
            "heddle",
            "auth",
            "derive-agent",
            "--server",
            "api.heddle.test",
            "--runner",
            "--scope",
            "spool:acme/api",
        ])
        .expect("runner flags parse");

        let Commands::Auth {
            command: AuthCommands::DeriveAgent { runner, scopes, .. },
        } = cli.command
        else {
            panic!("expected auth derive-agent");
        };
        assert!(runner);
        assert_eq!(scopes, ["spool:acme/api"]);

        for conflicting in [["--allow", "Push"], ["--template", "ci-landing"]] {
            assert!(
                Cli::try_parse_from([
                    "heddle",
                    "auth",
                    "derive-agent",
                    "--server",
                    "api.heddle.test",
                    "--runner",
                    conflicting[0],
                    conflicting[1],
                ])
                .is_err(),
                "runner persona must reject authority-changing overrides"
            );
        }
    }

    #[test]
    fn grant_create_parses_spool_principal_and_writer_role() {
        let cli = Cli::try_parse_from([
            "heddle",
            "grant",
            "create",
            "--spool",
            "spool/willow-ibis-8e7264/notes",
            "--principal",
            "alice",
            "--role",
            "writer",
            "--server",
            "api.preview.heddle.sh",
        ])
        .expect("grant create flags parse");
        let Commands::Grant {
            command: GrantCommands::Create(args),
        } = cli.command
        else {
            panic!("expected grant create");
        };
        assert_eq!(args.spool, "spool/willow-ibis-8e7264/notes");
        assert_eq!(args.principal, "alice");
        assert_eq!(args.role, GrantRoleArg::Writer);
        assert_eq!(args.role.as_resource_role_name(), "writer");
        assert_eq!(args.server.server.as_deref(), Some("api.preview.heddle.sh"));
    }

    #[test]
    fn grant_list_and_delete_parse() {
        let list = Cli::try_parse_from([
            "heddle",
            "grant",
            "list",
            "--spool",
            "notes",
            "--server",
            "api.preview.heddle.sh",
        ])
        .expect("grant list flags parse");
        let Commands::Grant {
            command: GrantCommands::List(args),
        } = list.command
        else {
            panic!("expected grant list");
        };
        assert_eq!(args.spool, "notes");
        assert_eq!(args.server.server.as_deref(), Some("api.preview.heddle.sh"));

        let delete = Cli::try_parse_from([
            "heddle",
            "grant",
            "delete",
            "alice",
            "--spool",
            "spool/willow-ibis-8e7264/notes",
        ])
        .expect("grant delete flags parse");
        let Commands::Grant {
            command: GrantCommands::Delete(args),
        } = delete.command
        else {
            panic!("expected grant delete");
        };
        assert_eq!(args.id, "alice");
        assert_eq!(args.spool, "spool/willow-ibis-8e7264/notes");
        assert!(Cli::try_parse_from(["heddle", "grant", "delete", "alice"]).is_err());
    }
}