openlatch-provider 0.1.0

Self-service onboarding CLI + runtime daemon for OpenLatch Editors and Providers
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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
//! `init` — interactive wizard that scaffolds `<slug>.yaml`.
//!
//! Flow per `phase-1-editor-cli.md` task P1.T8:
//!
//! ```text
//! 1. Authenticate (mandatory — no opt-out flag in production).
//! 2. Editor block prompts (TTY) or --editor-slug/--display-name flags.
//!    Every slug is validated against the platform before the user moves on:
//!    409 → re-prompt in TTY; exit 1 with OL-4280..OL-4283 in non-TTY.
//! 3. Resolve target path = `<provider_dir>/<slug>.yaml`; refuse to clobber
//!    unless --force (existing file backed up to `.bak`).
//! 4. Telemetry consent prompt.
//! 5. Atomically write the editor-only manifest + persist `manifest_slug`.
//! 6. (TTY) Branch-by-intent picker:
//!      A) Wizard — adds 1 Tool + 1 Capability + 1 Provider + 1 Binding,
//!         validates, re-writes, then opens `$EDITOR` for tweaks.
//!      B) `new tool --template …` (placeholder until P2.T10).
//!      C) Edit by hand — opens `$EDITOR` with four-entity guidance.
//!      D) Save and exit.
//!    (Non-TTY) Print the four-entity next-steps block and exit.
//! 7. Emit telemetry::Event::init_completed exactly once with branch counts.
//! ```

use std::collections::BTreeSet;
use std::path::Path;

use clap::Args;
use serde_json::json;

use crate::api::client::ApiClient;
use crate::api::editor as api_editor;
use crate::cli::commands::shared::make_client;
use crate::cli::GlobalArgs;
use crate::config;
use crate::error::{
    OlError, OL_4210_SCHEMA_MISMATCH, OL_4232_BACKEND_UNAUTHORIZED, OL_4263_CONSENT_WRITE_FAILED,
    OL_4274_MANIFEST_WRITE_FAILED, OL_4280_PLATFORM_DUPLICATE_TOOL_SLUG,
    OL_4281_PLATFORM_DUPLICATE_PROVIDER_SLUG, OL_4282_PLATFORM_DUPLICATE_EDITOR_SLUG,
    OL_4283_PLATFORM_DUPLICATE_BINDING,
};
use crate::manifest;
use crate::ui::output::OutputConfig;

#[derive(Args, Debug)]
pub struct InitArgs {
    /// Overwrite an existing `<slug>.yaml` (backed up to .bak).
    #[arg(long)]
    pub force: bool,

    /// (Hidden, test/CI use only) Skip the mandatory-auth gate and the
    /// platform `:validate` round-trips. Production users should never set
    /// this — collisions are detected by `register` instead, after the
    /// manifest has been written.
    #[arg(long, hide = true)]
    pub skip_preflight: bool,

    /// Editor slug — required when `--non-interactive`.
    #[arg(long)]
    pub editor_slug: Option<String>,

    /// Editor display name — required when `--non-interactive`.
    #[arg(long)]
    pub display_name: Option<String>,

    /// Editor description.
    #[arg(long)]
    pub description: Option<String>,

    /// Editor homepage URL.
    #[arg(long)]
    pub homepage_url: Option<String>,

    /// Editor docs URL.
    #[arg(long)]
    pub docs_url: Option<String>,

    /// Force-enable PostHog telemetry (skips the consent prompt).
    #[arg(long)]
    pub telemetry: bool,

