auths-cli 0.1.16

Command-line interface for Auths decentralized identity system
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
//! One-command guided setup wizard for Auths.
//!
//! Applies Gather → Execute → Display for each profile, delegating all
//! business logic to `auths-sdk`.

mod display;
mod gather;
mod guided;
mod helpers;
mod prompts;

use anyhow::{Result, anyhow};
use clap::{Args, ValueEnum};
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use auths_sdk::domains::identity::service::initialize;
use auths_sdk::domains::identity::types::IdentityConfig;
use auths_sdk::domains::identity::types::InitializeResult;
use auths_sdk::domains::signing::types::GitSigningScope;
use auths_sdk::keychain::KeyStorage;
use auths_sdk::ports::git_config::GitConfigProvider;
use auths_sdk::signing::PrefilledPassphraseProvider;
use auths_sdk::signing::StorageSigner;
use auths_sdk::workflows::roots::RootPinOutcome;

use crate::adapters::git_config::SystemGitConfigProvider;
use crate::config::CliConfig;
use crate::factories::storage::build_auths_context;
use crate::ux::format::Output;

use display::{
    display_agent_dry_run, display_agent_result, display_ci_result, display_developer_result,
};
use gather::{
    ensure_registry_dir, gather_agent_config, gather_ci_config, gather_developer_config,
    submit_registration,
};
use guided::GuidedSetup;
use helpers::{git_remote_is_github, offer_shell_completions};
use prompts::{prompt_platform_verification, prompt_profile};

const DEFAULT_KEY_ALIAS: &str = "main";

/// Setup profile for identity initialization.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum InitProfile {
    /// Full local development setup with keychain, identity, device linking, and git signing
    Developer,
    /// Temporary signing identity for CI/CD pipelines
    Ci,
    /// Restricted signing identity for AI agents
    Agent,
}

/// Where `auths init` writes git signing configuration.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum GitScopeArg {
    /// This repository only (`git config --local`).
    Local,
    /// Every repository on this machine (`git config --global`).
    Global,
    /// Do not touch git configuration at all.
    Skip,
}

impl GitScopeArg {
    /// Resolve to the SDK scope, reading the working directory for `Local`.
    pub(crate) fn resolve(self) -> Result<GitSigningScope> {
        Ok(match self {
            Self::Local => GitSigningScope::Local {
                repo_path: std::env::current_dir()
                    .map_err(|e| anyhow!("Failed to determine current working directory: {e}"))?,
            },
            Self::Global => GitSigningScope::Global,
            Self::Skip => GitSigningScope::Skip,
        })
    }
}

impl std::fmt::Display for InitProfile {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            InitProfile::Developer => write!(f, "developer"),
            InitProfile::Ci => write!(f, "ci"),
            InitProfile::Agent => write!(f, "agent"),
        }
    }
}

/// Initializes Auths identity with a guided setup wizard.
///
/// Supports three profiles (developer, ci, agent) covering the most common
/// deployment scenarios. Interactive by default on TTY; pass `--non-interactive`
/// for scripted or CI use, or `--interactive` to force prompts.
///
/// Usage:
/// ```ignore
/// // auths init
/// // auths init --profile developer --non-interactive
/// // auths init --interactive --profile developer
/// ```
#[derive(Args, Debug, Clone)]
#[command(
    name = "init",
    about = "Create your signing identity and configure Git",
    after_help = "Examples:
  auths init                              # Interactive setup wizard
  auths init --profile developer          # Developer profile with prompts
  auths init --profile ci --non-interactive # Automated CI setup

Profiles:
  developer — Local setup: keychain, Git signing, platform identity
  ci        — Temporary signing identity for CI/CD runners
  agent     — Restricted signing identity for AI agents

Related:
  auths status  — Check setup completion
  auths doctor  — Run health checks"
)]
pub struct InitCommand {
    /// Force interactive prompts (errors if not a TTY)
    #[clap(long, conflicts_with = "non_interactive")]
    pub interactive: bool,

    /// Skip interactive prompts and use sensible defaults
    #[clap(long, conflicts_with = "interactive")]
    pub non_interactive: bool,

    /// Preset profile: developer, ci, or agent
    #[clap(long, value_enum)]
    pub profile: Option<InitProfile>,

