lean-ctx 3.12.7

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported proxy integrations.
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
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
// SPDX-License-Identifier: Apache-2.0
//! `lean-ctx cloud connect`: the single entry to Cloud (CHECKLIST 2.1.1).
//!
//! 1. Browser login through the device flow. The person picks the
//!    workspace on the approval page. Skipped when this machine is
//!    already connected.
//! 2. One confirmation of what this machine shares with that workspace,
//!    asked once per workspace (`core::cloud::connect`).
//! 3. The current project is mapped to its vault. A first share into a
//!    vault waits for the person's yes (`core::cloud::mapping`), asked
//!    here at a terminal.
//!
//! Running it again is safe and asks nothing that was answered. Later
//! sessions never prompt.

use std::io::{BufRead as _, Write as _};
use std::path::Path;

use lean_ctx_time::UtcDateTime;
use serde_json::{Value, json};

use super::cloud_cmd::{flag_value, plan_name};
use lean_ctx_cloud::CloudConfigExt as _;
use lean_ctx_cloud::auth::{
    EnrollmentToken, Session, SetupAnnouncement, announce_setup, enroll_with_token,
    finish_device_flow, start_device_flow_for,
};
use lean_ctx_cloud::connect::{self as steps, ProjectStep};
use lean_ctx_cloud::consent::ConsentError;
use lean_ctx_cloud::mapping::MapError;
use lean_ctx_cloud::state::InstanceRecord;
use lean_ctx_cloud::status::report;
use lean_ctx_cloud::transport::CloudClient;
use lean_ctx_cloud::vault::VaultMap;
use lean_ctx_cloud::{CloudConfig, CloudError, CloudStore};
use lean_ctx_protocol::cloud::enroll::{DeviceCodeV1, MAX_INSTANCE_LABEL_CHARS, TrialPlan};
use lean_ctx_protocol::cloud::lease::CloudLeaseV1;

fn default_label() -> String {
    let host = gethostname::gethostname()
        .to_string_lossy()
        .trim()
        .to_string();
    let host: String = host
        .chars()
        .filter(|c| !c.is_control())
        .take(MAX_INSTANCE_LABEL_CHARS)
        .collect();
    if host.trim().is_empty() {
        "lean-ctx".into()
    } else {
        host
    }
}

/// A key set another root signed (Cloud task lean-ctx #2): say which root
/// this engine checked against and how to use the right one; what follows
/// the refusal (the removed key, task #1) stays.
fn name_the_root(
    error: CloudError,
    trust: &lean_ctx_cloud::root_cert::ConnectTrust,
    origin: &str,
) -> CloudError {
    use lean_ctx_cloud::lease::ROOT_MISMATCH;
    let CloudError::Protocol(message) = error else {
        return error;
    };
    let Some(rest) = message.strip_prefix(ROOT_MISMATCH) else {
        return CloudError::Protocol(message);
    };
    let which = if trust.unvouched {
        format!(
            "the development root key from `[cloud] root_key` in your lean-ctx config. For {origin}, remove `root_key` from `[cloud]` so lean-ctx uses the production root it carries, or set it to the root key of that LeanCTX Cloud server"
        )
    } else if trust.certificate.is_some() {
        format!(
            "the root the certificate of {origin} names. Ask the operator of that LeanCTX Cloud server to renew its root certificate"
        )
    } else {
        format!(
            "the production root key built into lean-ctx {}. Update lean-ctx; for a self-hosted LeanCTX Cloud server, set `[cloud] root_key` to its root key",
            env!("CARGO_PKG_VERSION")
        )
    };
    CloudError::Protocol(format!(
        "{origin} answered with a key set not signed by {which}{rest}"
    ))
}

/// The environment variable a managed launcher (LeanCTX Code under MDM)
/// passes a pre-issued enrollment token in.
pub(super) const ENROLLMENT_TOKEN_ENV: &str = "LEAN_CTX_CLOUD_ENROLLMENT_TOKEN";
/// The flag that reads the enrollment token from one line of stdin.
const ENROLLMENT_TOKEN_STDIN: &str = "--enrollment-token-stdin";
/// The longest stdin line read for a token (it is 68 characters).
const ENROLLMENT_TOKEN_MAX_LINE: u64 = 1024;

/// The enrollment token this connect uses, if any: one line of `stdin`
/// with `--enrollment-token-stdin` (an explicit flag wins), else
/// `env` (`LEAN_CTX_CLOUD_ENROLLMENT_TOKEN`; empty counts as unset). Never
/// from argv, where other users of the machine could read it in `ps`.
/// The format is checked here, before anything is sent.
fn enrollment_token(
    args: &[String],
    stdin: &mut dyn std::io::BufRead,
    env: Option<std::ffi::OsString>,
) -> Result<Option<EnrollmentToken>, CloudError> {
    if args
        .iter()
        .any(|a| a == "--enrollment-token" || a.starts_with("--enrollment-token="))
    {
        return Err(CloudError::Config(format!(
            "an enrollment token is never passed on the command line, where other users can read it: pipe it to `{ENROLLMENT_TOKEN_STDIN}` or set {ENROLLMENT_TOKEN_ENV}"
        )));
    }
    if args.iter().any(|a| a == ENROLLMENT_TOKEN_STDIN) {
        let mut line = zeroize::Zeroizing::new(String::new());
        std::io::Read::take(stdin, ENROLLMENT_TOKEN_MAX_LINE)
            .read_line(&mut line)
            .map_err(|e| {
                CloudError::Local(format!(
                    "read the enrollment token from stdin: {}",
                    e.kind()
                ))
            })?;
        if line.trim().is_empty() {
            return Err(CloudError::Config(format!(
                "{ENROLLMENT_TOKEN_STDIN}: stdin held no enrollment token"
            )));
        }
        return EnrollmentToken::parse(&line).map(Some);
    }
    let Some(raw) = env.filter(|v| !v.is_empty()) else {
        return Ok(None);
    };
    let raw = zeroize::Zeroizing::new(raw.into_string().map_err(|_| {
        CloudError::Config(format!(
            "{ENROLLMENT_TOKEN_ENV}: the enrollment token is malformed (not UTF-8)"
        ))
    })?);
    EnrollmentToken::parse(&raw).map(Some)
}

/// `--trial [--plan personal|team]`: the plan whose one-step trial the
/// browser starts (`--plan` defaults to personal and needs `--trial`).
fn trial_choice(args: &[String]) -> Result<Option<TrialPlan>, CloudError> {
    let plan = flag_value(args, "--plan")?;
    match (args.iter().any(|a| a == "--trial"), plan) {
        (false, None) => Ok(None),
        (false, Some(_)) => Err(CloudError::Config(
            "--plan is only valid with --trial".into(),
        )),
        (true, None) => Ok(Some(TrialPlan::Personal)),
        (true, Some(plan)) => TrialPlan::parse(plan).map(Some).ok_or_else(|| {
            let shown: String = plan.chars().filter(|c| !c.is_control()).take(32).collect();
            CloudError::Config(format!("--plan {shown}: choose personal or team"))
        }),
    }
}