    /// Force-disable PostHog telemetry (skips the consent prompt).
    #[arg(long)]
    pub no_telemetry: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NextStepBranch {
    Wizard,
    NewToolTemplate,
    EditByHand,
    SaveAndExit,
}

#[derive(Debug, Clone, Copy, Default)]
struct BranchCounts {
    tools: u32,
    providers: u32,
    bindings: u32,
}

pub async fn run(g: &GlobalArgs, args: InitArgs) -> Result<(), OlError> {
    let out = OutputConfig::resolve(g);
    crate::ui::header::print(&out, &["init"]);

    // Auth + platform client. Mandatory unless --skip-preflight is set
    // (which is test/CI-only and stays hidden from --help).
    let client = if args.skip_preflight {
        None
    } else {
        ensure_logged_in(&out, g).await?;
        Some(make_client().await?)
    };

    // If the user is re-running over an existing manifest with --force, we
    // want to skip slug validation for slugs the user already owns. Read the
    // existing manifest once up-front so the wizard branch can consult it.
    let owned_slugs = if args.force {
        owned_slugs_from_existing(&args)
    } else {
        OwnedSlugs::default()
    };

    let editor = if out.interactive {
        prompt_editor(&out, &args, client.as_ref(), &owned_slugs).await?
    } else {
        let editor = flags_to_editor(&args)?;
        validate_editor_slug_or_error(
            client.as_ref(),
            editor.get("slug").and_then(|v| v.as_str()).unwrap_or(""),
            &owned_slugs,
        )
        .await?;
        editor
    };

    let slug = editor
        .get("slug")
        .and_then(|v| v.as_str())
        .ok_or_else(|| OlError::new(OL_4210_SCHEMA_MISMATCH, "editor.slug missing"))?
        .to_string();
    let path = config::manifest_path_for_slug(&slug);

    if path.exists() && !args.force {
        out.print_step(&format!(
            "{} already exists — pass --force to overwrite (a .bak copy will be made first).",
            path.display()
        ));
        return Ok(());
    }

    if path.exists() && args.force {
        let bak = path.with_extension("yaml.bak");
        std::fs::copy(&path, &bak).map_err(|e| {
            OlError::new(
                OL_4274_MANIFEST_WRITE_FAILED,
                format!("backup {}: {e}", bak.display()),
            )
        })?;
        out.print_step(&format!("Backed up existing manifest to {}", bak.display()));
    }

    // First write — editor-only manifest. The picker may overwrite this with
    // a fully-populated manifest in the Wizard branch, but writing here first
    // preserves Branches B/C/D and the cancellation case.
    let mut manifest_value = json!({
        "schema_version": 1,
        "editor": editor,
    });
    write_manifest_value(&path, &manifest_value)?;
    out.print_step(&format!("Wrote {}", path.display()));

    config::set_manifest_slug(g.profile.as_deref(), &slug)?;
    out.print_step(&format!(
        "Linked manifest to profile `{}` (config.toml)",
        g.profile.as_deref().unwrap_or("default")
    ));

    handle_consent(&out, &args)?;

    // Branch dispatch.
    let counts = if !out.interactive || out.is_quiet() || out.is_machine() {
        print_onboarding_summary(&out, &path, BranchCounts::default());
        BranchCounts::default()
    } else {
        let branch = pick_next_step();
        match branch {
            NextStepBranch::Wizard => {
                run_wizard_branch(
                    &out,
                    &path,
                    &mut manifest_value,
                    client.as_ref(),
                    &owned_slugs,
                )
                .await?
            }
            NextStepBranch::NewToolTemplate => {
                run_new_tool_branch(&out, &path);
                BranchCounts::default()
            }
            NextStepBranch::EditByHand => {
                run_edit_branch(&out, &path);
                BranchCounts::default()
            }
            NextStepBranch::SaveAndExit => {
                print_onboarding_summary(&out, &path, BranchCounts::default());
                BranchCounts::default()
            }
        }
    };

    // Editor is always present at this point — we wrote it above and would
    // have errored out otherwise. Pass `true` literally rather than re-derive.
    crate::telemetry::capture_global(crate::telemetry::Event::init_completed(
        true,
        counts.tools,
        counts.providers,
        counts.bindings,
    ));

    Ok(())
}

// ---------------------------------------------------------------------------
// Editor block prompts (existing; unchanged behavior)
// ---------------------------------------------------------------------------

fn flags_to_editor(args: &InitArgs) -> Result<serde_json::Value, OlError> {
    let slug = args.editor_slug.clone().ok_or_else(|| {
        OlError::new(
            OL_4210_SCHEMA_MISMATCH,
            "--non-interactive mode requires --editor-slug",
        )
    })?;
    let display_name = args.display_name.clone().ok_or_else(|| {
        OlError::new(
            OL_4210_SCHEMA_MISMATCH,
            "--non-interactive mode requires --display-name",
        )
    })?;
    let mut editor = json!({
        "slug": slug,
        "display_name": display_name,
        "description": args.description.clone().unwrap_or_else(|| "TBD".into()),
    });
    if let Some(h) = &args.homepage_url {
        editor["homepage_url"] = json!(h);
    }
    if let Some(d) = &args.docs_url {
        editor["docs_url"] = json!(d);
    }
    Ok(editor)
}

async fn prompt_editor(
    out: &OutputConfig,
    args: &InitArgs,
    client: Option<&ApiClient>,
    owned: &OwnedSlugs,
) -> Result<serde_json::Value, OlError> {
    use inquire::Text;

    explain(
        out,
        "An Editor is your vendor identity in the OpenLatch marketplace — \
         the brand under which you publish detection tools.",
    );

    // Slug step: prompt → validate → re-prompt on collision.
    let slug = if let Some(s) = args.editor_slug.clone() {
        validate_editor_slug_or_error(client, &s, owned).await?;
        s
    } else {
        loop {
            let candidate = Text::new("Editor slug:")
                .with_validator(slug_validator())
                .prompt()
                .map_err(|e| OlError::new(OL_4210_SCHEMA_MISMATCH, format!("prompt: {e}")))?;
            match check_editor_slug(client, &candidate, owned).await {
                Ok(()) => break candidate,
                Err(e) if e.is(OL_4282_PLATFORM_DUPLICATE_EDITOR_SLUG) => {
                    eprintln!(
                        "  ✗ '{candidate}' is taken by another editor — pick a different slug."
                    );
                    continue;
                }
                Err(e) => return Err(e),
            }
        }
    };
    let display_name = args.display_name.clone().map_or_else(
        || {
            Text::new("Editor display name:")
                .with_help_message("Shown in the marketplace catalog")
                .prompt()
                .map_err(|e| OlError::new(OL_4210_SCHEMA_MISMATCH, format!("prompt: {e}")))
        },
        Ok,
    )?;
    let description = args.description.clone().map_or_else(
        || {
            Text::new("Description:")
                .with_default("TBD")
                .prompt()
                .map_err(|e| OlError::new(OL_4210_SCHEMA_MISMATCH, format!("prompt: {e}")))
        },
        Ok,
    )?;
    let homepage_url = args.homepage_url.clone().map_or_else(
        || {
            Text::new("Homepage URL (optional):")
                .with_default("")
                .prompt()
                .map_err(|e| OlError::new(OL_4210_SCHEMA_MISMATCH, format!("prompt: {e}")))
        },
        Ok,
    )?;
    let docs_url = args.docs_url.clone().map_or_else(
        || {
            Text::new("Docs URL (optional):")
                .with_default("")
                .prompt()
                .map_err(|e| OlError::new(OL_4210_SCHEMA_MISMATCH, format!("prompt: {e}")))
        },
        Ok,
    )?;

    let mut editor = json!({
        "slug": slug,
        "display_name": display_name,
        "description": description,
    });
    if !homepage_url.is_empty() {
        editor["homepage_url"] = json!(homepage_url);
    }
    if !docs_url.is_empty() {
        editor["docs_url"] = json!(docs_url);
    }
    Ok(editor)
}

// ---------------------------------------------------------------------------
// Branch-by-intent picker
// ---------------------------------------------------------------------------

const PICKER_WIZARD: &str = "Set up a Tool + Provider + Binding now (interactive) (Recommended)";
const PICKER_NEW_TEMPLATE: &str = "Scaffold a starter tool repo (`new tool --template …`)";
const PICKER_EDIT: &str = "Edit ~/.openlatch/provider/<slug>.yaml by hand (opens in $EDITOR)";
const PICKER_SAVE_EXIT: &str = "Save and exit — I'll handle this later";

fn pick_next_step() -> NextStepBranch {
    use inquire::Select;

    let options = vec![
        PICKER_WIZARD,
        PICKER_NEW_TEMPLATE,
        PICKER_EDIT,
        PICKER_SAVE_EXIT,
    ];
    match Select::new("What would you like to do next?", options).prompt() {
        Ok(PICKER_WIZARD) => NextStepBranch::Wizard,
        Ok(PICKER_NEW_TEMPLATE) => NextStepBranch::NewToolTemplate,
        Ok(PICKER_EDIT) => NextStepBranch::EditByHand,
        Ok(PICKER_SAVE_EXIT) => NextStepBranch::SaveAndExit,
        Ok(_) => NextStepBranch::SaveAndExit,
        Err(e) => {
            tracing::warn!(error = %e, "picker cancelled, defaulting to save-and-exit");
            NextStepBranch::SaveAndExit
        }
    }
}

// ---------------------------------------------------------------------------
// Branch A — Wizard: 1 Tool + 1 Capability + 1 Provider + 1 Binding
// ---------------------------------------------------------------------------

async fn run_wizard_branch(
    out: &OutputConfig,
    path: &Path,
    manifest_value: &mut serde_json::Value,
    client: Option<&ApiClient>,
    owned: &OwnedSlugs,
) -> Result<BranchCounts, OlError> {
    let tool = prompt_tool(out, client, owned).await?;
    let provider = prompt_provider(out, client, owned).await?;
    let binding = prompt_binding(
        out,
        tool["slug"].as_str().unwrap_or_default(),
        provider["slug"].as_str().unwrap_or_default(),
        client,
    )
    .await?;

    manifest_value["tools"] = json!([tool]);
    manifest_value["providers"] = json!([provider]);
    manifest_value["bindings"] = json!([binding]);

    // Re-serialize → re-parse → schema-validate, then write atomically. We
    // don't run `manifest::semantic_check` because the JSON Schema already
    // catches every constraint we prompted for; semantic_check adds slug
    // cross-refs that will hold by construction (we only have one of each).
    manifest::schema::validate(manifest_value)?;
    write_manifest_value(path, manifest_value)?;

    out.print_step("Manifest: 1 editor · 1 tool · 1 provider · 1 binding");
    confirm_and_open_editor(out, path);
    print_onboarding_summary(
        out,
        path,
        BranchCounts {
            tools: 1,
            providers: 1,
            bindings: 1,
        },
    );

    Ok(BranchCounts {
        tools: 1,
        providers: 1,
        bindings: 1,
    })
}

async fn prompt_tool(
    out: &OutputConfig,
    client: Option<&ApiClient>,
    owned: &OwnedSlugs,
) -> Result<serde_json::Value, OlError> {
    use inquire::{MultiSelect, Text};

    explain(
        out,
        "A Tool is one detection capability you offer (e.g. PII scanning, \
         credential detection). One logical tool per slug; versions are tracked \
         independently when you `publish`.",
    );

    let slug = loop {
        let candidate = Text::new("Tool slug:")
            .with_validator(slug_validator())
            .with_help_message("Lowercase, ≤63 chars, [a-z0-9-]")
            .prompt()
            .map_err(prompt_err)?;
        match check_tool_slug(client, &candidate, owned).await {
            Ok(()) => break candidate,
            Err(e) if e.is(OL_4280_PLATFORM_DUPLICATE_TOOL_SLUG) => {
                eprintln!("  ✗ tool slug '{candidate}' is already in use — pick another.");
                continue;
            }
            Err(e) => return Err(e),
        }
    };

    let description = Text::new("Tool description:")
        .with_default("TBD")
        .prompt()
        .map_err(prompt_err)?;

    let hooks_supported: Vec<String> = loop {
        let picks = MultiSelect::new(
            "Hook events this tool subscribes to:",
            manifest::KNOWN_HOOK_EVENTS.to_vec(),
        )
        .prompt()
        .map_err(prompt_err)?;
        if !picks.is_empty() {
            break picks.into_iter().map(String::from).collect();
        }
        eprintln!("  (pick at least one hook event — press space to select)");
    };

    let agents_supported: Vec<String> = loop {
        let picks = MultiSelect::new(
            "Agent platforms this tool supports:",
            manifest::KNOWN_AGENT_PLATFORMS.to_vec(),
        )
        .with_default(&[0])
        .prompt()
        .map_err(prompt_err)?;
        if !picks.is_empty() {
            break picks.into_iter().map(String::from).collect();
        }
        eprintln!("  (pick at least one agent platform — press space to select)");
    };

    let capability = prompt_capability()?;

    Ok(json!({
        "slug": slug,
        "version": "0.1.0",
        "license": "apache-2.0",
        "description": description,
        "hooks_supported": hooks_supported,
        "agents_supported": agents_supported,
        "capabilities": [capability],
    }))
}

fn prompt_capability() -> Result<serde_json::Value, OlError> {
    use inquire::{Confirm, Select, Text};

    let threat_category = Select::new("Threat category:", threat_category_options())
        .prompt()
        .map_err(prompt_err)?
        .value;

    let declared_latency_p95_ms = Text::new("Declared p95 latency (ms, 1..=60000):")
        .with_default("200")
        .with_validator(int_range_validator(1, 60000))
        .prompt()
        .map_err(prompt_err)?
        .parse::<u64>()
        .map_err(|e| OlError::new(OL_4210_SCHEMA_MISMATCH, format!("latency: {e}")))?;

    let execution_mode = Select::new("Execution mode:", vec!["sync", "async"])
        .prompt()
        .map_err(prompt_err)?;

    let needs_raw_payload = Confirm::new("Does the tool need the raw (un-redacted) event payload?")
        .with_default(false)
        .prompt()
        .map_err(prompt_err)?;

    Ok(json!({
        "threat_category": threat_category,
        "declared_latency_p95_ms": declared_latency_p95_ms,
        "execution_mode": execution_mode,
        "needs_raw_payload": needs_raw_payload,
    }))
}

async fn prompt_provider(
    out: &OutputConfig,
    client: Option<&ApiClient>,
    owned: &OwnedSlugs,
) -> Result<serde_json::Value, OlError> {
    use inquire::{validator::Validation, Text};

    explain(
        out,
        "A Provider is the compute environment hosting your tool — typically \
         named by region and capacity. You can have several providers per tool \
         (e.g. one per region) for redundancy.",
    );

    let slug = loop {
        let candidate = Text::new("Provider slug:")
            .with_validator(slug_validator())
            .with_help_message("Lowercase, ≤63 chars, [a-z0-9-]")
            .prompt()
            .map_err(prompt_err)?;
        match check_provider_slug(client, &candidate, owned).await {
            Ok(()) => break candidate,
            Err(e) if e.is(OL_4281_PLATFORM_DUPLICATE_PROVIDER_SLUG) => {
                eprintln!("  ✗ provider slug '{candidate}' is already in use — pick another.");
                continue;
            }
            Err(e) => return Err(e),
        }
    };

    let display_name = Text::new("Provider display name:")
        .with_validator(|s: &str| {
            if s.trim().is_empty() {
                Ok(Validation::Invalid("display_name cannot be empty".into()))
            } else {
                Ok(Validation::Valid)
            }
        })
        .prompt()
        .map_err(prompt_err)?;

    let region = Text::new("Region:")
        .with_default("us-east-1")
        .prompt()
        .map_err(prompt_err)?;

    let total_capacity_qps = Text::new("Total capacity (qps, ≥1):")
        .with_default("100")
        .with_validator(int_range_validator(1, i64::MAX))
        .prompt()
        .map_err(prompt_err)?
        .parse::<u64>()
        .map_err(|e| OlError::new(OL_4210_SCHEMA_MISMATCH, format!("capacity: {e}")))?;

    Ok(json!({
        "slug": slug,
        "display_name": display_name,
        "region": region,
        "total_capacity_qps": total_capacity_qps,
    }))
}

async fn prompt_binding(
    out: &OutputConfig,
    tool_slug: &str,
    provider_slug: &str,
    client: Option<&ApiClient>,
) -> Result<serde_json::Value, OlError> {
    use inquire::Text;

    explain(
        out,
        "A Binding wires one tool to one provider behind a public HTTPS endpoint. \
         The platform routes events to that URL using its declared latency, capacity \
         and priority — this is what the marketplace's routing engine actually picks.",
    );

    // Validate (tool, provider) pair against the platform up-front. A
    // duplicate-binding 409 here means the user previously bound this same
    // pair under another endpoint; ask them to pick a different pair via
    // the surrounding wizard rather than silently overwriting.
    if let Some(c) = client {
        if let Err(e) = api_editor::validate_binding(c, tool_slug, provider_slug).await {
            if e.is(OL_4283_PLATFORM_DUPLICATE_BINDING) {
                return Err(e.with_suggestion(
                    "Re-run `init` and choose a different tool or provider slug.",
                ));
            }
            return Err(e);
        }
    }

    let endpoint_url = Text::new("Public HTTPS endpoint (binding):")
        .with_help_message("e.g. https://provider.example.com/v1/event")
        .with_validator(https_url_validator())
        .prompt()
        .map_err(prompt_err)?;

    let declared_latency_p95_ms = Text::new("Binding p95 latency (ms, 1..=60000):")
        .with_default("200")
        .with_validator(int_range_validator(1, 60000))
        .prompt()
        .map_err(prompt_err)?
        .parse::<u64>()
        .map_err(|e| OlError::new(OL_4210_SCHEMA_MISMATCH, format!("latency: {e}")))?;

    let capacity_qps = Text::new("Capacity (qps, ≥1):")
        .with_default("100")
        .with_validator(int_range_validator(1, i64::MAX))
        .prompt()
        .map_err(prompt_err)?
        .parse::<u64>()
        .map_err(|e| OlError::new(OL_4210_SCHEMA_MISMATCH, format!("capacity: {e}")))?;

    let priority = Text::new("Priority (0..=100):")
        .with_default("50")
        .with_validator(int_range_validator(0, 100))
        .prompt()
        .map_err(prompt_err)?
        .parse::<u64>()
        .map_err(|e| OlError::new(OL_4210_SCHEMA_MISMATCH, format!("priority: {e}")))?;

    Ok(json!({
        "tool": tool_slug,
        "provider": provider_slug,
        "endpoint_url": endpoint_url,
        "declared_latency_p95_ms": declared_latency_p95_ms,
        "capacity_qps": capacity_qps,
        "priority": priority,
    }))
}

// ---------------------------------------------------------------------------
// Branch B — `new tool --template …` placeholder (P2.T10)
// ---------------------------------------------------------------------------

fn run_new_tool_branch(out: &OutputConfig, path: &Path) {
    out.print_info(
        "Scaffolding starter tool repos lands in P2.T10 \
         (`new tool --template <python|rust|node>`).",
    );
    out.print_info(
        "For now, opening the manifest so you can fill in tools[]/providers[]/bindings[] by hand.",
    );
    out.print_info("Docs: https://docs.openlatch.ai/cli/new-tool");
    run_edit_branch(out, path);
}

// ---------------------------------------------------------------------------
// Branch C — Edit by hand
// ---------------------------------------------------------------------------

fn run_edit_branch(out: &OutputConfig, path: &Path) {
    out.print_info("Add three sections to your manifest. The marketplace mental model:");
    out.print_substep("editor    ✓ already filled in (your vendor identity)");
    out.print_substep("tools[]    — what you detect (one entry per logical capability)");
    out.print_substep("providers[] — where you run (region + capacity)");
    out.print_substep("bindings[]  — how the platform routes (HTTPS endpoint per tool×provider)");
    confirm_and_open_editor(out, path);
    print_onboarding_summary(out, path, BranchCounts::default());
}

// ---------------------------------------------------------------------------
// Common output helpers
// ---------------------------------------------------------------------------

/// Print a one-sentence explanation block before an interactive prompt
/// section. Newlines around it keep prompts visually grouped.
fn explain(out: &OutputConfig, msg: &str) {
    if !out.interactive || out.is_quiet() || out.is_machine() {
        return;
    }
    out.print_info("");
    out.print_info(msg);
}

/// End-of-onboarding summary. Shows what was written, where, and the
/// next-step command sequence with a short rationale per step.
///
/// Common to every branch (Wizard / NewToolTemplate / Edit / SaveAndExit and
/// the non-interactive path). Suppressed in machine / quiet output modes.
fn print_onboarding_summary(out: &OutputConfig, manifest_path: &Path, counts: BranchCounts) {
    if out.is_quiet() || out.is_machine() {
        return;
    }
    out.print_info("");
    out.print_info("✨ You're all set — your editor profile is ready.");
    out.print_info("");
    out.print_info("Files written:");
    out.print_substep(&format!("manifest: {}", manifest_path.display()));
    if counts.tools > 0 || counts.providers > 0 || counts.bindings > 0 {
        out.print_substep(&format!(
            "contains: 1 editor · {} tool(s) · {} provider(s) · {} binding(s) — \
             all in the same file",
            counts.tools, counts.providers, counts.bindings
        ));
    } else {
        out.print_substep(
            "contains: 1 editor — add tools[]/providers[]/bindings[] to make it registerable",
        );
    }
    out.print_info("");
    out.print_info("What's next:");
    out.print_substep(
        "1. `openlatch-provider register --dry-run` — preview the diff against the platform \
         and probe your binding endpoints client-side. No mutations are sent.",
    );
    out.print_substep(
        "2. `openlatch-provider register` — commit the upsert. The platform will reveal \
         one-time webhook signing secrets (whsec_live_…) for each new binding; store them \
         immediately, they're never shown again.",
    );
    out.print_substep(
        "3. `openlatch-provider listen --port 8443` — run the runtime daemon on your \
         compute to receive HMAC-signed events from the platform.",
    );
    out.print_info("");
    out.print_info("Reference: https://docs.openlatch.ai/manifest");
}

// ---------------------------------------------------------------------------
// $EDITOR launcher
// ---------------------------------------------------------------------------

/// Ask the user before launching `$EDITOR`. Skipped in non-interactive
/// output modes — we just print the path. The Confirm defaults to yes
/// since the user just finished a flow that funnels into this step.
fn confirm_and_open_editor(out: &OutputConfig, path: &Path) {
    if !out.interactive || out.is_quiet() || out.is_machine() {
        out.print_info(&format!(
            "Manifest written. Review it at {} before running `register`.",
            path.display()
        ));
        return;
    }

    out.print_info("");
    out.print_info(
        "We'll open the manifest in your $EDITOR so you can review and tweak \
         it (license, hooks_supported, version, etc.) before registration.",
    );

    use inquire::Confirm;
    let answer = Confirm::new(&format!("Open {} now?", path.display()))
        .with_default(true)
        .prompt();
    match answer {
        Ok(true) => open_in_editor(out, path),
        Ok(false) => {
            out.print_info(&format!(
                "Skipped. Open {} manually whenever you're ready.",
                path.display()
            ));
        }
        Err(e) => {
            tracing::warn!(error = %e, "editor confirmation cancelled, skipping launch");
            out.print_info(&format!(
                "Skipped. Open {} manually whenever you're ready.",
                path.display()
            ));
        }
    }
}

fn open_in_editor(out: &OutputConfig, path: &Path) {
    let editor = std::env::var_os("VISUAL")
        .or_else(|| std::env::var_os("EDITOR"))
        .unwrap_or_else(|| {
            if cfg!(target_os = "windows") {
                "notepad".into()
            } else {
                "vi".into()
            }
        });
    let editor_str = editor.to_string_lossy().into_owned();
    let mut parts = editor_str.split_whitespace();
    let bin = parts.next().unwrap_or("vi");
    let args: Vec<&str> = parts.collect();

    match std::process::Command::new(bin)
        .args(&args)
        .arg(path)
        .status()
    {
        Ok(status) if status.success() => {
            out.print_step(&format!("Reviewed in {bin}"));
        }
        Ok(_) | Err(_) => {
            tracing::warn!(
                editor = %bin,
                path = %path.display(),
                "could not launch $EDITOR — falling back to printing path",
            );
            out.print_info(&format!("Open {} in your editor manually.", path.display()));
        }
    }
}

// ---------------------------------------------------------------------------
// Threat category labels (customer-facing UI text → schema enum value)
// ---------------------------------------------------------------------------

/// Picker option that shows a friendly description in the prompt while
/// preserving the canonical schema enum value for the manifest.
#[derive(Debug, Clone)]
struct ThreatChoice {
    value: &'static str,
    label: &'static str,
}

impl std::fmt::Display for ThreatChoice {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.label)
    }
}