    /// Key alias for the identity key (default: main)
    #[clap(long, default_value = DEFAULT_KEY_ALIAS)]
    pub key_alias: String,

    /// Force overwrite if identity already exists
    #[clap(long)]
    pub force: bool,

    /// Confirm replacing an existing root identity when running non-interactively. Required with
    /// `--force` over an existing identity when there is no TTY to confirm at.
    #[clap(long)]
    pub confirm_replace: bool,

    /// Preview agent configuration without creating files or identities
    #[clap(long)]
    pub dry_run: bool,

    /// Registry URL for identity registration. No default: auths needs no
    /// registry, and registration is opt-in via `--register`.
    #[clap(long, env = "AUTHS_REGISTRY_URL")]
    pub registry: Option<String>,

    /// Register identity with the Auths Registry after creation
    #[clap(long)]
    pub register: bool,

    /// Link your GitHub account and upload your SSH signing key, so your commits
    /// show as Verified on github.com.
    ///
    /// Defaults to on when this repo has a GitHub remote and there is a TTY to
    /// confirm at. Unrelated to `--register`, which publishes to the Auths
    /// Registry.
    #[clap(long)]
    pub github: bool,

    /// Skip linking GitHub, even when this repo has a GitHub remote.
    #[clap(long = "no-github", conflicts_with = "github")]
    pub no_github: bool,

    /// Where to write git signing config: local (this repo), global (every repo
    /// on this machine), or skip.
    ///
    /// Interactive runs ask. Non-interactive runs default to `local` — a scripted
    /// or CI init should not silently rewrite your `~/.gitconfig`.
    #[clap(long, value_enum)]
    pub git_scope: Option<GitScopeArg>,

    /// Scaffold a GitHub Actions workflow using the auths attest-action
    #[clap(long)]
    pub github_action: bool,

    /// Number of device slots for a multi-key KEL (default 1).
    ///
    /// Values > 1 require `--signing-threshold` and `--rotation-threshold`.
    /// Multi-device init today runs a single-device inception; add further
    /// devices with `auths device pair` (each is a delegated identity under
    /// the root). The full atomic multi-device inception path is wired later.
    #[clap(long, default_value_t = 1)]
    pub device_count: u8,

    /// Signing threshold: scalar integer (e.g. `"2"`) or fraction list
    /// (e.g. `"1/2,1/2,1/2"`). Required when `--device-count > 1`.
    #[clap(long)]
    pub signing_threshold: Option<String>,

    /// Rotation (next) threshold, same format as `--signing-threshold`.
    #[clap(long)]
    pub rotation_threshold: Option<String>,
}

/// Parse a threshold argument from the CLI.
///
/// Accepts either a plain integer (`"2"`, `"a"` hex) for `Threshold::Simple`
/// or a comma-separated fraction list (`"1/2,1/2,1/2"`) for
/// `Threshold::Weighted`. Rejects mixed shapes (`"2,3"` with no `/`) with
/// a clear error.
pub fn parse_threshold_cli(
    s: &str,
    key_count: usize,
) -> Result<auths_keri::Threshold, anyhow::Error> {
    let trimmed = s.trim();
    if trimmed.is_empty() {
        return Err(anyhow!("threshold value is empty"));
    }

    if trimmed.contains(',') || trimmed.contains('/') {
        // Fraction list path.
        let fractions: Result<Vec<auths_keri::Fraction>, _> = trimmed
            .split(',')
            .map(|part| part.trim().parse::<auths_keri::Fraction>())
            .collect();
        let fractions = fractions.map_err(|e| {
            anyhow!(
                "invalid fraction in threshold {:?}: {e}. Provide either an integer count (e.g. \"2\") or a comma-separated fraction list (e.g. \"1/2,1/2,1/2\").",
                trimmed
            )
        })?;
        if fractions.len() != key_count {
            return Err(anyhow!(
                "threshold fraction list has {} entries for device_count {}",
                fractions.len(),
                key_count
            ));
        }
        Ok(auths_keri::Threshold::Weighted(vec![fractions]))
    } else {
        let n = u64::from_str_radix(trimmed, 16).map_err(|_| {
            anyhow!(
                "invalid scalar threshold {:?}: expected hex integer (e.g. \"2\") or fraction list (e.g. \"1/2,1/2,1/2\")",
                trimmed
            )
        })?;
        if (n as usize) > key_count {
            return Err(anyhow!(
                "threshold {} exceeds device count {}",
                n,
                key_count
            ));
        }
        if n == 0 && key_count > 0 {
            return Err(anyhow!(
                "threshold 0 is unsatisfiable for non-empty device set"
            ));
        }
        Ok(auths_keri::Threshold::Simple(n))
    }
}