/// How a device flow ended, worded for a `--trial` connect: a Cloud that
/// refuses a used trial only in the browser lets the code expire, so the
/// hint names the plans page ([`CloudError::for_trial`]).
fn trial_aware(error: CloudError, trial: Option<TrialPlan>) -> CloudError {
    if trial.is_some() {
        error.for_trial()
    } else {
        error
    }
}

/// `cloud connect --json`, event `code`: what the person opens and checks.
fn code_event(code: &DeviceCodeV1) -> Value {
    json!({
        "event": "code",
        "verification_uri": code.verification_uri,
        "verification_uri_complete": code.verification_uri_complete,
        "user_code": code.user_code,
        "expires_in": code.expires_in,
    })
}

/// `cloud connect --json`, event `connected`: the plan's wire name and
/// when a running trial ends (`null` without one).
fn connected_event(lease: &CloudLeaseV1) -> Value {
    json!({
        "event": "connected",
        "plan": lease.plan,
        "trial_ends_at": lean_ctx_cloud::status::trial_ends_at(lease),
    })
}

/// `cloud connect --json`, event `error` (the command exits 1).
fn error_event(error: &CloudError) -> Value {
    json!({
        "event": "error",
        "code": error.event_code(),
        "message": error.to_string(),
    })
}

/// One event per line on stdout, flushed at once for the reader.
fn emit(event: &Value) {
    let mut out = std::io::stdout().lock();
    let _ = writeln!(out, "{event}");
    let _ = out.flush();
}

/// The enrollment token of this run, removed from the environment.
fn take_enrollment_token(args: &[String]) -> Result<Option<EnrollmentToken>, CloudError> {
    // Read and checked before anything else, so a malformed token never
    // reaches the network.
    let env = std::env::var_os(ENROLLMENT_TOKEN_ENV);
    let had_env = env.is_some();
    let token = enrollment_token(args, &mut std::io::stdin().lock(), env);
    if had_env {
        // SAFETY: removed on the CLI's main thread before this command
        // spawns anything, so the daemon, the runtime installer and other
        // children never inherit the token.
        unsafe { std::env::remove_var(ENROLLMENT_TOKEN_ENV) };
    }
    token
}

/// `--url`, else the configured Cloud.
fn origin_for(config: &CloudConfig, args: &[String]) -> Result<String, CloudError> {
    match flag_value(args, "--url")? {
        Some(url) => lean_ctx_cloud::config::normalize_origin(url),
        None => config.origin(),
    }
}

/// `lean-ctx cloud connect [--url <origin>] [--label <name>] [--no-browser] [--yes]
/// [--enrollment-token-stdin] [--trial [--plan personal|team]] [--json]`.
///
/// Prints the three steps the web shows too (approve this machine,
/// connected, share this project) and ends with "Done." and where to look.
/// With an enrollment token (stdin or `LEAN_CTX_CLOUD_ENROLLMENT_TOKEN`)
/// step 1 enrolls without a browser. `--json`: see [`run_json`].
pub(super) fn run(config: &CloudConfig, args: &[String]) -> Result<(), CloudError> {
    if args.iter().any(|a| a == "--json") {
        if let Err(error) = run_json(config, args) {
            emit(&error_event(&error));
            std::process::exit(1);
        }
        return Ok(());
    }
    let token = take_enrollment_token(args)?;
    let trial = trial_choice(args)?;
    let store = CloudStore::open()?;
    let origin = origin_for(config, args)?;
    if let Some(existing) = store.instance()? {
        let current = report(&store, config, UtcDateTime::now());
        if current.connected() {
            println!(
                "Already connected to {} as {} ({}). Run `lean-ctx cloud disconnect` first to switch.",
                existing.url, existing.label, existing.org_name
            );
            let session = lean_ctx_cloud::root_cert::trust_root(&store, config, &existing.url)
                .and_then(|root| Session::load(store, root));
            return match session {
                Ok(session) => {
                    let outcome = after_login(config, &session, &existing, args)?;
                    print_done(&existing, &outcome);
                    Ok(())
                }
                // `status` explains a broken session; connect stays a no-op.
                Err(error) => {
                    tracing::info!("cloud connect: {error}");
                    Ok(())
                }
            };
        }
        // A lapsed or broken enrollment is replaced; its keys are reused.
    }
    let chosen: Option<String> = flag_value(args, "--label")?
        .map(|label| label.chars().take(MAX_INSTANCE_LABEL_CHARS).collect());
    let label = chosen.clone().unwrap_or_else(default_label);
    let client = CloudClient::new(&origin)?;
    println!("LeanCTX Cloud — connect this machine");
    // A self-hosted Cloud is trusted when LeanCTX vouched for its root.
    let trust = lean_ctx_cloud::root_cert::for_connect(&client, config, &origin)
        .map_err(|error| unreachable(error, &origin))?;
    if trust.unvouched {
        println!(
            "(Development LeanCTX Cloud server: its root key comes from `[cloud] root_key` in your config.)"
        );
    }
    let root = trust.root;
    let here = project_here();
    let (early, named, announced, enrolled) = if let Some(token) = &token {
        // A pre-issued enrollment token (MDM, unattended hosts): no device
        // code, no browser; the team is the one the token was issued for.
        println!("\nStep 1 of 3 · Enroll this machine with your team's enrollment token");
        print!("  Enrolling…");
        let _ = std::io::stdout().flush();
        let enrolled = enroll_with_token(&store, &client, token, &label, &root)
            .map_err(|error| unreachable(error, &origin));
        (None, None, false, enrolled)
    } else {
        let code = start_device_flow_for(&client, chosen.as_deref(), trial)
            .map_err(|error| unreachable(error, &origin))?;
        // C0 2.1: the approval page also asks "Share this project" (one code).
        // The folder name and git remote reach Cloud only after the person's
        // yes here (or `--yes`); without one the page names no project.
        let early = here
            .as_ref()
            .filter(|_| code.offers_device_setup())
            .and_then(|_| share_before_approval(config, args));
        let mut announce_config = config.clone();
        if early == Some(false) {
            steps::without_sharing(&mut announce_config);
        }
        let named = here.as_deref().filter(|_| early == Some(true));
        let announced =
            announce_setup(&client, &code, &setup_announcement(&announce_config, named));
        println!("\nStep 1 of 3 · Approve this machine in your browser");
        if args.iter().any(|a| a == "--no-browser")
            || std::env::var_os("LEAN_CTX_NO_BROWSER").is_some()
        {
            println!(
                "  Open this link on any device: {}",
                code.verification_uri_complete
            );
        } else {
            let _ = open_browser(&code.verification_uri_complete);
            println!("  We opened: {}", code.verification_uri_complete);
        }
        println!(
            "  Check the code  {}  in the browser: it must be the same (valid {} minutes).",
            code.user_code,
            code.expires_in.div_ceil(60).max(1)
        );
        if let Some(plan) = trial {
            println!(
                "  There you sign in and start your {} trial for this machine.",
                trial_plan_name(plan)
            );
        } else if announced {
            println!(
                "  There you sign in, choose the workspace and confirm what this machine shares."
            );
        } else {
            println!("  There you sign in and choose the workspace for this machine.");
        }
        print!("  Waiting for you to approve…");
        let _ = std::io::stdout().flush();
        let enrolled =
            finish_device_flow(&store, &client, &code, &label, &root, &std::thread::sleep)
                .map_err(|error| trial_aware(error, trial));
        (early, named, announced, enrolled)
    };
    let (instance, sharing) = enrolled
        .map_err(|error| name_the_root(error, &trust, &origin))
        .map_err(|error| {
            println!();
            // A cooling-down Personal slot: `cloud status` keeps saying until when
            // and where the web recovery is (P7).
            if matches!(&error, CloudError::QuotaExceeded(q) if q.cooling_slot()) {
                println!("Instances:    {origin} (Settings › Connected instances)");
            }
            lean_ctx_cloud::throttle::note(
                &store,
                lean_ctx_cloud::throttle::Scope::Connect,
                error,
                UtcDateTime::now(),
            )
        })?;
    println!(
        "{}",
        if token.is_some() {
            " enrolled."
        } else {
            " approved."
        }
    );
    if let Some(certificate) = &trust.certificate {
        lean_ctx_cloud::root_cert::store_certificate(&store, certificate)?;
    }
    // An admin allowed this new enrolment: an earlier revocation is over.
    lean_ctx_cloud::revoked::clear(&store)?;
    lean_ctx_cloud::throttle::clear_connect(&store);
    let session = Session::load(store, root)?;
    // Prove the instance key works before reporting success.
    session.client()?;
    println!(
        "\nStep 2 of 3 · Connected {} to {} ({} plan).",
        instance.label,
        instance.workspace_label(),
        plan_name(&session.lease.lease.plan)
    );
    if let Some(trial) = lean_ctx_cloud::status::trial_line(&session.lease.lease) {
        println!("  {trial}.");
    }
    // Sync runs in the daemon's background: keep it running by itself, and
    // restart it so its scheduler starts for this connection (a test or an
    // isolated instance never installs a user-wide service).
    if let Some(line) = lean_ctx::daemon_autostart::supervision_line(
        lean_ctx::daemon_autostart::ensure_supervised(true),
    ) {
        println!("{line}");
    }
    announce_and_pull(&session);
    // The page answered "Share this project": recorded like the terminal's
    // answer, so no session asks again; a no switches every upload off.
    // E2E 27.10. E3: outside a project the page offers no share choice, so
    // whatever it sent is no answer and nothing is recorded or switched off.
    // The page asks only about a project it was named; otherwise the
    // answer given here before the approval stands.
    let sharing = sharing.filter(|_| project_here().is_some() && named.is_some());
    let answer = match sharing {
        Some(Some(share)) => Some((share, Some(steps::SOURCE_BROWSER))),
        _ => early.map(|share| (share, None)),
    };
    let mut device = false;
    if let Some((share, source)) = answer {
        if !share {
            lean_ctx::core::config::Config::update_global(|c| steps::without_sharing(&mut c.cloud))
                .map_err(|e| CloudError::Local(format!("record the answer: {e}")))?;
        }
        steps::record_from(
            &session.store,
            &instance.org_id,
            share,
            UtcDateTime::now(),
            source,
        )?;
        device = share && source.is_some();
    }
    let config = if answer.is_some_and(|(share, _)| !share) {
        let mut off = config.clone();
        steps::without_sharing(&mut off);
        off
    } else {
        config.clone()
    };
    let outcome = after_login_with(&config, &session, &instance, args, device, announced)?;
    if announced {
        report_setup(&session, &outcome);
    }
    print_done(&instance, &outcome);
    engine_metrics_notice(&config, &session, &instance);
    if session
        .lease
        .lease
        .grants(lean_ctx_protocol::cloud::lease::CloudRight::Runtime)
        && !config.runtime_consent
    {
        // Asked only at a terminal; nothing is installed without a yes.
        if lean_ctx::core::host_env::stdin_is_terminal()
            && super::prompt::confirm(RUNTIME_QUESTION, false)
        {
            return install_runtime(true);
        }
        println!(
            "  Optional: `lean-ctx cloud runtime install` adds the LeanCTX Intelligence runtime your plan includes; it enforces {}'s policies on this machine.",
            instance.org_name
        );
    }
    Ok(())
}

