difflore-cli 0.1.0

Your AI coding agent, taught by your team's PR reviews — a local-first, open-source MCP server that turns past review comments into rules your agent follows automatically.
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
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
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
use std::io::{self, IsTerminal, Write};
use std::sync::{
    Arc,
    atomic::{AtomicU8, Ordering},
};
use std::time::{Duration, Instant};

use crate::style::{self, sym};

/// Filename of the sentinel under `~/.difflore/` that records a user has
/// already seen the first-run welcome. Bare `difflore` checks for it
/// before deciding whether to print the screen below.
const SENTINEL: &str = "welcomed";
const SENTINEL_VERSION: &str = "welcome-v2";

/// Filename of the resume marker. Written by Step 4 when cloud extraction
/// is taking longer than the user is willing to wait. Presence means:
/// "import is queued upstream, baseline rule count was N at time T —
/// re-running `difflore` should jump back to Step 4 with that baseline
/// instead of restarting the whole flow." Removed once a wizard
/// completes successfully (`mark_welcomed`) or the user explicitly resets.
const RESUME_SENTINEL: &str = "wizard_resume";
const RESUME_SENTINEL_VERSION: &str = "wizard-resume-v2";

/// Soft offer-out: at this elapsed mark we ask the user whether to keep
/// waiting or finish now and resume later. Tunable, not user-facing.
const SOFT_CAP: Duration = Duration::from_secs(60);

/// Hard cap: we never block the wizard longer than this even if the user
/// keeps saying "wait more". Past this, fall through to the resume hint
/// unconditionally.
const HARD_CAP: Duration = Duration::from_secs(180);

/// Heartbeat cadence — how often Step 4 reprints the elapsed line so the
/// user sees the wait isn't frozen. Each tick also re-polls cloud.
const POLL_INTERVAL: Duration = Duration::from_secs(5);

const DEFAULT_IMPORT_MAX_PRS: usize = 50;
const MIN_IMPORT_MAX_PRS: usize = 1;
const MAX_IMPORT_MAX_PRS: usize = 1000;