/// Friendly labels for the 12 canonical threat categories. The wire value
/// (`.value`) MUST match `manifest::KNOWN_THREAT_CATEGORIES` — that constant
/// is in turn validated against `manifest-capability.schema.json` by the
/// `known_threat_categories_match_schema` test.
fn threat_category_options() -> Vec<ThreatChoice> {
    vec![
        ThreatChoice {
            value: "pii_outbound",
            label: "PII outbound — personal data leaving the agent",
        },
        ThreatChoice {
            value: "credential_detection",
            label: "Credentials & secrets — API keys, tokens, passwords in payloads",
        },
        ThreatChoice {
            value: "tool_poison_detection",
            label: "Tool / MCP poisoning — malicious or tampered tool definitions",
        },
        ThreatChoice {
            value: "shell_dangerous",
            label: "Dangerous shell commands — destructive or sandbox-escape patterns",
        },
        ThreatChoice {
            value: "injection_tool_response",
            label: "Prompt injection — adversarial content inside tool responses",
        },
        ThreatChoice {
            value: "injection_user_input",
            label: "Prompt injection — adversarial content in user input",
        },
        ThreatChoice {
            value: "attack_path_analysis",
            label: "Attack-path analysis — chained risky actions across an agent run",
        },
        ThreatChoice {
            value: "behavioral_anomaly",
            label: "Behavioral anomaly — out-of-pattern agent / tool behavior",
        },
        ThreatChoice {
            value: "data_exfiltration",
            label: "Data exfiltration — unauthorized outbound data transfers",
        },
        ThreatChoice {
            value: "privilege_escalation",
            label: "Privilege escalation — agent gaining capabilities it shouldn't have",
        },
        ThreatChoice {
            value: "unauthorized_resource_access",
            label: "Unauthorized resource access — files, services, secrets out of scope",
        },
        ThreatChoice {
            value: "policy_violation",
            label: "Policy violation — generic governance / compliance breach",
        },
    ]
}