fn resolve_interactive(cmd: &InitCommand) -> Result<bool> {
    // `--json` is a machine-readable contract: never prompt, so a parser on the
    // other end gets a single JSON object on stdout and nothing blocks on input.
    if crate::ux::format::is_json_mode() {
        if cmd.interactive {
            return Err(anyhow!("--interactive cannot be combined with --json"));
        }
        return Ok(false);
    }
    if cmd.interactive {
        if !std::io::stdin().is_terminal() {
            return Err(anyhow!(
                "--interactive requires a TTY (stdin is not a terminal)"
            ));
        }
        Ok(true)
    } else if cmd.non_interactive {
        Ok(false)
    } else {
        Ok(std::io::stdin().is_terminal())
    }
}

/// Handle the `init` command with Gather → Execute → Display pattern.
///
/// Args:
/// * `cmd`: Parsed [`InitCommand`] from the CLI.
/// * `ctx`: CLI configuration with passphrase provider and repo path.
///
/// Usage:
/// ```ignore
/// handle_init(cmd, &ctx)?;
/// ```
pub fn handle_init(
    cmd: InitCommand,
    ctx: &CliConfig,
    now: chrono::DateTime<chrono::Utc>,
) -> Result<()> {
    let out = Output::new();

    if cmd.github_action {
        return helpers::scaffold_github_action(&out);
    }

    // Validate multi-device flag combinations at CLI parse time.
    let device_count = cmd.device_count.max(1) as usize;
    if device_count > 1 {
        let kt_str = cmd
            .signing_threshold
            .as_deref()
            .ok_or_else(|| anyhow!("--signing-threshold is required when --device-count > 1"))?;
        let nt_str = cmd
            .rotation_threshold
            .as_deref()
            .ok_or_else(|| anyhow!("--rotation-threshold is required when --device-count > 1"))?;
        let _kt = parse_threshold_cli(kt_str, device_count)?;
        let _nt = parse_threshold_cli(nt_str, device_count)?;
        return Err(anyhow!(
            "multi-device init (--device-count > 1) is not yet wired through the developer setup flow. \
             Run `auths init` for a single-device identity, then add devices with `auths device pair` \
             (each device is a delegated identity under your root)."
        ));
    }
    if cmd.signing_threshold.is_some() && device_count == 1 {
        let kt = parse_threshold_cli(cmd.signing_threshold.as_deref().unwrap_or("1"), 1)?;
        if !matches!(kt, auths_keri::Threshold::Simple(1)) {
            return Err(anyhow!(
                "single-device init requires --signing-threshold to be 1 or omitted"
            ));
        }
    }

    let interactive = resolve_interactive(&cmd)?;

    let profile = match cmd.profile {
        Some(p) => p,
        None if !interactive => {
            out.println("No profile specified in non-interactive mode, defaulting to developer.");
            InitProfile::Developer
        }
        None => prompt_profile(&out)?,
    };

    out.print_heading(&format!("Auths Setup ({})", profile));
    out.println("=".repeat(40).as_str());

    match profile {
        InitProfile::Developer => run_developer_setup(interactive, &out, &cmd, ctx, now)?,
        InitProfile::Ci => run_ci_setup(&out, ctx)?,
        InitProfile::Agent => run_agent_setup(interactive, &out, &cmd, ctx)?,
    }

    Ok(())
}