/// E44 at connect (SPEC-ENGINE §3.6) and the effective policy: neither
/// ever fails the connect.
fn announce_and_pull(session: &Session) {
    // A Cloud before C0 2.0 has no instance card.
    if let Err(error) = lean_ctx_cloud::workers::register::announce_instance(session) {
        tracing::info!("cloud instance card: {error}");
    }
    // Unified Control (2.x): the effective policy is in force and acked from
    // the connect on; the scheduler checks it again every interval. A 1.x
    // Cloud keeps its scheduled pull only.
    if lean_ctx_cloud::bus::relay_v2::speaks_v2(&session.store)
        && session
            .lease
            .lease
            .grants(lean_ctx_protocol::cloud::lease::CloudRight::PolicyPull)
        && let Err(error) = lean_ctx_cloud::policy::pull(session)
    {
        tracing::info!("cloud policy at connect: {error}");
    }
}

fn trial_plan_name(plan: TrialPlan) -> &'static str {
    match plan {
        TrialPlan::Personal => "Personal",
        TrialPlan::Team => "Team",
    }
}

/// `cloud connect --json` (LeanCTX Code and other launchers): asks
/// nothing and prints only line-delimited JSON events on stdout:
/// `code` (open `verification_uri_complete`, check `user_code`), then
/// `connected`, or `error` (printed by [`run`], exit 1). An already
/// connected machine answers `connected` for its connection at once.
/// Sharing is not asked: it follows the `[cloud]` settings until a person
/// answers `lean-ctx cloud connect` in a terminal.
fn run_json(config: &CloudConfig, args: &[String]) -> Result<(), CloudError> {
    let token = take_enrollment_token(args)?;
    let trial = trial_choice(args)?;
    let store = CloudStore::open()?;
    let origin = origin_for(config, args)?;
    if store.instance()?.is_some() {
        let current = report(&store, config, UtcDateTime::now());
        if let (true, Some(lease)) = (current.connected(), &current.lease) {
            emit(&connected_event(lease));
            return Ok(());
        }
    }
    let chosen: Option<String> = flag_value(args, "--label")?
        .map(|label| label.chars().take(MAX_INSTANCE_LABEL_CHARS).collect());
    let label = chosen.clone().unwrap_or_else(default_label);
    let client = CloudClient::new(&origin)?;
    let trust = lean_ctx_cloud::root_cert::for_connect(&client, config, &origin)?;
    let root = trust.root;
    let enrolled = if let Some(token) = &token {
        enroll_with_token(&store, &client, token, &label, &root)
    } else {
        let code = start_device_flow_for(&client, chosen.as_deref(), trial)?;
        emit(&code_event(&code));
        if !args.iter().any(|a| a == "--no-browser") {
            let _ = open_browser(&code.verification_uri_complete);
        }
        finish_device_flow(&store, &client, &code, &label, &root, &std::thread::sleep)
            .map_err(|error| trial_aware(error, trial))
    };
    enrolled
        .map_err(|error| name_the_root(error, &trust, &origin))
        .map_err(|error| {
            lean_ctx_cloud::throttle::note(
                &store,
                lean_ctx_cloud::throttle::Scope::Connect,
                error,
                UtcDateTime::now(),
            )
        })?;
    if let Some(certificate) = &trust.certificate {
        lean_ctx_cloud::root_cert::store_certificate(&store, certificate)?;
    }
    lean_ctx_cloud::revoked::clear(&store)?;
    lean_ctx_cloud::throttle::clear_connect(&store);
    let session = Session::load(store, root)?;
    session.client()?;
    // The supervision line is for people; stdout carries events only.
    let _ = lean_ctx::daemon_autostart::ensure_supervised(true);
    announce_and_pull(&session);
    emit(&connected_event(&session.lease.lease));
    Ok(())
}