// ---------------------------------------------------------------------------
// Validators / helpers
// ---------------------------------------------------------------------------

fn slug_validator(
) -> impl Fn(&str) -> Result<inquire::validator::Validation, inquire::CustomUserError> + Clone + 'static
{
    use inquire::validator::Validation;
    |s: &str| {
        let re = regex::Regex::new(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$").unwrap();
        if re.is_match(s) {
            Ok(Validation::Valid)
        } else {
            Ok(Validation::Invalid(
                "slug must be lowercase, ≤63 chars, [a-z0-9-]".into(),
            ))
        }
    }
}

fn https_url_validator(
) -> impl Fn(&str) -> Result<inquire::validator::Validation, inquire::CustomUserError> + Clone + 'static
{
    use inquire::validator::Validation;
    |s: &str| {
        if s.starts_with("https://") && s.len() > "https://".len() {
            Ok(Validation::Valid)
        } else {
            Ok(Validation::Invalid(
                "endpoint_url must start with https:// (the platform never connects to plaintext)"
                    .into(),
            ))
        }
    }
}

fn int_range_validator(
    min: i64,
    max: i64,
) -> impl Fn(&str) -> Result<inquire::validator::Validation, inquire::CustomUserError> + Clone + 'static
{
    use inquire::validator::Validation;
    move |s: &str| match s.trim().parse::<i64>() {
        Ok(n) if n >= min && n <= max => Ok(Validation::Valid),
        Ok(_) => Ok(Validation::Invalid(
            format!("must be an integer in {min}..={max}").into(),
        )),
        Err(_) => Ok(Validation::Invalid("must be an integer".into())),
    }
}

fn prompt_err(e: inquire::InquireError) -> OlError {
    OlError::new(OL_4210_SCHEMA_MISMATCH, format!("prompt: {e}"))
}

// ---------------------------------------------------------------------------
// Manifest write
// ---------------------------------------------------------------------------

fn write_manifest_value(path: &Path, value: &serde_json::Value) -> Result<(), OlError> {
    let yaml = serde_yaml::to_string(value).map_err(|e| {
        OlError::new(
            OL_4274_MANIFEST_WRITE_FAILED,
            format!("serialise manifest: {e}"),
        )
    })?;
    write_manifest(path, yaml.as_bytes())
}

fn write_manifest(path: &Path, bytes: &[u8]) -> Result<(), OlError> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| {
            OlError::new(
                OL_4274_MANIFEST_WRITE_FAILED,
                format!("create parent {}: {e}", parent.display()),
            )
        })?;
    }
    let tmp = path.with_extension("yaml.tmp");
    std::fs::write(&tmp, bytes).map_err(|e| {
        OlError::new(
            OL_4274_MANIFEST_WRITE_FAILED,
            format!("write {}: {e}", tmp.display()),
        )
    })?;
    std::fs::rename(&tmp, path).map_err(|e| {
        OlError::new(
            OL_4274_MANIFEST_WRITE_FAILED,
            format!("rename {}: {e}", path.display()),
        )
    })
}