/// First-run state machine, per the CLI Command Interaction Redesign:
///
/// ```text
/// Brand-new user, zero rules, no cloud login, sentinel missing
///   -> launch interactive wizard (collapses 4-bounce onboarding)
/// New machine, no welcome sentinel, but not fresh
///   -> show static welcome screen, then drop into the TUI
/// Returning user / opted out
///   -> stay silent and let the TUI path emit its own drift hint
/// ```
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub(crate) enum FirstRunPath {
    /// New machine + interactive — run the chained wizard, then TUI.
    LaunchWizard,
    /// New machine but non-interactive — print static welcome, then TUI.
    ShowWelcome,
    /// Either a returning user (sentinel exists) or a non-TTY context.
    /// The TUI path handles its own drift hint; we do nothing here.
    Skip,
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub(crate) enum WelcomeFlow {
    ContinueTui,
    Stop,
}

impl WelcomeFlow {
    pub(crate) const fn should_continue_tui(self) -> bool {
        matches!(self, Self::ContinueTui)
    }
}

/// Inputs for [`should_launch_wizard`]. Pulled out of the env-sniffing
/// branches so unit tests can supply deterministic fixtures.
#[derive(Debug, Clone, Copy)]
pub(crate) struct WizardSignals {
    pub stdin_is_tty: bool,
    pub stdout_is_tty: bool,
    pub no_interactive_flag: bool,
    pub no_welcome_env: bool,
    pub sentinel_exists: bool,
    pub local_rules_count: usize,
    pub cloud_logged_in: bool,
}

/// Pure decision: should the chained wizard run?
///
/// All four "skip" rails (CI flag, pipe, env opt-out, returning user)
/// short-circuit before the first-run criteria are checked so a user who
/// already onboarded is never pulled back into the wizard.
pub(crate) const fn should_launch_wizard(s: WizardSignals) -> bool {
    if s.no_interactive_flag {
        return false;
    }
    if !s.stdin_is_tty || !s.stdout_is_tty {
        return false;
    }
    if s.no_welcome_env {
        return false;
    }
    if s.sentinel_exists {
        return false;
    }
    // First-run criteria: any single one is enough that the user
    // hasn't gotten value out of the product yet.
    s.local_rules_count == 0 && !s.cloud_logged_in
}

#[derive(Debug, Clone, Copy)]
struct FirstRunPreflight {
    stdout_is_tty: bool,
    no_interactive_flag: bool,
    no_welcome_env: bool,
    sentinel_exists: bool,
    resume_pending: bool,
}

/// Fast rails that never need DB / cloud probing. Keeping these separate
/// prevents bare `difflore` from paying `CommandContext::new` latency for
/// returning users, opted-out users, or pending resume markers.
const fn preflight_first_run_path(s: FirstRunPreflight) -> Option<FirstRunPath> {
    if !s.stdout_is_tty || s.no_interactive_flag || s.no_welcome_env {
        return Some(FirstRunPath::Skip);
    }
    if s.sentinel_exists && !s.resume_pending {
        return Some(FirstRunPath::Skip);
    }
    if s.resume_pending {
        return Some(FirstRunPath::LaunchWizard);
    }
    None
}

/// Decide which first-run path bare `difflore` should take.
///
/// The suppression rails are intentionally ordered before the DB/cloud
/// sniff: non-TTY, explicit no-interactive, env opt-out, then sentinels.
pub(crate) async fn first_run_path(no_interactive_flag: bool) -> FirstRunPath {
    let stdout_tty = io::stdout().is_terminal();
    let stdin_tty = io::stdin().is_terminal();
    if !stdout_tty || no_interactive_flag {
        return FirstRunPath::Skip;
    }
    let no_welcome_env = difflore_core::env::flag_set(difflore_core::env::DIFFLORE_NO_WELCOME);
    if no_welcome_env {
        return FirstRunPath::Skip;
    }
    let Ok(dir) = difflore_core::paths::data_home() else {
        return FirstRunPath::Skip;
    };
    let sentinel_exists = sentinel_version_current(&dir.join(SENTINEL), SENTINEL_VERSION);
    let resume_pending =
        sentinel_version_current(&dir.join(RESUME_SENTINEL), RESUME_SENTINEL_VERSION);
    if let Some(path) = preflight_first_run_path(FirstRunPreflight {
        stdout_is_tty: stdout_tty,
        no_interactive_flag,
        no_welcome_env,
        sentinel_exists,
        resume_pending,
    }) {
        return path;
    }

    // Probe the same signals init.rs uses so wizard / static welcome
    // share the same definition of "fresh install".
    let (rules_count, cloud_logged_in) = sniff_first_run_state().await;

    let signals = WizardSignals {
        stdin_is_tty: stdin_tty,
        stdout_is_tty: stdout_tty,
        no_interactive_flag,
        no_welcome_env: false,
        sentinel_exists: false,
        local_rules_count: rules_count,
        cloud_logged_in,
    };

    if should_launch_wizard(signals) {
        FirstRunPath::LaunchWizard
    } else {
        FirstRunPath::ShowWelcome
    }
}

/// Reuse init.rs's queries so wizard's "is this user fresh" matches the
/// dashboard's idea of fresh exactly. Failures degrade to "fresh".
async fn sniff_first_run_state() -> (usize, bool) {
    // `first_run_path` runs once per process before dispatch, so we
    // build the context locally rather than threading one through the
    // pre-dispatch pipeline. Subsequent commands re-init their own.
    let ctx = crate::runtime::CommandContext::new(crate::runtime::OutputMode::Text).await;
    let rules = match difflore_core::skills::stats(&ctx.db).await {
        Ok(s) => s.total as usize,
        Err(_) => 0,
    };
    let logged_in = ctx.cloud().await.is_logged_in();
    (rules, logged_in)
}

/// Print the first-run welcome screen and mark the sentinel.
///
/// Non-blocking: the TUI launches afterwards no matter what the user
/// types. The screen exists to set expectations — without `init`, the
/// product's headline promise (review memory recalled by your AI agent
/// before it codes) cannot fire, and the empty TUI dashboard alone hides
/// that.
pub(crate) async fn show_welcome_then_continue() -> WelcomeFlow {
    let cloud_logged_in = difflore_core::cloud::client::CloudClient::create()
        .await
        .is_logged_in();
    let import_cmd = static_welcome_import_command(cloud_logged_in);
    let wordmark = style::wordmark();
    let rule = style::pewter(style::DIVIDER);
    let tip = style::emerald(sym::TIP);

    println!();
    println!("  {wordmark}");
    println!("  {rule}");
    println!(
        "  DiffLore helps Claude, Codex, Cursor, and local agents remember team review judgment."
    );
    println!("  Fewer repeated review comments, fewer redo loops.");
    println!();
    println!("  {tip} See it work right now — no repo, no setup:");
    println!(
        "        {}   a live recall on a bundled sample edit (5 seconds)",
        style::cmd("difflore try"),
    );
    println!();
    println!("  {tip} Then make it real on your repo:");
    println!(
        "        1. {} install once: wire agents and pick a provider",
        style::cmd("difflore init"),
    );
    println!(
        "        2. {}  {}",
        style::cmd(import_cmd),
        if cloud_logged_in {
            "queue cloud extraction from PR comments"
        } else {
            "create local memories from PR comments"
        },
    );
    println!(
        "        3. {}   show what your AI agents would recall on a real diff",
        style::cmd("difflore recall --diff"),
    );
    println!(
        "        4. {}        prove recall, MCP serve, and local value",
        style::cmd("difflore status"),
    );
    println!(
        "        {} Cloud adds managed extraction, sync, governance, and impact proof.",
        style::pewter(sym::BULLET),
    );
    println!();
    println!(
        "  {} press {} to show local memory status ({} won't show again)",
        style::pewter(sym::BULLET),
        style::cmd("Enter"),
        style::pewter("this message"),
    );
    print!("  > ");
    let _ = io::stdout().flush();
    let mut buf = String::new();
    let _ = io::stdin().read_line(&mut buf);

    mark_welcomed();
    WelcomeFlow::ContinueTui
}

const fn static_welcome_import_command(cloud_logged_in: bool) -> &'static str {
    if cloud_logged_in {
        "difflore import-reviews --max-prs 50 --upload"
    } else {
        "difflore import-reviews --max-prs 50"
    }
}