/// An unreachable Cloud before anything was sent, in plain words.
fn unreachable(error: CloudError, origin: &str) -> CloudError {
    match error {
        CloudError::Offline(_) => CloudError::Refused(format!(
            "can't reach LeanCTX Cloud at {origin}. Check your connection and try again; LeanCTX keeps working locally meanwhile."
        )),
        other => other,
    }
}

/// How step 3 ended for the project here.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Outcome {
    /// Not inside a project with a stable identity (no git origin, id file
    /// or manifest).
    NoProject,
    /// The project syncs with the vault `ns/name`.
    Shared { ns: String, name: String },
    /// Nothing leaves this machine, and why.
    KeptLocal(String),
    /// The project waits for the person's yes.
    Waiting,
    /// The project has no vault yet; the background sync retries.
    Retry(String),
}

/// The engine-metrics notice (telemetry SPEC §4, K4): once at connect, in
/// this terminal only, once engine metrics are released. On Personal nothing is shared until the person says yes here (or later with
/// `cloud metrics confirm`); `--yes` does not answer it.
fn engine_metrics_notice(config: &CloudConfig, session: &Session, instance: &InstanceRecord) {
    use lean_ctx_cloud::metrics_v2::{self, gate, upload};
    if !upload::released(&instance.url) || !config.metrics_upload {
        return;
    }
    let workspace = instance.workspace_label();
    let web_url = instance
        .web_url
        .clone()
        .unwrap_or_else(|| instance.url.clone());
    let lease = &session.lease.lease;
    let sharing = gate::decide(&session.store, config, instance, lease, UtcDateTime::now());
    // Before the release nothing is shared, so nothing is asked either.
    let needs =
        gate::needs_confirmation(lease.plan) && !sharing.is_on() && upload::released(&instance.url);
    println!(
        "\n{}",
        metrics_v2::disclosure(&workspace, &web_url, &sharing, needs)
    );
    let terminal = lean_ctx::core::host_env::stdin_is_terminal()
        && std::io::IsTerminal::is_terminal(&std::io::stdout());
    if needs
        && terminal
        && super::prompt::confirm("Share instance metrics with this workspace?", false)
    {
        match upload::confirm(session) {
            Ok(_) => println!("Instance metrics confirmed for {workspace}."),
            Err(error) => eprintln!("cloud: instance metrics not confirmed: {error}"),
        }
    }
}

/// Steps 2 and 3 for a connected machine.
fn after_login(
    config: &CloudConfig,
    session: &Session,
    instance: &InstanceRecord,
    args: &[String],
) -> Result<Outcome, CloudError> {
    after_login_with(config, session, instance, args, false, false)
}

/// The checkout here, when LeanCTX can identify it (git origin, id file or
/// manifest): what connect shares and the page names.
fn project_here() -> Option<String> {
    let cwd = std::env::current_dir().ok()?;
    let root = lean_ctx::core::protocol::detect_project_root_or_cwd(&cwd.to_string_lossy());
    lean_ctx_cloud::vault::project_identity(Path::new(&root))?;
    Some(root)
}

/// What the approval page shows (C0 2.1): the folder name (as the first
/// share's consent names it) and the remote, plus the upload channels.
fn setup_announcement(config: &CloudConfig, root: Option<&str>) -> SetupAnnouncement {
    let project = root.map(|root| {
        let root = Path::new(root);
        let name: String = project_name(root)
            .chars()
            .filter(|c| !c.is_control())
            .take(64)
            .collect();
        let remote = lean_ctx_cloud::identity_v2::origin_remote(root)
            .filter(|r| (1..=500).contains(&r.chars().count()));
        (name, remote)
    });
    SetupAnnouncement {
        project: project.filter(|(name, _)| !name.trim().is_empty()),
        shares: steps::share_codes(config),
    }
}

/// Tell the approval page how the project step ended (best effort).
fn report_setup(session: &Session, outcome: &Outcome) {
    use lean_ctx_protocol::cloud::enroll::{DEVICE_SETUP_RESULT_SCHEMA, DeviceSetupResultV1};
    let (state, vault) = match outcome {
        Outcome::Shared { ns, name } => ("shared", Some(format!("{ns}/{name}"))),
        Outcome::NoProject => ("no_project", None),
        Outcome::KeptLocal(_) => ("kept_local", None),
        Outcome::Waiting | Outcome::Retry(_) => ("failed", None),
    };
    let body = DeviceSetupResultV1 {
        schema: DEVICE_SETUP_RESULT_SCHEMA.into(),
        state: state.into(),
        vault,
    };
    let sent = serde_json::to_value(&body)
        .map_err(|e| CloudError::Local(e.to_string()))
        .and_then(|body| session.with_client(|client| client.post("/device/setup/result", &body)));
    if let Err(error) = sent {
        tracing::info!("cloud device setup result: {error}");
    }
}

/// Steps 2 and 3; `device`: the approval page just confirmed sharing this
/// project, so its first share is answered there (C0 2.1), not here;
/// `announced`: this Cloud asks about sharing on the page, so `--yes`
/// does not answer it.
fn after_login_with(
    config: &CloudConfig,
    session: &Session,
    instance: &InstanceRecord,
    args: &[String],
    device: bool,
    announced: bool,
) -> Result<Outcome, CloudError> {
    // Sharing is asked per project: a folder LeanCTX cannot identify (no
    // git remote) has nothing to share, whatever was answered (E3).
    if project_here().is_none() {
        return Ok(Outcome::NoProject);
    }
    let Some(shared) = confirm_sharing(config, &session.store, instance, args, announced)? else {
        return Ok(Outcome::Waiting);
    };
    if !shared {
        return Ok(Outcome::KeptLocal(format!(
            "nothing from this machine is shared with {}",
            instance.org_name
        )));
    }
    let cwd = std::env::current_dir().map_err(|e| CloudError::Local(e.to_string()))?;
    let root = lean_ctx::core::protocol::detect_project_root_or_cwd(&cwd.to_string_lossy());
    // A yes given again in this run turned the channels back on.
    let config = lean_ctx::core::config::Config::load().cloud.clone();
    Ok(map_project(&config, session, Path::new(&root), device))
}