fn run_developer_setup(
    interactive: bool,
    out: &Output,
    cmd: &InitCommand,
    ctx: &CliConfig,
    now: chrono::DateTime<chrono::Utc>,
) -> Result<()> {
    let mut guide = GuidedSetup::new(out, guided::developer_steps(), interactive);

    // GATHER
    guide.section("Prerequisites & Configuration");
    let registry_path = auths_sdk::paths::resolve_registry_path(ctx.repo_path.clone())?;
    let (keychain, mut config) = gather_developer_config(interactive, out, cmd, &registry_path)?;
    ensure_registry_dir(&registry_path)?;

    let sign_binary_path = which::which("auths-sign").ok();
    if let Some(ref path) = sign_binary_path {
        config.sign_binary_path = Some(path.clone());
    }
    let git_config_provider: Option<Box<dyn GitConfigProvider>> = match &config.git_signing_scope {
        GitSigningScope::Skip => None,
        GitSigningScope::Global => Some(Box::new(SystemGitConfigProvider::global())),
        GitSigningScope::Local { repo_path } => {
            Some(Box::new(SystemGitConfigProvider::local(repo_path.clone())))
        }
    };

    // EXECUTE
    guide.section("Creating Identity");
    let sdk_ctx = build_auths_context(&registry_path, &ctx.env_config, None)?;
    let keychain_arc: Arc<dyn KeyStorage + Send + Sync> = Arc::from(keychain);
    let signer = StorageSigner::new(Arc::clone(&keychain_arc));
    let result = initialize(
        IdentityConfig::Developer(config),
        &sdk_ctx,
        keychain_arc,
        &signer,
        ctx.passphrase_provider.as_ref(),
        git_config_provider.as_deref(),
    )?;
    let result = match result {
        InitializeResult::Developer(r) => r,
        _ => unreachable!(),
    };

    out.print_success(&format!(
        "Identity created: {}",
        crate::ux::product_id(&result.identity_did)
    ));
    out.print_success(&format!(
        "This device authorized: {}",
        crate::ux::product_id(result.device_did.as_str())
    ));

    // PLATFORM VERIFICATION
    //
    // Linking GitHub is what uploads the SSH signing key, and that is the only
    // thing that makes a user's commits render as "Verified" to everyone else.
    // It was previously gated behind `--register` — a flag whose documented job is
    // publishing to the Auths Registry, an unrelated (and dead) host. So the
    // default first run left commits Unverified on github.com while the code to
    // fix that sat one boolean away.
    //
    // Research puts a number on the cost: 73.73% of commit-signature verification
    // failures in the wild are `unknown_key` — developers sign and never register
    // the key ("a usability problem, not a cryptographic one", arXiv:2604.14014).
    // Auths mints the key, signs with it, and can upload it; withholding that by
    // default forfeits the product's clearest advantage over gitsign, whose certs
    // GitHub structurally cannot verify.
    let link_github = if cmd.no_github {
        false
    } else if cmd.github {
        true
    } else {
        interactive && git_remote_is_github()
    };
    guide.section("Platform Verification");
    let proof_url = if link_github {
        out.print_info("Link your GitHub account");
        out.newline();
        match prompt_platform_verification(
            out,
            Arc::clone(&ctx.passphrase_provider),
            &ctx.env_config,
            now,
        )? {
            Some((url, _username)) => {
                out.print_success(&format!("GitHub identity linked: {}", url));
                Some(url)
            }
            None => {
                out.println("  Continuing as anonymous identity");
                None
            }
        }
    } else {
        None
    };

    // POST-SETUP
    guide.section("Shell & Signing Setup");
    offer_shell_completions(interactive, out)?;

    // Commit-time trailers: install the prepare-commit-msg hook and point
    // core.hooksPath at it, so a plain `git commit` carries the Auths-Id /
    // Auths-Device trailers `auths verify` replays — zero extra commands.
    // Trailer values come from the signer resolver (same source as `auths sign`):
    // on the root machine Auths-Device is the root `did:keri:` itself, on a
    // delegate it is the device's delegated AID — always a replayable KEL.
    if let Some(git_config) = git_config_provider.as_deref() {
        match auths_sdk::domains::identity::local::resolve_local_signer(&sdk_ctx) {
            Ok(signer) => {
                match auths_sdk::workflows::commit_hooks::enable_commit_trailers(
                    &registry_path,
                    &signer.root_did,
                    &signer.signer_did,
                    git_config,
                ) {
                    Ok(()) => {
                        // Refresh stamps the current KEL position (Auths-Anchor-Seq)
                        // into the trailer file the hook reads.
                        let _ = auths_sdk::workflows::commit_hooks::refresh_commit_trailers(
                            &sdk_ctx,
                            &registry_path,
                        );
                        out.println("  Commit trailers enabled (prepare-commit-msg hook)");
                    }
                    Err(e) => out.println(&format!("  Note: could not install commit hook ({e})")),
                }
            }
            Err(e) => out.println(&format!("  Note: could not resolve signer for hook ({e})")),
        }
    }

    // Pin the local identity as a trusted root for KEL-native verification (Epic B):
    // the committed `<repo>/.auths/roots` is the root of trust — no allowed_signers file.
    // Staging is the load-bearing half: a pin that is written but never staged never
    // reaches a cloner, so every third-party verification path dead-ends on it. We do
    // not author a commit on the user's behalf — the pin rides their next one.
    if let Ok(output) = crate::subprocess::git_command(&["rev-parse", "--show-toplevel"]).output()
        && output.status.success()
    {
        let root = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
        let root_did = result.identity_did.to_string();
        let index = crate::adapters::git_index::SystemRepoIndex::at(root.clone());
        match auths_sdk::workflows::roots::pin_root_in_repo(
            &crate::adapters::config_store::FileConfigStore,
            &index,
            &root,
            &root_did,
        ) {
            Ok(RootPinOutcome::AlreadyTracked) => out.println(&format!(
                "  Trusted root already pinned: {}",
                crate::ux::product_id(&root_did)
            )),
            Ok(_) => {
                out.println(&format!(
                    "  Pinned trusted root: {}",
                    crate::ux::product_id(&root_did)
                ));
                out.println("  Staged .auths/roots — your next commit lets clones verify you");
            }
            Err(e) => out.println(&format!("  Note: could not pin trusted root ({e})")),
        }
    }

    // REGISTRATION & DISPLAY
    guide.section("Registration & Summary");
    let registered = submit_registration(
        &registry_path,
        cmd.registry.as_deref(),
        proof_url,
        !cmd.register, // skip unless --register is explicitly passed
        out,
    );
    display_developer_result(out, &result, registered.as_deref());

    Ok(())
}