/// Run the chained 5-step onboarding wizard.
///
/// Each step is independently skippable (`n` answers bail out cleanly
/// with a `difflore init` bridge) so a user who only wants part of the
/// flow never gets trapped.
pub(crate) async fn run_wizard() -> WelcomeFlow {
    let resume = difflore_core::paths::data_home().ok().is_some_and(|dir| {
        sentinel_version_current(&dir.join(RESUME_SENTINEL), RESUME_SENTINEL_VERSION)
    });
    run_wizard_with_interrupt(resume).await
}

/// Step return signal. `Continue` advances to the next step;
/// `BailWelcomed` means the step already called `finish_with_bridge`
/// (which marks welcomed) and the wizard should exit silently;
/// `BailResumeLater` means the resume marker is set and the wizard
/// should exit without marking welcomed.
enum StepFlow {
    Continue,
    BailWelcomed,
    BailResumeLater,
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
enum Step4Mode {
    CloudExtraction,
    LocalBridge,
}

#[derive(Default)]
struct WizardState {
    detected_repo: Option<String>,
    cloud_logged_in: bool,
    used_cloud_import: bool,
    cloud_rule_baseline: Option<i32>,
    local_import_ready: bool,
    import_recovery_needed: bool,
    import_max_prs: usize,
}

impl WizardState {
    fn new() -> Self {
        Self {
            import_max_prs: DEFAULT_IMPORT_MAX_PRS,
            ..Self::default()
        }
    }
}

const fn step4_mode(state: &WizardState) -> Step4Mode {
    if state.used_cloud_import {
        Step4Mode::CloudExtraction
    } else {
        Step4Mode::LocalBridge
    }
}

const INTERRUPT_MARK_WELCOMED: u8 = 0;
const INTERRUPT_WRITE_RESUME: u8 = 1;

#[derive(Clone, Default)]
struct WizardInterrupt {
    action: Arc<AtomicU8>,
}

impl WizardInterrupt {
    fn mark_welcomed_on_interrupt(&self) {
        self.action
            .store(INTERRUPT_MARK_WELCOMED, Ordering::Relaxed);
    }

    fn write_resume_on_interrupt(&self) {
        self.action.store(INTERRUPT_WRITE_RESUME, Ordering::Relaxed);
    }