/// The project's name as people know it: its folder.
fn project_name(root: &Path) -> String {
    root.file_name().map_or_else(
        || root.display().to_string(),
        |n| n.to_string_lossy().into_owned(),
    )
}

/// The closing block: what happened, where to look, what comes next.
fn print_done(instance: &InstanceRecord, outcome: &Outcome) {
    let web = instance
        .web_url
        .clone()
        .unwrap_or_else(|| instance.url.clone());
    let web = web.trim_end_matches('/');
    let cwd = std::env::current_dir().unwrap_or_default();
    let root = lean_ctx::core::protocol::detect_project_root_or_cwd(&cwd.to_string_lossy());
    let project = project_name(Path::new(&root));
    let org = &instance.org_name;
    println!();
    match outcome {
        Outcome::Shared { ns, name } => {
            println!(
                "Done. Your agents now share what they learn about {project} with your team in {org}."
            );
            println!("  Open:  {web}/o/{ns}/v/{name}/");
            println!("  Next:  Keep working as usual; LeanCTX syncs in the background.");
            println!("         Another project? Run `lean-ctx cloud connect` there.");
        }
        Outcome::NoProject => {
            println!(
                "Done. This machine is connected to {org}. This folder is not a project LeanCTX can share (it has no git remote)."
            );
            println!("  Open:  {web}/app/");
            println!("  Next:  Run `lean-ctx cloud connect` inside a project to share it.");
        }
        Outcome::KeptLocal(why) => {
            println!("Done. {project} stays on this machine: {why}.");
            println!("  Your agents still use {org}'s knowledge and policies.");
            println!("  Open:  {web}/app/");
            println!(
                "  Changed your mind? Run `lean-ctx cloud connect` here again in your own terminal: it asks again."
            );
        }
        Outcome::Waiting => {
            println!(
                "Almost done. {project} stays on this machine until you confirm it yourself: run `lean-ctx cloud connect` here, in your own terminal (agents cannot confirm it)."
            );
            println!("  Open:  {web}/app/");
        }
        Outcome::Retry(why) => {
            println!(
                "Connected, but {project} is not set up yet: {why}. LeanCTX tries again in the background; nothing leaves this machine before that."
            );
            println!("  Open:  {web}/app/");
        }
    }
}

/// Step 3's line for a recorded answer; one from the approval page says so.
fn decided_line(decided: &steps::SharingDecision, org: &str) -> String {
    match (decided.source.as_deref(), decided.shared) {
        (Some(steps::SOURCE_BROWSER), true) => {
            format!("answered in the browser: shared with {org}.")
        }
        (Some(steps::SOURCE_BROWSER), false) => {
            "answered in the browser: not shared. Nothing from this machine is shared.".into()
        }
        (_, true) => format!("Sharing with {org} is on: you confirmed it."),
        (_, false) => format!("Sharing with {org} is off: you said no."),
    }
}

/// A recorded "no" is asked again when a person can answer (a terminal);
/// a recorded yes stands. `--yes` never turns a no into a yes.
fn asks_again(decided: &steps::SharingDecision, terminal: bool) -> bool {
    !decided.shared && terminal
}

/// `--yes` answers the sharing question only where the terminal asks it:
/// a Cloud that took the setup (C0 2.1) asks on the approval page.
fn yes_answers_sharing(args: &[String], announced: bool) -> bool {
    !announced && super::prompt::wants_yes(args)
}

/// Against a Cloud that offers the device setup (C0 2.1): ask before the
/// approval, because only a yes may send the project's folder name and git
/// remote to Cloud (`/device/setup`). `None` when nobody can answer (no
/// terminal, no `--yes`): the project is then not named.
fn share_before_approval(config: &CloudConfig, args: &[String]) -> Option<bool> {
    let assume_yes = super::prompt::wants_yes(args);
    if !assume_yes && !lean_ctx::core::host_env::stdin_is_terminal() {
        return None;
    }
    println!("\nBefore you approve · Share this project");
    println!("  With the workspace you choose, this machine would share:");
    for item in steps::shared_items(config) {
        println!("  - {item}");
    }
    Some(super::prompt::confirm(
        "Share this project? A yes sends its folder name and git remote to LeanCTX Cloud now, so the approval page can show it",
        assume_yes,
    ))
}

/// The sharing answer for the instance's workspace: the recorded one, or
/// asked now. `None` when no person could answer (no terminal, no
/// `--yes`); the `[cloud]` settings then apply unchanged, as before.
fn confirm_sharing(
    config: &CloudConfig,
    store: &CloudStore,
    instance: &InstanceRecord,
    args: &[String],
    announced: bool,
) -> Result<Option<bool>, CloudError> {
    println!("\nStep 3 of 3 · Share this project");
    if let Some(decided) = steps::decision(store, &instance.org_id) {
        println!("  {}", decided_line(&decided, &instance.org_name));
        let terminal = lean_ctx::core::host_env::stdin_is_terminal();
        if !asks_again(&decided, terminal) {
            return Ok(Some(decided.shared));
        }
        // E2E 27.10. E2: a recorded "no" is asked again here, in a terminal.
        if !super::prompt::confirm("Share it with the workspace now?", false) {
            return Ok(Some(false));
        }
        lean_ctx::core::config::Config::update_global(|c| steps::with_sharing(&mut c.cloud))
            .map_err(|e| CloudError::Local(format!("record the answer: {e}")))?;
        steps::record(store, &instance.org_id, true, UtcDateTime::now())?;
        return Ok(Some(true));
    }
    let items = steps::shared_items(config);
    if items.is_empty() {
        println!(
            "  This machine shares nothing with {}: every upload is switched off in your `[cloud]` settings.",
            instance.org_name
        );
        // Not recorded: turning a channel on later asks at the next connect.
        return Ok(Some(false));
    }
    let assume_yes = yes_answers_sharing(args, announced);
    if announced && super::prompt::wants_yes(args) {
        println!(
            "  --yes does not answer this: LeanCTX Cloud asks about sharing on the approval page."
        );
    }
    if !assume_yes && !lean_ctx::core::host_env::stdin_is_terminal() {
        println!(
            "  Nobody could answer here (no terminal), so sharing with {} follows your `[cloud]` settings until you do.",
            instance.org_name
        );
        return Ok(None);
    }
    println!(
        "  Your agents share what they learn with your team in {}. From this machine that is:",
        instance.org_name
    );
    for item in &items {
        println!("  - {item}");
    }
    println!(
        "  Either way your agents get the workspace's knowledge and policies, and local tools never depend on LeanCTX Cloud."
    );
    let shared = super::prompt::confirm("Share this with the workspace?", assume_yes);
    if !shared {
        lean_ctx::core::config::Config::update_global(|c| steps::without_sharing(&mut c.cloud))
            .map_err(|e| CloudError::Local(format!("record the answer: {e}")))?;
        println!(
            "  Nothing is shared. Turn single channels on later with `lean-ctx config set cloud.<key> true`."
        );
    }
    steps::record(store, &instance.org_id, shared, UtcDateTime::now())?;
    Ok(Some(shared))
}