// ---------------------------------------------------------------------------
// Auth + telemetry consent (existing; unchanged)
// ---------------------------------------------------------------------------

async fn ensure_logged_in(out: &OutputConfig, g: &GlobalArgs) -> Result<(), OlError> {
    if let Some(identity) = super::auth::current_identity().await {
        let email = identity.email.as_deref().unwrap_or("?");
        let org = identity
            .organization_name
            .as_deref()
            .filter(|s| !s.is_empty())
            .unwrap_or("(no org)");
        out.print_step(&format!("Already authenticated as {email} ({org})"));
        return Ok(());
    }

    // Mandatory auth in v1 — non-interactive callers MUST provide a token.
    // The pre-flight slug-validate calls hard-depend on a working bearer.
    if !out.interactive {
        return Err(OlError::new(
            OL_4232_BACKEND_UNAUTHORIZED,
            "init requires authentication; set OPENLATCH_TOKEN or run \
             `openlatch-provider login` first",
        )
        .with_suggestion(
            "In CI: provide OPENLATCH_TOKEN. Locally: run `openlatch-provider login` once.",
        ));
    }

    super::auth::login(
        g,
        super::auth::LoginArgs {
            token_file: None,
            auth_url: None,
        },
    )
    .await
}

// ---------------------------------------------------------------------------
// Pre-flight slug validation helpers
// ---------------------------------------------------------------------------