    fn should_write_resume(&self) -> bool {
        self.action.load(Ordering::Relaxed) == INTERRUPT_WRITE_RESUME
    }
}

async fn run_wizard_with_interrupt(resume: bool) -> WelcomeFlow {
    let interrupt = WizardInterrupt::default();
    tokio::select! {
        flow = run_wizard_inner(resume, interrupt.clone()) => flow,
        _ = tokio::signal::ctrl_c() => {
            handle_wizard_interrupt(&interrupt);
            WelcomeFlow::Stop
        }
    }
}

fn handle_wizard_interrupt(interrupt: &WizardInterrupt) {
    println!();
    println!("  {} Setup interrupted.", style::amber(sym::WARN));
    if interrupt.should_write_resume() {
        write_resume_marker();
        println!(
            "  {} Saved your cloud extraction checkpoint; resume with {}.",
            style::pewter(sym::BULLET),
            style::cmd("difflore"),
        );
    } else {
        mark_welcomed();
        println!(
            "  {} Saved the first-run decision; continue later with {}.",
            style::pewter(sym::BULLET),
            style::cmd("difflore init"),
        );
    }
}

async fn run_wizard_inner(resume: bool, interrupt: WizardInterrupt) -> WelcomeFlow {
    print_wizard_header(resume);

    let mut state = WizardState::new();

    if resume {
        println!(
            "  {} Steps 1-3 already done in the previous session.",
            style::emerald(sym::OK),
        );
        state.used_cloud_import = true;
        interrupt.write_resume_on_interrupt();
    } else {
        interrupt.mark_welcomed_on_interrupt();
        match step1_repo_confirm(&mut state).await {
            StepFlow::Continue => {}
            StepFlow::BailWelcomed | StepFlow::BailResumeLater => return WelcomeFlow::Stop,
        }
        match step2_login(&mut state).await {
            StepFlow::Continue => {}
            StepFlow::BailWelcomed | StepFlow::BailResumeLater => return WelcomeFlow::Stop,
        }
        match step3_import(&mut state).await {
            StepFlow::Continue => {}
            StepFlow::BailWelcomed | StepFlow::BailResumeLater => return WelcomeFlow::Stop,
        }
    }

    match step4_mode(&state) {
        Step4Mode::CloudExtraction => {
            interrupt.write_resume_on_interrupt();
            match step4_wait(state.cloud_rule_baseline).await {
                StepFlow::Continue => {}
                StepFlow::BailWelcomed | StepFlow::BailResumeLater => return WelcomeFlow::Stop,
            }

            interrupt.mark_welcomed_on_interrupt();
            step5_recall().await;
        }
        Step4Mode::LocalBridge => {
            step4_local_candidate_bridge(
                state.local_import_ready,
                state.import_recovery_needed,
                state.import_max_prs,
            );
        }
    }

    println!();
    println!(
        "  {} DiffLore is wired. Run `difflore status` any time to see the next best memory step.",
        style::emerald(sym::OK),
    );

    mark_welcomed();
    WelcomeFlow::ContinueTui
}

fn print_wizard_header(resume: bool) {
    let wordmark = style::wordmark();
    let rule = style::pewter(style::DIVIDER);

    println!();
    if resume {
        println!("  {wordmark}  resuming setup");
    } else {
        println!("  {wordmark}  setup wizard");
    }
    println!("  {rule}");
    if resume {
        println!("  Picking up where we left off — checking on cloud extraction.");
    } else {
        println!("  Five quick questions to wire DiffLore into your repo.");
        println!(
            "  {} skip any step with {} — you can resume with {}",
            style::pewter(sym::BULLET),
            style::cmd("n"),
            style::cmd("difflore"),
        );
        if io::stdout().is_terminal() {
            println!(
                "  {}",
                style::pewter("Tip: skip this with `difflore --no-interactive` (CI / scripts)."),
            );
        }
    }
    println!();
}

async fn step1_repo_confirm(state: &mut WizardState) -> StepFlow {
    state.detected_repo = detect_repo_label();
    let repo_label = state.detected_repo.as_deref().unwrap_or("this repo");
    let q1 = format!(
        "Step 1/5  Detected: {}. Use this as your first source?",
        style::ident(repo_label),
    );
    if !prompt_yes(&q1).await {
        finish_with_bridge("OK — you can wire a different repo later with `difflore init`.");
        return StepFlow::BailWelcomed;
    }
    StepFlow::Continue
}

async fn step2_login(state: &mut WizardState) -> StepFlow {
    let cloud_client = difflore_core::cloud::client::CloudClient::create().await;
    if cloud_client.is_logged_in() {
        println!(
            "  {} Step 2/5  Already logged in to DiffLore Cloud.",
            style::emerald(sym::OK),
        );
        state.cloud_logged_in = true;
        return StepFlow::Continue;
    }
    let q2 =
        "Step 2/5  Connect to DiffLore Cloud for managed extraction and team proof?".to_owned();
    if !prompt_yes(&q2).await {
        println!(
            "  {} Staying local — the CLI can still draft candidates and recall accepted rules.",
            style::pewter(sym::BULLET),
        );
        state.cloud_logged_in = false;
        return StepFlow::Continue;
    }
    if let Err(e) = crate::commands::cloud::try_login_dispatch(None, true).await {
        println!();
        println!(
            "  {} Cloud login did not finish: {e}",
            style::amber(sym::WARN),
        );
        println!(
            "  {} Continuing locally so first-run setup still proves value.",
            style::pewter(sym::BULLET),
        );
        println!(
            "  {} Later: {} then {}",
            style::pewter(sym::BULLET),
            style::cmd("difflore cloud login"),
            style::cmd("difflore import-reviews --upload"),
        );
        state.cloud_logged_in = false;
        return StepFlow::Continue;
    }
    let refreshed = difflore_core::cloud::client::CloudClient::create().await;
    state.cloud_logged_in = refreshed.is_logged_in();
    StepFlow::Continue
}

async fn step3_import(state: &mut WizardState) -> StepFlow {
    let from_label = state.detected_repo.as_deref().unwrap_or("upstream");
    let import_label = if state.cloud_logged_in {
        "Import PR review history with Cloud extraction from"
    } else {
        "Draft local candidates from PR review history in"
    };
    let q3 = format!("Step 3/5  {import_label} {}?", style::ident(from_label));
    println!(
        "  {} Preview first any time with {}.",
        style::pewter(sym::BULLET),
        style::cmd("difflore import-reviews --dry-run"),
    );
    if !prompt_yes(&q3).await {
        finish_with_bridge(
            "OK — you can import later with `difflore import-reviews --max-prs 50`.",
        );
        return StepFlow::BailWelcomed;
    }
    let Some(max_prs) = prompt_import_depth(DEFAULT_IMPORT_MAX_PRS).await else {
        finish_with_bridge(
            "OK — import was not started. Resume later with `difflore import-reviews --dry-run`.",
        );
        return StepFlow::BailWelcomed;
    };
    state.import_max_prs = max_prs;
    println!(
        "  {} Using {}; import progress prints fetched PR/comment counts as it runs.",
        style::pewter(sym::BULLET),
        style::cmd(&format!("--max-prs {max_prs}")),
    );
    state.used_cloud_import = state.cloud_logged_in;
    if state.used_cloud_import {
        state.cloud_rule_baseline = capture_cloud_rule_count().await;
    }
    let ctx = crate::runtime::CommandContext::new(crate::runtime::OutputMode::Text).await;
    let result = crate::commands::import_reviews::try_handle(
        &ctx,
        crate::commands::import_reviews::ImportArgs {
            repo: None,
            from_upstream: None,
            max_prs,
            pr_numbers: Vec::new(),
            exclude_prs: Vec::new(),
            since: None,
            include_open: false,
            upload: state.used_cloud_import,
            dry_run: false,
            json: false,
        },
    )
    .await;
    match result {
        Ok(outcome) => {
            if state.used_cloud_import && !outcome.cloud_upload_queued {
                println!(
                    "  {} No cloud extraction was queued, so setup will stay on the local path.",
                    style::pewter(sym::BULLET),
                );
                state.used_cloud_import = false;
            }
            state.local_import_ready = !state.used_cloud_import;
            StepFlow::Continue
        }
        Err(e) => {
            println!();
            println!(
                "  {} Step 3 import could not finish.",
                style::amber(sym::WARN)
            );
            println!("{e}");
            println!(
                "  {} Recovery: run {} after GitHub auth/rate limits are clear.",
                style::pewter(sym::BULLET),
                style::cmd("difflore import-reviews --dry-run"),
            );
            println!(
                "  {} Then run {} to draft local memory candidates.",
                style::pewter(sym::BULLET),
                style::cmd(&format!("difflore import-reviews --max-prs {max_prs}")),
            );
            state.used_cloud_import = false;
            state.local_import_ready = false;
            state.import_recovery_needed = true;
            StepFlow::Continue
        }
    }
}

fn step4_local_candidate_bridge(
    local_import_ready: bool,
    import_recovery_needed: bool,
    max_prs: usize,
) {
    println!();
    if local_import_ready {
        println!("  Step 4/5  Local memories are ready.");
        println!(
            "  {} Preview what agents can recall now:",
            style::pewter(sym::BULLET),
        );
        println!("    {}", style::cmd("difflore recall --diff"));
    } else if import_recovery_needed {
        println!("  Step 4/5  Import is paused; your setup progress is still saved.");
        println!(
            "  {} First recover GitHub access and preview the import:",
            style::pewter(sym::BULLET),
        );
        println!("    {}", style::cmd("gh auth login"));
        println!("    {}", style::cmd("difflore import-reviews --dry-run"));
        println!(
            "  {} Then create local memories:",
            style::pewter(sym::BULLET),
        );
        println!(
            "    {}",
            style::cmd(&format!("difflore import-reviews --max-prs {max_prs}")),
        );
    } else {
        println!("  Step 4/5  Staying local.");
        println!(
            "  {} Start with a preview, then create local memories:",
            style::pewter(sym::BULLET),
        );
        println!("    {}", style::cmd("difflore import-reviews --dry-run"));
        println!(
            "    {}",
            style::cmd(&format!("difflore import-reviews --max-prs {max_prs}")),
        );
    }
    println!(
        "  {} Then run {} to prove the agent recall path on this repo.",
        style::pewter(sym::BULLET),
        style::cmd("difflore recall --diff"),
    );
}

async fn step4_wait(baseline: Option<i32>) -> StepFlow {
    println!();
    println!("  Step 4/5  Waiting for cloud extraction (usually 10-60s, occasionally longer)…");
    match wait_for_extraction_tolerant(SOFT_CAP, HARD_CAP, 1, baseline).await {
        ExtractionOutcome::Done { pulled } => {
            println!(
                "  {} Pulled {pulled} rules from cloud.",
                style::emerald(sym::OK),
            );
            clear_resume_marker();
            StepFlow::Continue
        }
        ExtractionOutcome::ResumeLater { pulled, elapsed } => {
            println!();
            println!(
                "  {} Extraction is taking longer than usual ({}s elapsed, {pulled} rules so far).",
                style::pewter(sym::BULLET),
                elapsed.as_secs(),
            );
            println!(
                "  {} Your import is still running on the cloud — we've saved your progress.",
                style::pewter(sym::BULLET),
            );
            println!(
                "  {} Resume any time with {} (or just re-run {}).",
                style::pewter(sym::BULLET),
                style::cmd("difflore"),
                style::cmd("difflore"),
            );
            write_resume_marker();
            StepFlow::BailResumeLater
        }
    }
}

async fn step5_recall() {
    println!();
    println!("  Step 5/5  Showing what your AI agents will recall on the current diff:");
    let ctx = crate::runtime::CommandContext::new(crate::runtime::OutputMode::Text).await;
    crate::commands::recall::handle_recall(
        &ctx,
        crate::commands::recall::RecallArgs {
            intent: None,
            file: None,
            diff: true,
            top_k: 3,
            json: false,
            verbose: false,
            copy: false,
        },
    )
    .await;
}

/// Outcome of [`wait_for_extraction_tolerant`]. `Done` means we hit the
/// rule threshold (or surfaced a non-zero pull at the soft cap and the
/// user accepted it). `ResumeLater` means the user opted out at the soft
/// cap, or the hard cap fired with no rules — caller writes the resume
/// marker and prints the bridge.
enum ExtractionOutcome {
    Done { pulled: i32 },
    ResumeLater { pulled: i32, elapsed: Duration },
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
enum HeartbeatMode {
    InlineRewrite,
    PlainLines,
}

const fn heartbeat_mode(stdout_is_tty: bool, term_is_dumb: bool) -> HeartbeatMode {
    if stdout_is_tty && !term_is_dumb {
        HeartbeatMode::InlineRewrite
    } else {
        HeartbeatMode::PlainLines
    }
}

fn current_heartbeat_mode() -> HeartbeatMode {
    let term_is_dumb = difflore_core::env::var(difflore_core::env::TERM)
        .is_some_and(|term| term.eq_ignore_ascii_case("dumb"));
    heartbeat_mode(io::stdout().is_terminal(), term_is_dumb)
}

fn print_extraction_heartbeat(mode: HeartbeatMode, elapsed: Duration, delta: i32) {
    let line = format!(
        "{}s elapsed, {delta} rules pulled, still extracting",
        elapsed.as_secs(),
    );
    match mode {
        HeartbeatMode::InlineRewrite => {
            print!("\r{line}     ");
            let _ = io::stdout().flush();
        }
        HeartbeatMode::PlainLines => {
            println!("{line}");
        }
    }
}

// TODO(wave5): wrap (soft_cap, hard_cap, min_rules) into a `WaitConfig`
// struct if a second caller appears. Today there's only one call site
// in `step4_wait` and the 3-arg signature is still under the clippy
// threshold, so the struct would be cosmetic churn.
/// Tolerant Step-4 polling loop:
/// - Heartbeat line every `POLL_INTERVAL` showing elapsed seconds and
///   running delta. Replaces the silent spinner; the user always knows
///   the wait isn't frozen.
/// - At `soft_cap` we stop and ask: keep waiting, or finish + resume.
/// - `hard_cap` is the absolute ceiling — past it the answer is forced
///   to "resume later" no matter what.
/// - Returns `Done` as soon as the rule delta meets `min_rules`.
async fn wait_for_extraction_tolerant(
    soft_cap: Duration,
    hard_cap: Duration,
    min_rules: i32,
    baseline: Option<i32>,
) -> ExtractionOutcome {
    let client = difflore_core::cloud::client::CloudClient::create().await;
    if !client.is_logged_in() {
        // Nothing we can poll. Treat as resume-later so the user gets
        // the bridge text instead of a confusing silent success.
        return ExtractionOutcome::ResumeLater {
            pulled: 0,
            elapsed: Duration::ZERO,
        };
    }
    let baseline = match baseline {
        Some(value) => Some(value),
        None => difflore_core::cloud::sync::sync_team_skills(&client)
            .await
            .ok()
            .map(|team| team.visible_count)
            .filter(|value| *value == 0),
    };
    let start = Instant::now();
    let mut soft_offered = false;
    let heartbeat = current_heartbeat_mode();
    loop {
        let elapsed = start.elapsed();
        let now = difflore_core::cloud::sync::sync_team_skills(&client)
            .await
            .map_or_else(|_| baseline.unwrap_or(0), |team| team.visible_count);
        let delta = extraction_delta(now, baseline);

        if delta >= min_rules {
            println!();
            return ExtractionOutcome::Done { pulled: delta };
        }

        if elapsed >= hard_cap {
            println!();
            return ExtractionOutcome::ResumeLater {
                pulled: delta,
                elapsed,
            };
        }

        if !soft_offered && elapsed >= soft_cap {
            soft_offered = true;
            println!();
            let q = format!(
                "  Still waiting after {}s ({delta} rules so far). Keep waiting up to {}s more?",
                elapsed.as_secs(),
                (hard_cap.saturating_sub(elapsed)).as_secs(),
            );
            if !prompt_yes(&q).await {
                return ExtractionOutcome::ResumeLater {
                    pulled: delta,
                    elapsed,
                };
            }
            // User opted to keep waiting — fall through to next poll.
        } else {
            print_extraction_heartbeat(heartbeat, elapsed, delta);
        }

        tokio::time::sleep(POLL_INTERVAL).await;
    }
}

async fn capture_cloud_rule_count() -> Option<i32> {
    let client = difflore_core::cloud::client::CloudClient::create().await;
    if !client.is_logged_in() {
        return None;
    }
    difflore_core::cloud::sync::sync_team_skills(&client)
        .await
        .map(|team| team.visible_count)
        .ok()
}

fn extraction_delta(current_count: i32, baseline: Option<i32>) -> i32 {
    match baseline {
        Some(baseline) => (current_count - baseline).max(0),
        None => current_count.max(0),
    }
}

async fn prompt_import_depth(default: usize) -> Option<usize> {
    print!(
        "  {} How far back? {} ",
        style::emerald(sym::TIP),
        style::pewter(&format!(
            "PR limit [{default}] (20 quick, 50 recommended, 100 deeper)"
        )),
    );
    let _ = io::stdout().flush();
    let stdin_is_tty = io::stdin().is_terminal();
    let Some(buf) = read_prompt_line().await else {
        println!();
        return None;
    };

    let answer = clean_prompt_answer(&buf);
    if answer.is_empty() && !stdin_is_tty {
        println!();
        return None;
    }

    match parse_import_depth_answer(&answer, default) {
        Ok(max_prs) => Some(max_prs),
        Err(e) => {
            println!(
                "  {} {e}; using {}.",
                style::amber(sym::WARN),
                style::cmd(&format!("--max-prs {default}")),
            );
            Some(default)
        }
    }
}

fn parse_import_depth_answer(answer: &str, default: usize) -> Result<usize, String> {
    let cleaned = clean_prompt_answer(answer);
    if cleaned.is_empty() {
        return Ok(default);
    }
    let parsed = cleaned
        .parse::<usize>()
        .map_err(|_| format!("{answer:?} is not a number"))?;
    if !(MIN_IMPORT_MAX_PRS..=MAX_IMPORT_MAX_PRS).contains(&parsed) {
        return Err(format!(
            "--max-prs must be between {MIN_IMPORT_MAX_PRS} and {MAX_IMPORT_MAX_PRS}"
        ));
    }
    Ok(parsed)
}

fn detect_repo_label() -> Option<String> {
    if let Ok(cwd) = std::env::current_dir() {
        if let Some(repo) =
            difflore_core::git::detect_github_repo_full_names(&cwd.to_string_lossy())
                .into_iter()
                .next()
        {
            return Some(repo);
        }
    }
    let url = crate::commands::util::git_str(&["config", "--get", "remote.origin.url"])?;
    if url.is_empty() {
        return None;
    }
    crate::commands::init::parse_owner_repo_from_url(&url).or(Some(url))
}

/// Render `[Y/n]` prompt with default-yes semantics. Empty lines or any
/// non-`n` answer count as yes; EOF/read errors bail out instead of
/// opting a non-interactive caller into browser/network work.
async fn prompt_yes(question: &str) -> bool {
    print!(
        "  {} {} {} ",
        style::emerald(sym::TIP),
        question,
        style::pewter("[Y/n]"),
    );
    let _ = io::stdout().flush();
    let stdin_is_tty = io::stdin().is_terminal();
    let Some(buf) = read_prompt_line().await else {
        println!();
        return false;
    };
    let answer = clean_prompt_answer(&buf);
    if answer.is_empty() && !stdin_is_tty {
        println!();
        return false;
    }
    !(answer == "n" || answer == "no")
}

async fn read_prompt_line() -> Option<String> {
    let mut buf = String::new();
    let mut reader = tokio::io::BufReader::new(tokio::io::stdin());
    match tokio::io::AsyncBufReadExt::read_line(&mut reader, &mut buf).await {
        Ok(0) | Err(_) => None,
        Ok(_) => Some(buf),
    }
}

fn clean_prompt_answer(line: &str) -> String {
    line.trim_matches(|c: char| c.is_whitespace() || c == '\0' || c == '\u{feff}')
        .to_ascii_lowercase()
}

fn finish_with_bridge(msg: &str) {
    println!();
    println!("  {} {msg}", style::pewter(sym::BULLET));
    println!(
        "  {} Resume any time with {}.",
        style::pewter(sym::BULLET),
        style::cmd("difflore init"),
    );
    mark_welcomed();
}

/// Touch `~/.difflore/welcomed` so the screen never shows again on this
/// machine. Failures are silent — worst case the user sees the welcome a
/// second time, which is annoying but not broken. Also clears any
/// pending resume marker — completing the wizard means the user isn't
/// mid-flow anymore.
fn mark_welcomed() {
    let Ok(dir) = difflore_core::paths::data_home() else {
        return;
    };
    let _ = std::fs::create_dir_all(&dir);
    let _ = std::fs::write(dir.join(SENTINEL), sentinel_body(SENTINEL_VERSION));
    let _ = std::fs::remove_file(dir.join(RESUME_SENTINEL));
}

/// Write the resume marker so a subsequent bare `difflore` knows to jump
/// back into Step 4 instead of restarting the wizard from Step 1.
/// Best-effort; failures are silent
/// (worst case the user re-runs the full wizard, which is idempotent
/// for steps 1-3 anyway because login + import dedupe).
fn write_resume_marker() {
    let Ok(dir) = difflore_core::paths::data_home() else {
        return;
    };
    let _ = std::fs::create_dir_all(&dir);
    let _ = std::fs::write(
        dir.join(RESUME_SENTINEL),
        sentinel_body(RESUME_SENTINEL_VERSION),
    );
}

/// Remove the resume marker once Step 4 actually completed. Called from
/// the success branch so the next `difflore` doesn't re-enter the
/// wizard. The post-wizard `mark_welcomed` also clears it, but doing it
/// explicitly here keeps the success path correct even if a future
/// refactor moves `mark_welcomed`.
fn clear_resume_marker() {
    let Ok(dir) = difflore_core::paths::data_home() else {
        return;
    };
    let _ = std::fs::remove_file(dir.join(RESUME_SENTINEL));
}

fn sentinel_body(version: &str) -> String {
    format!("{version}\n")
}

fn sentinel_content_current(raw: &str, expected_version: &str) -> bool {
    raw.lines()
        .next()
        .is_some_and(|line| line == expected_version)
}

fn sentinel_version_current(path: &std::path::Path, expected_version: &str) -> bool {
    std::fs::read_to_string(path).is_ok_and(|raw| sentinel_content_current(&raw, expected_version))
}

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