fn run_ci_setup(out: &Output, ctx: &CliConfig) -> Result<()> {
    let mut guide = GuidedSetup::new(out, guided::ci_steps(), false);

    // GATHER
    guide.section("CI Environment Detection");
    let (ci_env, config, keychain, passphrase_str) =
        gather_ci_config(out, ctx.repo_path.as_deref())?;
    let registry_path = config.registry_path.clone();
    ensure_registry_dir(&registry_path)?;

    // EXECUTE
    guide.section("Creating CI Identity");
    // gather_ci_config set the file-backend env vars; read them fresh so the SDK
    // context's keychain matches the one we just built (ctx.env_config predates them).
    let ci_env_config = auths_sdk::core_config::EnvironmentConfig::from_env();
    let sdk_ctx = build_auths_context(&registry_path, &ci_env_config, None)?;
    let keychain_arc: Arc<dyn KeyStorage + Send + Sync> = Arc::from(keychain);
    let signer = StorageSigner::new(Arc::clone(&keychain_arc));
    let provider = PrefilledPassphraseProvider::new(&passphrase_str);
    let result = initialize(
        IdentityConfig::Ci(config),
        &sdk_ctx,
        keychain_arc,
        &signer,
        &provider,
        None,
    )?;
    let result = match result {
        InitializeResult::Ci(r) => r,
        _ => unreachable!(),
    };

    // DISPLAY
    guide.section("Summary");
    display_ci_result(out, &result, ci_env.as_deref());

    Ok(())
}