/// Step 3: name the vault of the project at `root`. Never fails the
/// connect: the background sync retries what did not work here.
fn map_project(config: &CloudConfig, session: &Session, root: &Path, device: bool) -> Outcome {
    // Dogfood 5.11.: a recorded vault the link file or the identity no
    // longer backs is dropped here and resolved again, never reused.
    match lean_ctx_cloud::resolution::forget_stale_at(session.store.data_dir(), root) {
        Ok(Some(stale)) => println!("  Note: {}; resolving it again.", stale.describe()),
        Ok(None) => {}
        Err(error) => return Outcome::Retry(error.to_string()),
    }
    let outcome = map_project_step(config, session, root, device);
    if let Outcome::Shared { ns, name } = &outcome {
        let ours = lean_ctx_protocol::cloud::vault::VaultRefV1 {
            ns: ns.clone(),
            name: name.clone(),
        };
        if let Some(other) = lean_ctx_cloud::mapping::bound_elsewhere(session, root, &ours) {
            println!(
                "  Warning: LeanCTX Cloud binds this repository to the vault {}/{} (another Instance of {} resolved it there), but this machine syncs it with {ns}/{name}. One repository in two vaults splits its knowledge: run `lean-ctx cloud link {}/{}` here, or move it in LeanCTX Cloud.",
                other.ns, other.name, session.instance.org_name, other.ns, other.name
            );
        }
    }
    outcome
}

fn map_project_step(config: &CloudConfig, session: &Session, root: &Path, device: bool) -> Outcome {
    let project = project_name(root);
    let org = &session.instance.org_name;
    match steps::project_step(&VaultMap::load(session.store.data_dir()), root) {
        ProjectStep::None => Outcome::NoProject,
        ProjectStep::Known(vault) => {
            println!("  This project syncs with the vault {vault}.");
            let (ns, name) = vault.split_once('/').unwrap_or(("", vault.as_str()));
            Outcome::Shared {
                ns: ns.to_string(),
                name: name.to_string(),
            }
        }
        ProjectStep::Resolve => {
            let resolve =
                || lean_ctx_cloud::knowledge::pull::resolve_project(session, config, root);
            let mut result = resolve();
            // C0 2.1: the approval page confirmed this share a moment ago.
            if device
                && let Err(MapError::Consent(ConsentError::Required { consent_id, .. })) = &result
            {
                match answer_on_device_page(config, session, consent_id) {
                    Ok(()) => result = resolve(),
                    Err(error) => println!("  cloud: {error}"),
                }
            }
            // 2.1.3: the first share waits for the person; at a terminal
            // they answer here, through the same channel as `cloud consent`.
            if let Err(MapError::Consent(ConsentError::Required { consent_id, .. })) = &result
                && lean_ctx::core::host_env::stdin_is_terminal()
            {
                println!(
                    "  {project} has not shared anything with {org} yet. Confirm it once: what your agents learn here then goes into this project's vault in {org} (the one it already has there, or a new one)."
                );
                let approve = ["approve".to_string(), consent_id.clone()];
                match super::cloud_consent_cmd::run(config, &approve) {
                    Ok(()) => result = resolve(),
                    Err(error) => println!("  cloud: {error}"),
                }
            }
            match result {
                Ok(record) => {
                    println!(
                        "  This project syncs with the vault {}/{}.",
                        record.ns, record.name
                    );
                    Outcome::Shared {
                        ns: record.ns,
                        name: record.name,
                    }
                }
                Err(MapError::Consent(ConsentError::Denied)) => {
                    Outcome::KeptLocal("you said no to sharing it".into())
                }
                Err(MapError::Consent(_)) => Outcome::Waiting,
                Err(MapError::Cloud(CloudError::Refused(why)))
                    if why.starts_with("vault_mismatch") =>
                {
                    Outcome::KeptLocal(why)
                }
                Err(error) => Outcome::Retry(format!(
                    "it has no vault yet ({error}); `lean-ctx cloud link <workspace>/<vault>` names one"
                )),
            }
        }
    }
}

/// The first share, answered on the device approval page (C0 2.1).
fn answer_on_device_page(
    config: &CloudConfig,
    session: &Session,
    consent_id: &str,
) -> Result<(), CloudError> {
    use lean_ctx_cloud::consent::broker::{Broker, Trust};
    use lean_ctx_cloud::consent::web::WebRun;
    let store = &session.store;
    let broker = Broker::open(store, Trust::load(store, config));
    let now = || u64::try_from(UtcDateTime::now().timestamp_millis()).unwrap_or_default();
    let run = WebRun {
        broker: &broker,
        data_dir: store.data_dir(),
        now: &now,
        sleep: &std::thread::sleep,
        open: &|_| {},
    };
    let record = session.with_client(|client| {
        Ok(run.run_device(client, consent_id, &mut || {
            println!("  One more question is waiting for you on the browser page.");
        }))
    })??;
    if record.state == lean_ctx_cloud::consent::State::Approved {
        Ok(())
    } else {
        Err(ConsentError::Denied.into())
    }
}

const RUNTIME_QUESTION: &str = "Your plan includes the LeanCTX Intelligence runtime (proprietary, from the signed LeanCTX channel); it enforces your workspace's policy on this machine. Install it now?";

/// Record the consent, then install through the signed runtime channel.
pub(super) fn install_runtime(consented: bool) -> Result<(), CloudError> {
    if !super::prompt::confirm(RUNTIME_QUESTION, consented) {
        return Err(CloudError::Config(
            "the runtime was not installed: no consent".into(),
        ));
    }
    lean_ctx::core::config::Config::update_global(|config| config.cloud.runtime_consent = true)
        .map_err(|e| CloudError::Local(format!("record the consent: {e}")))?;
    let result = lean_ctx::core::intelligence_runtime::run(&[
        "sync-configured".to_string(),
        "--accept-proprietary".to_string(),
    ])
    .map_err(|e| CloudError::Local(format!("runtime install: {e}")))?;
    println!("{result}");
    Ok(())
}