    fn base() -> WizardSignals {
        WizardSignals {
            stdin_is_tty: true,
            stdout_is_tty: true,
            no_interactive_flag: false,
            no_welcome_env: false,
            sentinel_exists: false,
            local_rules_count: 0,
            cloud_logged_in: false,
        }
    }

    #[test]
    fn should_launch_wizard_fresh_interactive() {
        assert!(should_launch_wizard(base()));
    }

    #[test]
    fn should_launch_wizard_false_when_piped_stdin() {
        let s = WizardSignals {
            stdin_is_tty: false,
            ..base()
        };
        assert!(!should_launch_wizard(s));
    }

    #[test]
    fn should_launch_wizard_false_when_no_interactive_flag() {
        let s = WizardSignals {
            no_interactive_flag: true,
            ..base()
        };
        assert!(!should_launch_wizard(s));
    }

    #[test]
    fn should_launch_wizard_false_for_returning_user() {
        let s = WizardSignals {
            local_rules_count: 12,
            ..base()
        };
        assert!(!should_launch_wizard(s));
    }

    #[test]
    fn should_launch_wizard_false_when_sentinel_exists() {
        let s = WizardSignals {
            sentinel_exists: true,
            ..base()
        };
        assert!(!should_launch_wizard(s));
    }

    #[test]
    fn should_launch_wizard_false_when_env_opt_out() {
        let s = WizardSignals {
            no_welcome_env: true,
            ..base()
        };
        assert!(!should_launch_wizard(s));
    }