fn run_agent_setup(
    interactive: bool,
    out: &Output,
    cmd: &InitCommand,
    ctx: &CliConfig,
) -> Result<()> {
    let mut guide = GuidedSetup::new(out, guided::agent_steps(), interactive);

    // GATHER
    guide.section("Agent Configuration");
    let (keychain, config) = gather_agent_config(interactive, out, cmd)?;
    let registry_path = config.registry_path.clone();

    if config.dry_run {
        display_agent_dry_run(out, &config);
        return Ok(());
    }

    // The user said "I want an agent" — deliver one. An agent is a KERI
    // delegated identifier under an existing root, so when a root identity
    // exists, route straight into the delegation flow (the same machinery as
    // `auths id agent add`), reusing the capabilities just selected.
    if interactive && delegate_agent_interactively(out, cmd, ctx, &config, &registry_path)? {
        return Ok(());
    }

    // EXECUTE — no root identity (or non-interactive): the SDK returns the
    // actionable "delegate via `auths id agent add`" guidance.
    guide.section("Creating Agent Identity");
    ensure_registry_dir(&registry_path)?;
    let sdk_ctx = build_auths_context(&registry_path, &ctx.env_config, None)?;
    let keychain_arc: Arc<dyn KeyStorage + Send + Sync> = Arc::from(keychain);
    let signer = StorageSigner::new(Arc::clone(&keychain_arc));
    let result = initialize(
        IdentityConfig::Agent(config),
        &sdk_ctx,
        keychain_arc,
        &signer,
        ctx.passphrase_provider.as_ref(),
        None,
    )?;
    let result = match result {
        InitializeResult::Agent(r) => r,
        _ => unreachable!(),
    };

    // DISPLAY
    guide.section("Summary");
    display_agent_result(out, &result);

    Ok(())
}

/// Delegate an agent under the existing root identity, interactively. Returns
/// `Ok(false)` when no root identity exists (the caller falls through to the
/// guidance path).
fn delegate_agent_interactively(
    out: &Output,
    cmd: &InitCommand,
    ctx: &CliConfig,
    config: &auths_sdk::types::CreateAgentIdentityConfig,
    registry_path: &Path,
) -> Result<bool> {
    let sdk_ctx = build_auths_context(
        registry_path,
        &ctx.env_config,
        Some(Arc::clone(&ctx.passphrase_provider)),
    )?;
    if sdk_ctx.identity_storage.load_identity().is_err() {
        out.print_info("No root identity found — an agent is delegated under a root identity.");
        out.println("  Run `auths init` (developer profile) first, then choose Agent again.");
        return Ok(false);
    }

    let label: String = dialoguer::Input::new()
        .with_prompt("Agent label (also the keychain alias for its key)")
        .default("agent".to_string())
        .interact_text()
        .unwrap_or_else(|_| "agent".to_string());

    let root_alias = auths_sdk::keychain::KeyAlias::new_unchecked(&cmd.key_alias);
    let agent_alias = auths_sdk::keychain::KeyAlias::new_unchecked(&label);
    #[allow(clippy::disallowed_methods)] // CLI boundary: clock injected here
    let expires_at = config
        .expires_in
        .map(|secs| chrono::Utc::now().timestamp() + secs as i64);

    let result = auths_sdk::domains::agents::add_scoped(
        &sdk_ctx,
        &root_alias,
        &agent_alias,
        auths_crypto::CurveType::default(),
        &config.capabilities,
        expires_at,
    )
    .map_err(anyhow::Error::new)?;
    let _ = auths_sdk::workflows::commit_hooks::refresh_commit_trailers(&sdk_ctx, registry_path);

    out.newline();
    out.print_success("Agent delegated under your identity:");
    out.println(&format!(
        "  {}",
        out.info(&crate::ux::product_id(&result.agent_did))
    ));
    let cap_display: Vec<String> = config.capabilities.iter().map(|c| c.to_string()).collect();
    if !cap_display.is_empty() {
        out.println(&format!("  Capabilities: {}", cap_display.join(", ")));
    }
    out.newline();
    out.println("  Manage it: auths id agent list / auths id agent revoke");
    Ok(true)
}