/// Slugs the user already owns when re-running `init --force` over an
/// existing manifest. Validation is skipped for these to avoid "I just
/// claimed it last time" false positives.
#[derive(Debug, Default, Clone)]
struct OwnedSlugs {
    editor: Option<String>,
    tools: BTreeSet<String>,
    providers: BTreeSet<String>,
}

impl OwnedSlugs {
    fn editor_matches(&self, slug: &str) -> bool {
        self.editor.as_deref() == Some(slug)
    }
    fn owns_tool(&self, slug: &str) -> bool {
        self.tools.contains(slug)
    }
    fn owns_provider(&self, slug: &str) -> bool {
        self.providers.contains(slug)
    }
}

/// Best-effort: read the existing `<slug>.yaml` so we know which slugs the
/// user already owns when re-running `init --force`. Failure to read is
/// non-fatal — we just fall back to validating every slug.
fn owned_slugs_from_existing(args: &InitArgs) -> OwnedSlugs {
    let Some(slug) = args.editor_slug.as_deref() else {
        return OwnedSlugs::default();
    };
    let path = config::manifest_path_for_slug(slug);
    if !path.exists() {
        return OwnedSlugs::default();
    }
    let Ok(m) = manifest::load(&path) else {
        return OwnedSlugs::default();
    };
    OwnedSlugs {
        editor: Some((*m.editor.slug).to_string()),
        tools: m.tools.iter().map(|t| (*t.slug).to_string()).collect(),
        providers: m.providers.iter().map(|p| (*p.slug).to_string()).collect(),
    }
}