    #[test]
    fn first_run_preflight_skips_returning_user_without_state_probe() {
        assert_eq!(
            preflight_first_run_path(FirstRunPreflight {
                stdout_is_tty: true,
                no_interactive_flag: false,
                no_welcome_env: false,
                sentinel_exists: true,
                resume_pending: false,
            }),
            Some(FirstRunPath::Skip)
        );
    }

    #[test]
    fn first_run_preflight_resume_wins_over_welcomed_sentinel() {
        assert_eq!(
            preflight_first_run_path(FirstRunPreflight {
                stdout_is_tty: true,
                no_interactive_flag: false,
                no_welcome_env: false,
                sentinel_exists: true,
                resume_pending: true,
            }),
            Some(FirstRunPath::LaunchWizard)
        );
    }

    #[test]
    fn first_run_preflight_respects_no_interactive_before_probe() {
        assert_eq!(
            preflight_first_run_path(FirstRunPreflight {
                stdout_is_tty: true,
                no_interactive_flag: true,
                no_welcome_env: false,
                sentinel_exists: false,
                resume_pending: false,
            }),
            Some(FirstRunPath::Skip)
        );
    }

    #[test]
    fn welcome_flow_explicitly_controls_tui_continuation() {
        assert!(WelcomeFlow::ContinueTui.should_continue_tui());
        assert!(!WelcomeFlow::Stop.should_continue_tui());
    }