impl crate::commands::executable::ExecutableCommand for InitCommand {
    #[allow(clippy::disallowed_methods)]
    fn execute(&self, ctx: &CliConfig) -> anyhow::Result<()> {
        handle_init(self.clone(), ctx, chrono::Utc::now())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use auths_sdk::types::CiEnvironment;
    use gather::map_ci_environment;

    #[test]
    fn test_setup_profile_display() {
        assert_eq!(InitProfile::Developer.to_string(), "developer");
        assert_eq!(InitProfile::Ci.to_string(), "ci");
        assert_eq!(InitProfile::Agent.to_string(), "agent");
    }

    #[test]
    fn parse_threshold_cli_rejects_unsatisfiable_thresholds() {
        // A threshold larger than the device count can never be met — it would brick recovery,
        // so it is rejected at creation.
        assert!(parse_threshold_cli("3", 2).is_err());
        // Zero is unsatisfiable for a non-empty device set.
        assert!(parse_threshold_cli("0", 2).is_err());
        // A satisfiable threshold parses: 2-of-2.
        assert_eq!(
            parse_threshold_cli("2", 2).unwrap(),
            auths_keri::Threshold::Simple(2)
        );
        // 1-of-N (the any-device default) is satisfiable.
        assert!(parse_threshold_cli("1", 3).is_ok());
    }

    #[test]
    fn test_setup_command_defaults() {
        let cmd = InitCommand {
            interactive: false,
            non_interactive: false,
            profile: None,
            key_alias: DEFAULT_KEY_ALIAS.to_string(),
            force: false,
            confirm_replace: false,
            dry_run: false,
            registry: None,
            register: false,
            github: false,
            no_github: false,
            git_scope: None,
            github_action: false,
            device_count: 1,
            signing_threshold: None,
            rotation_threshold: None,
        };
        assert!(!cmd.interactive);
        assert!(!cmd.non_interactive);
        assert!(cmd.profile.is_none());
        assert_eq!(cmd.key_alias, "main");
        assert!(!cmd.force);
        assert!(!cmd.dry_run);
        // No default: auths needs no registry, and the one that used to be baked
        // in returned 404. Registration is opt-in and must name its registry.
        assert_eq!(cmd.registry, None);
        assert!(!cmd.register);
        assert!(!cmd.github_action);
    }

    #[test]
    fn test_setup_command_with_profile() {
        let cmd = InitCommand {
            interactive: false,
            non_interactive: true,
            profile: Some(InitProfile::Ci),
            key_alias: "ci-key".to_string(),
            force: true,
            confirm_replace: false,
            dry_run: false,
            registry: None,
            register: false,
            github: false,
            no_github: false,
            git_scope: None,
            github_action: false,
            device_count: 1,
            signing_threshold: None,
            rotation_threshold: None,
        };
        assert!(cmd.non_interactive);
        assert!(matches!(cmd.profile, Some(InitProfile::Ci)));
        assert_eq!(cmd.key_alias, "ci-key");
        assert!(cmd.force);
    }

    #[test]
    fn test_map_ci_environment() {
        assert!(matches!(
            map_ci_environment(&Some("GitHub Actions".into())),
            CiEnvironment::GitHubActions
        ));
        assert!(matches!(
            map_ci_environment(&Some("GitLab CI".into())),
            CiEnvironment::GitLabCi
        ));
        assert!(matches!(map_ci_environment(&None), CiEnvironment::Unknown));
    }

    #[test]
    fn test_resolve_interactive_non_interactive_flag() {
        let cmd = InitCommand {
            interactive: false,
            non_interactive: true,
            profile: None,
            key_alias: DEFAULT_KEY_ALIAS.to_string(),
            force: false,
            confirm_replace: false,
            dry_run: false,
            registry: None,
            register: false,
            github: false,
            no_github: false,
            git_scope: None,
            github_action: false,
            device_count: 1,
            signing_threshold: None,
            rotation_threshold: None,
        };
        assert!(!resolve_interactive(&cmd).unwrap());
    }

    #[test]
    fn test_resolve_interactive_auto_detect() {
        let cmd = InitCommand {
            interactive: false,
            non_interactive: false,
            profile: None,
            key_alias: DEFAULT_KEY_ALIAS.to_string(),
            force: false,
            confirm_replace: false,
            dry_run: false,
            registry: None,
            register: false,
            github: false,
            no_github: false,
            git_scope: None,
            github_action: false,
            device_count: 1,
            signing_threshold: None,
            rotation_threshold: None,
        };
        // Auto-detect returns is_terminal() — result depends on environment
        let result = resolve_interactive(&cmd).unwrap();
        assert_eq!(result, std::io::stdin().is_terminal());
    }
}