/// Open `url` in the default browser (best effort). `LEAN_CTX_NO_BROWSER`
/// (any value) keeps every browser closed, like `--no-browser`.
pub(super) fn open_browser(url: &str) -> std::io::Result<()> {
    if std::env::var_os("LEAN_CTX_NO_BROWSER").is_some() {
        return Ok(());
    }
    #[cfg(target_os = "macos")]
    let mut command = std::process::Command::new("open");
    #[cfg(windows)]
    let mut command = {
        let mut c = std::process::Command::new("rundll32");
        c.arg("url.dll,FileProtocolHandler");
        c
    };
    #[cfg(not(any(target_os = "macos", windows)))]
    let mut command = std::process::Command::new("xdg-open");
    command
        .arg(url)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .map(|_| ())
}

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

    fn decided(shared: bool, source: Option<&str>) -> steps::SharingDecision {
        steps::SharingDecision {
            schema: steps::SHARING_SCHEMA.into(),
            org_id: "org_a".into(),
            shared,
            decided_at: "2026-10-26T09:00:00Z".into(),
            source: source.map(str::to_string),
        }
    }

    #[test]
    fn step_three_says_when_the_browser_answered() {
        assert_eq!(
            decided_line(&decided(true, Some("browser")), "Acme"),
            "answered in the browser: shared with Acme."
        );
        assert!(
            decided_line(&decided(false, Some("browser")), "Acme")
                .starts_with("answered in the browser: not shared")
        );
        assert_eq!(
            decided_line(&decided(true, None), "Acme"),
            "Sharing with Acme is on: you confirmed it."
        );
    }

    /// E2E 27.10. E2: "Changed your mind? Run connect again" must ask again.
    #[test]
    fn a_recorded_no_is_asked_again_in_a_terminal_only() {
        assert!(asks_again(&decided(false, Some("browser")), true));
        assert!(asks_again(&decided(false, None), true));
        assert!(!asks_again(&decided(false, None), false), "no terminal");
        assert!(!asks_again(&decided(true, None), true), "a yes stands");
    }

    const TOKEN: &str = "het_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
    const OTHER: &str = "het_fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210";

    fn token_from(args: &[&str], stdin: &str, env: Option<&str>) -> Result<Option<String>, String> {
        let args: Vec<String> = args.iter().map(|a| (*a).to_string()).collect();
        enrollment_token(
            &args,
            &mut std::io::Cursor::new(stdin.as_bytes()),
            env.map(std::ffi::OsString::from),
        )
        .map(|t| t.map(|t| format!("{t:?}")))
        .map_err(|e| e.to_string())
    }

    #[test]
    fn the_enrollment_token_comes_from_stdin_first_then_the_environment() {
        assert_eq!(token_from(&[], "", None), Ok(None), "no token: device flow");
        assert_eq!(
            token_from(&[], TOKEN, Some("")),
            Ok(None),
            "empty env is unset"
        );
        let some = Ok(Some("EnrollmentToken(het_…)".to_string()));
        assert_eq!(token_from(&[], "", Some(TOKEN)), some);
        assert_eq!(
            token_from(&["--enrollment-token-stdin"], &format!("{TOKEN}\n"), None),
            some
        );
        // The explicit flag wins over the ambient variable: a malformed
        // stdin fails even with a good token in the environment.
        let stdin_wins = token_from(&["--enrollment-token-stdin"], "nope\n", Some(OTHER));
        assert!(stdin_wins.is_err_and(|e| e.contains("malformed")));
        assert_eq!(
            token_from(
                &["--enrollment-token-stdin"],
                &format!("{TOKEN}\n"),
                Some("bad")
            ),
            some
        );
        // Only the first line counts.
        assert_eq!(
            token_from(
                &["--enrollment-token-stdin"],
                &format!("{TOKEN}\n{OTHER}\n"),
                None
            ),
            some
        );
        assert!(
            token_from(&["--enrollment-token-stdin"], "\n", Some(TOKEN))
                .is_err_and(|e| e.contains("stdin held no enrollment token"))
        );
    }

    #[test]
    fn the_enrollment_token_is_never_taken_from_argv_nor_echoed() {
        let inline = format!("--enrollment-token={TOKEN}");
        for args in [vec!["--enrollment-token", TOKEN], vec![inline.as_str()]] {
            let error = token_from(&args, "", None).expect_err("argv refused");
            assert!(
                error.contains("never passed on the command line"),
                "{error}"
            );
            assert!(!error.contains(&TOKEN[4..]), "{error}");
        }
        let bad = format!("{}x", &TOKEN[..TOKEN.len() - 1]);
        for error in [
            token_from(&[], "", Some(&bad)).unwrap_err(),
            token_from(&["--enrollment-token-stdin"], &bad, None).unwrap_err(),
        ] {
            assert!(error.contains("malformed"), "{error}");
            assert!(!error.contains(&bad[4..20]), "{error}");
        }
        let long = "a".repeat(4096);
        let error = token_from(&["--enrollment-token-stdin"], &long, None).unwrap_err();
        assert!(!error.contains(&long[..64]), "{error}");
    }

    fn strings(args: &[&str]) -> Vec<String> {
        args.iter().map(|a| (*a).to_string()).collect()
    }

    #[test]
    fn trial_flags_default_to_personal_and_plan_needs_trial() {
        assert_eq!(trial_choice(&strings(&[])), Ok(None));
        assert_eq!(
            trial_choice(&strings(&["--trial", "--yes"])),
            Ok(Some(TrialPlan::Personal))
        );
        assert_eq!(
            trial_choice(&strings(&["--trial", "--plan", "team"])),
            Ok(Some(TrialPlan::Team))
        );
        let alone = trial_choice(&strings(&["--plan", "team"])).unwrap_err();
        assert_eq!(alone.event_code(), "config");
        assert!(alone.to_string().contains("only valid with --trial"));
        let other = trial_choice(&strings(&["--trial", "--plan", "enterprise"])).unwrap_err();
        assert!(other.to_string().contains("choose personal or team"));
        assert!(trial_choice(&strings(&["--trial", "--plan"])).is_err());
    }

    fn lease(trial_ends_at: Option<&str>) -> CloudLeaseV1 {
        let envelope: Value = serde_json::from_str(
            &std::fs::read_to_string(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/../lean-ctx-protocol/tests/fixtures/cloud/lease_envelope.response.json"
            ))
            .unwrap(),
        )
        .unwrap();
        let mut lease = envelope["lease"].clone();
        if let Some(at) = trial_ends_at {
            lease["trial_ends_at"] = at.into();
        }
        serde_json::from_value(lease).unwrap()
    }

    /// The `--json` events are one compact object per line, exactly the
    /// documented members.
    #[test]
    fn trial_json_events_carry_the_documented_members() {
        let code = DeviceCodeV1 {
            schema: "leanctx.cloud.device-code/v1".into(),
            device_code: "secret-device-code".into(),
            user_code: "WDJB-MJHT".into(),
            verification_uri: "https://cloud.leanctx.com/device".into(),
            verification_uri_complete:
                "https://cloud.leanctx.com/device?user_code=WDJB-MJHT&intent=trial&plan=personal"
                    .into(),
            interval: 5,
            expires_in: 600,
            features: Vec::new(),
            intent: None,
            plan: None,
        };
        let event = code_event(&code);
        assert_eq!(
            event,
            json!({
                "event": "code",
                "verification_uri": "https://cloud.leanctx.com/device",
                "verification_uri_complete": "https://cloud.leanctx.com/device?user_code=WDJB-MJHT&intent=trial&plan=personal",
                "user_code": "WDJB-MJHT",
                "expires_in": 600,
            })
        );
        assert!(!event.to_string().contains("secret-device-code"));
        assert!(!event.to_string().contains('\n'));

        let trial = connected_event(&lease(Some("2026-12-02T10:00:00Z")));
        assert_eq!(trial["event"], "connected");
        assert_eq!(trial["trial_ends_at"], "2026-12-02T10:00:00Z");
        assert!(trial["plan"].is_string());
        let plain = connected_event(&lease(None));
        assert_eq!(plain["trial_ends_at"], Value::Null);
        assert_eq!(
            plain.as_object().unwrap().keys().collect::<Vec<_>>(),
            ["event", "plan", "trial_ends_at"]
        );

        let used = CloudError::PlanRequired(Box::new(lean_ctx_cloud::error::PlanNeed {
            plan_needed: Some("personal".into()),
            reason: Some(lean_ctx_cloud::error::TRIAL_USED.into()),
            plans_url: Some("https://cloud.leanctx.com/plans".into()),
            ..Default::default()
        }));
        let event = error_event(&used);
        assert_eq!(event["event"], "error");
        assert_eq!(event["code"], "trial_used");
        assert!(event["message"].as_str().unwrap().contains("trial"));
        let expired = error_event(&CloudError::DeviceFlow(
            lean_ctx_cloud::error::CODE_EXPIRED.into(),
        ));
        assert_eq!(expired["code"], "expired");
        let denied = error_event(&CloudError::DeviceFlow(
            lean_ctx_cloud::error::CODE_DENIED.into(),
        ));
        assert_eq!(denied["code"], "denied");
        let old = error_event(&CloudError::TrialUnsupported {
            origin: "https://cloud.example".into(),
        });
        assert_eq!(old["code"], "trial_unsupported");
    }

    /// The top-level function `name` of this file, from its `fn` line to
    /// its closing brace at column 0. Line endings are normalised, as a
    /// Windows checkout may store this file with CRLF.
    fn source_of(name: &str) -> &'static str {
        static SOURCE: std::sync::LazyLock<String> =
            std::sync::LazyLock::new(|| include_str!("cloud_connect_cmd.rs").replace("\r\n", "\n"));
        let source: &'static str = &SOURCE;
        let tests = source
            .find("#[cfg(test)]\nmod tests")
            .expect("tests module");
        let start = [format!("\nfn {name}("), format!("\npub(super) fn {name}(")]
            .iter()
            .find_map(|head| source[..tests].find(head.as_str()))
            .unwrap_or_else(|| panic!("fn {name} not found"));
        let end = source[start..].find("\n}\n").expect("closing brace") + start;
        &source[start..end]
    }

    /// Text that reaches stdout outside `emit`: a print macro (not the
    /// stderr `eprint`s), a `write!` to a stream, or the stdout handle.
    fn stdout_writes(body: &str) -> Vec<&'static str> {
        let mut found = Vec::new();
        for needle in ["print!", "println!"] {
            for (at, _) in body.match_indices(needle) {
                if !body[..at].ends_with('e') {
                    found.push(needle);
                }
            }
        }
        for needle in [
            "io::stdout",
            "stdout()",
            "write!(",
            "writeln!(",
            "print_done(",
        ] {
            if body.contains(needle) {
                found.push(needle);
            }
        }
        found
    }

    /// Local Read §6a: with `--json` stdout carries only event lines and
    /// nothing comes before the first event; LeanCTX Code tells an older
    /// lean-ctx from a silent one by that. `emit` is the only stdout
    /// writer on the whole `--json` path of this file.
    #[test]
    fn json_connect_writes_stdout_only_through_the_event_writer() {
        let emit_body = source_of("emit");
        assert!(emit_body.contains("std::io::stdout()"), "{emit_body}");
        let run = source_of("run");
        let json_branch = &run[..run.find("let token = take_enrollment_token").unwrap()];
        assert!(json_branch.contains("run_json(config, args)"));
        assert!(
            stdout_writes(json_branch).is_empty(),
            "the --json branch of run prints: {json_branch}"
        );
        for name in [
            "run_json",
            "take_enrollment_token",
            "enrollment_token",
            "trial_choice",
            "origin_for",
            "default_label",
            "code_event",
            "connected_event",
            "error_event",
            "name_the_root",
            "trial_aware",
            "open_browser",
            "announce_and_pull",
        ] {
            let body = source_of(name);
            assert_eq!(
                stdout_writes(body),
                Vec::<&str>::new(),
                "fn {name} writes to stdout outside emit"
            );
        }
        // The first thing run_json writes is an event, and every write is one.
        let body = source_of("run_json");
        let emits: Vec<_> = body.match_indices("emit(").map(|(at, _)| at).collect();
        assert!(!emits.is_empty());
        for at in emits {
            let call = &body[at..];
            assert!(
                call.starts_with("emit(&code_event(") || call.starts_with("emit(&connected_event("),
                "{}",
                &call[..call.len().min(60)]
            );
        }
        assert!(
            body.find("emit(&code_event(").unwrap() < body.find("finish_device_flow(").unwrap()
        );
        // The terminal flow, by contrast, prints: the check sees it.
        assert!(stdout_writes(run).contains(&"println!"));
        assert!(stdout_writes("let _ = writeln!(std::io::stdout(), \"x\");").len() >= 2);
        assert!(stdout_writes("eprintln!(\"to stderr\");").is_empty());
    }

    /// A `--trial` code that ran out points to the plans page (an older
    /// Cloud refuses a used trial only in the browser); a sign-in keeps
    /// "run connect again". Both stay event code `expired`.
    #[test]
    fn trial_expiry_names_the_plans_page_not_a_new_code() {
        let expired = || CloudError::DeviceFlow(lean_ctx_cloud::error::CODE_EXPIRED.into());
        let trial = error_event(&trial_aware(expired(), Some(TrialPlan::Personal)));
        assert_eq!(trial["code"], "expired");
        let message = trial["message"].as_str().unwrap();
        assert!(
            message.contains("choose a plan in LeanCTX Cloud"),
            "{message}"
        );
        assert!(
            message.contains("lean-ctx cloud connect --trial"),
            "{message}"
        );
        let plain = error_event(&trial_aware(expired(), None));
        assert_eq!(plain["code"], "expired");
        assert_eq!(plain["message"], expired().to_string());
        let denied = CloudError::DeviceFlow(lean_ctx_cloud::error::CODE_DENIED.into());
        assert_eq!(trial_aware(denied.clone(), Some(TrialPlan::Team)), denied);
    }

    #[test]
    fn yes_answers_sharing_only_where_the_terminal_asks() {
        let yes = vec!["--yes".to_string()];
        assert!(
            yes_answers_sharing(&yes, false),
            "older LeanCTX Cloud: as before"
        );
        assert!(
            !yes_answers_sharing(&yes, true),
            "C0 2.1 LeanCTX Cloud: the page asks, --yes never answers"
        );
        assert!(!yes_answers_sharing(&[], false));
    }
}