    /// The constants form an ordered triple: poll < soft < hard. Anything
    /// else makes the loop misbehave (e.g. soft cap firing before the
    /// first poll, or never).
    #[test]
    fn cap_constants_are_ordered() {
        assert!(POLL_INTERVAL < SOFT_CAP);
        assert!(SOFT_CAP < HARD_CAP);
    }

    #[test]
    fn import_depth_parser_accepts_blank_and_range() {
        assert_eq!(parse_import_depth_answer("", 50).unwrap(), 50);
        assert_eq!(parse_import_depth_answer("\r\n", 50).unwrap(), 50);
        assert_eq!(parse_import_depth_answer("100\r\n", 50).unwrap(), 100);
    }

    #[test]
    fn import_depth_parser_rejects_invalid_scope() {
        assert!(parse_import_depth_answer("0", 50).is_err());
        assert!(parse_import_depth_answer("1001", 50).is_err());
        assert!(parse_import_depth_answer("many", 50).is_err());
    }

    #[test]
    fn prompt_answer_cleanup_handles_windows_control_bytes() {
        assert_eq!(clean_prompt_answer("NO\r\n"), "no");
        assert_eq!(clean_prompt_answer("\u{feff}y\0\r\n"), "y");
    }

    #[test]
    fn heartbeat_mode_uses_plain_lines_for_captures_and_dumb_terms() {
        assert_eq!(heartbeat_mode(false, false), HeartbeatMode::PlainLines);
        assert_eq!(heartbeat_mode(true, true), HeartbeatMode::PlainLines);
        assert_eq!(heartbeat_mode(true, false), HeartbeatMode::InlineRewrite);
    }