async fn check_editor_slug(
    client: Option<&ApiClient>,
    slug: &str,
    owned: &OwnedSlugs,
) -> Result<(), OlError> {
    if owned.editor_matches(slug) {
        return Ok(());
    }
    let Some(c) = client else { return Ok(()) };
    api_editor::validate_editor_slug(c, slug).await
}

async fn check_tool_slug(
    client: Option<&ApiClient>,
    slug: &str,
    owned: &OwnedSlugs,
) -> Result<(), OlError> {
    if owned.owns_tool(slug) {
        return Ok(());
    }
    let Some(c) = client else { return Ok(()) };
    let body = json!({ "slug": slug });
    api_editor::validate_tool(c, &body).await
}

async fn check_provider_slug(
    client: Option<&ApiClient>,
    slug: &str,
    owned: &OwnedSlugs,
) -> Result<(), OlError> {
    if owned.owns_provider(slug) {
        return Ok(());
    }
    let Some(c) = client else { return Ok(()) };
    let body = json!({ "slug": slug });
    api_editor::validate_provider(c, &body).await
}

/// Non-TTY editor-slug validation: collisions become terminal errors with
/// the structured `OL-4282` code. (TTY callers loop in the prompt itself.)
async fn validate_editor_slug_or_error(
    client: Option<&ApiClient>,
    slug: &str,
    owned: &OwnedSlugs,
) -> Result<(), OlError> {
    if slug.is_empty() {
        return Ok(());
    }
    check_editor_slug(client, slug, owned).await
}

fn handle_consent(out: &OutputConfig, args: &InitArgs) -> Result<(), OlError> {
    let consent_path = crate::config::provider_dir().join("telemetry.json");

    // Explicit flag wins.
    if args.telemetry {
        return crate::telemetry::consent_file::write_consent(&consent_path, true);
    }
    if args.no_telemetry {
        return crate::telemetry::consent_file::write_consent(&consent_path, false);
    }

    // Already decided? respect prior choice.
    if let Ok(Some(_)) = crate::telemetry::consent_file::read_consent(&consent_path) {
        return Ok(());
    }

    // CI / non-interactive → write disabled-by-default; user can flip via
    // `config set telemetry.enabled true`.
    if !out.interactive {
        return crate::telemetry::consent_file::write_consent(&consent_path, false);
    }

    use inquire::Confirm;
    let answer = Confirm::new(
        "Send anonymous usage telemetry to PostHog (EU)? See \
         https://docs.openlatch.ai/telemetry for what's collected.",
    )
    .with_default(true)
    .prompt()
    .map_err(|e| OlError::new(OL_4263_CONSENT_WRITE_FAILED, format!("consent prompt: {e}")))?;
    crate::telemetry::consent_file::write_consent(&consent_path, answer)
}