    #[test]
    fn interrupt_action_switches_to_resume_checkpoint() {
        let interrupt = WizardInterrupt::default();
        assert!(!interrupt.should_write_resume());
        interrupt.write_resume_on_interrupt();
        assert!(interrupt.should_write_resume());
        interrupt.mark_welcomed_on_interrupt();
        assert!(!interrupt.should_write_resume());
    }

    #[test]
    fn sentinel_content_requires_current_version() {
        assert!(sentinel_content_current("welcome-v2\n", SENTINEL_VERSION));
        assert!(sentinel_content_current(
            "wizard-resume-v2\n",
            RESUME_SENTINEL_VERSION
        ));
        assert!(!sentinel_content_current("", SENTINEL_VERSION));
        assert!(!sentinel_content_current("welcome-v1\n", SENTINEL_VERSION));
    }

    #[test]
    fn static_welcome_import_command_matches_cloud_state() {
        assert_eq!(
            static_welcome_import_command(false),
            "difflore import-reviews --max-prs 50"
        );
        assert_eq!(
            static_welcome_import_command(true),
            "difflore import-reviews --max-prs 50 --upload"
        );
    }

    #[test]
    fn step4_mode_stays_local_when_login_was_skipped() {
        let mut state = WizardState::new();
        state.cloud_logged_in = false;
        state.used_cloud_import = false;

        assert_eq!(step4_mode(&state), Step4Mode::LocalBridge);

        state.cloud_logged_in = true;
        state.used_cloud_import = true;
        assert_eq!(step4_mode(&state), Step4Mode::CloudExtraction);
    }

    #[test]
    fn extraction_delta_uses_pre_import_baseline() {
        assert_eq!(extraction_delta(5, Some(2)), 3);
        assert_eq!(extraction_delta(2, Some(5)), 0);
    }

    #[test]
    fn extraction_delta_without_resume_baseline_counts_existing_rules() {
        assert_eq!(extraction_delta(4, None), 4);
        assert_eq!(extraction_delta(-1, None), 0);
    }
}