quilt-cli 0.31.0

Local-first data versioning for AI agent workflows: commit immutable data packages on your own machine, then sync them with S3 to share.
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
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
//! Not a part of the library and meant to be an independent project.
//! This is a CLI frontend for `quilt_rs`.

use std::path::Path;
use std::path::PathBuf;

use clap::Parser;
use clap::Subcommand;
use tracing::log;

use quilt_rs::flow::UserMeta;
use quilt_rs::io::remote::WorkflowIntent;
use quilt_uri::Host;
use quilt_uri::Namespace;

mod browse;
mod commit;
mod create;
mod history;
mod install;
mod list;
mod login;
mod model;
mod output;
mod pull;
mod push;
mod role;
mod status;
mod text;
mod undo_commit;
mod uninstall;

#[cfg(test)]
mod fixtures;

use model::Model;
pub use output::Std;
pub use output::print;

const DOMAIN_DIR_NAMESPACE: &str = "com.quiltdata.quilt-sync";

/// Resolve the commit command's `(--workflow, --no-workflow)` flag pair into a
/// [`WorkflowIntent`] at the clap boundary.
///
/// * `--no-workflow` → [`WorkflowIntent::NoWorkflow`] (explicit opt-out).
/// * an explicitly-passed but blank `--workflow` (empty or whitespace) → error:
///   a scripted unset-variable footgun is rejected loudly rather than silently
///   falling back to the bucket default.
/// * otherwise the id is normalized by [`WorkflowIntent::from_optional_id`]:
///   omitting `--workflow` → [`WorkflowIntent::BucketDefault`], a non-blank id →
///   [`WorkflowIntent::Named`] (trimmed).
fn commit_workflow_intent(
    workflow: Option<&str>,
    no_workflow: bool,
) -> Result<WorkflowIntent, Error> {
    if no_workflow {
        Ok(WorkflowIntent::NoWorkflow)
    } else if matches!(workflow, Some(id) if id.trim().is_empty()) {
        Err(Error::WorkflowEmpty)
    } else {
        Ok(WorkflowIntent::from_optional_id(workflow))
    }
}

fn parse_optional_namespace(namespace: Option<String>) -> Result<Option<Namespace>, Error> {
    Ok(match namespace {
        Some(namespace) => Some(namespace.try_into()?),
        None => None,
    })
}

fn get_domain_dir(dir_arg: Option<PathBuf>) -> Result<PathBuf, Error> {
    match dir_arg {
        Some(user_specified_dir) => Ok(user_specified_dir),
        None => match dirs::data_local_dir() {
            Some(default_user_dir) => Ok(default_user_dir.join(DOMAIN_DIR_NAMESPACE)),
            None => Err(Error::Domain),
        },
    }
}

fn get_default_home_dir() -> Result<PathBuf, Error> {
    dirs::home_dir()
        .map(|user_home| user_home.join(quilt_rs::DEFAULT_HOME_DIR_NAME))
        .ok_or(Error::Home)
}

async fn initialize_home(model: &Model, home: Option<PathBuf>) -> Result<(), Error> {
    if let Some(dir) = home {
        model.set_home(dir).await?;
    } else {
        match model.get_home().await {
            Ok(_) => {}
            Err(Error::Quilt(quilt_rs::Error::Lineage(
                quilt_rs::LineageError::Missing | quilt_rs::LineageError::MissingHome,
            ))) => {
                model.set_home(get_default_home_dir()?).await?;
            }
            Err(err) => return Err(err),
        }
    }

    model.get_home().await?;
    Ok(())
}

fn namespace_from_working_dir(home: &Path, current_dir: &Path) -> Result<Namespace, Error> {
    let home = std::fs::canonicalize(home).unwrap_or_else(|_| home.to_path_buf());
    let current_dir =
        std::fs::canonicalize(current_dir).unwrap_or_else(|_| current_dir.to_path_buf());
    let mut components = current_dir
        .strip_prefix(&home)
        .map_err(|_| Error::NamespaceRequired)?
        .components();

    let prefix = components
        .next()
        .and_then(|component| component.as_os_str().to_str())
        .ok_or(Error::NamespaceRequired)?;
    let name = components
        .next()
        .and_then(|component| component.as_os_str().to_str())
        .ok_or(Error::NamespaceRequired)?;

    Namespace::try_from(format!("{prefix}/{name}")).map_err(Error::from)
}

async fn resolve_namespace(model: &Model, namespace: Option<String>) -> Result<Namespace, Error> {
    if let Some(namespace) = namespace {
        return Ok(namespace.try_into()?);
    }

    let home = model.get_home().await?;
    let current_dir = std::env::current_dir()?;
    namespace_from_working_dir(home.as_ref(), &current_dir)
}

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
pub struct Args {
    #[command(subcommand)]
    command: Commands,

    /// Absolute path for the directory, where all packages will store their mutable files.
    /// Defaults to `~/QuiltSync` on first use. Ex. /home/user/QuiltSync
    #[arg(long)]
    home: Option<PathBuf>,

    /// Path to local domain
    #[arg(short, long)]
    domain: Option<PathBuf>,

    /// Enable INFO-level logging; use `RUST_LOG` for finer-grained filtering.
    #[arg(short, long, global = true)]
    pub(crate) verbose: bool,
}

/// The package a command acts on.
///
/// An omitted `--namespace` is inferred from the current working directory.
/// `install` keeps its own `namespace`: there, omitting it means "take it from
/// the URI", which is a different question.
#[derive(clap::Args, Debug)]
struct PackageRef {
    /// Namespace of the package. If omitted, infer it from the current
    /// working directory under the configured home.
    #[arg(short, long)]
    namespace: Option<String>,
}

impl PackageRef {
    async fn resolve(self, model: &Model) -> Result<Namespace, Error> {
        resolve_namespace(model, self.namespace).await
    }
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Browse remote manifest
    Browse {
        #[arg(value_name = "PKG_URI")]
        uri: String,
    },
    /// Create a new local package
    Create {
        /// Namespace for the package, e.g. foo/bar
        #[arg(short, long)]
        namespace: String,
        /// Optional source directory to populate the package from
        #[arg(short, long)]
        source: Option<PathBuf>,
        /// Commit message for the initial revision
        #[arg(short, long)]
        message: Option<String>,
    },
    /// Commit new package revision
    Commit {
        /// Commit message
        #[arg(short, long)]
        message: String,
        /// JSON string for user meta
        #[arg(short, long)]
        user_meta: Option<String>,
        #[command(flatten)]
        pkg: PackageRef,
        /// Workflow ID
        /// Ex. `"my_workflow"`
        /// Omit to use the bucket's default workflow.
        #[arg(short, long)]
        workflow: Option<String>,
        /// Commit with no workflow (explicit opt-out)
        #[arg(long, conflicts_with = "workflow")]
        no_workflow: bool,
    },
    /// Install package locally
    Install {
        /// Source URI for the package.
        /// Ex. `quilt+s3://bucket#package=foo/bar`
        #[arg(value_name = "PKG_URI")]
        uri: String,
        /// Namespace for the package, ex. foo/bar.
        #[arg(short, long)]
        namespace: Option<String>,
        /// Logical key relative to the root of the package to be installed locally.
        /// You can provide multiple paths.
        #[arg(short, long)]
        path: Option<Vec<PathBuf>>,
    },
    /// Authenticate against a Quilt stack
    Login {
        /// Code from the `https://QUILT_STACK/code` page
        #[arg(short, long)]
        code: Option<String>,
        #[arg(long)]
        host: Host,
    },
    /// List installed packages
    List {
        /// Print machine-readable JSON
        #[arg(long)]
        json: bool,
    },
    /// List the revisions of a package this copy has, newest first.
    ///
    /// Ordered by when this copy obtained each revision, which is all that is
    /// recorded locally — a manifest carries no timestamp of its own, so for a
    /// revision fetched from a remote this is the fetch time, not the commit
    /// time.
    Log {
        #[command(flatten)]
        pkg: PackageRef,
    },
    /// Pull
    Pull {
        #[command(flatten)]
        pkg: PackageRef,
    },
    /// Push
    Push {
        #[command(flatten)]
        pkg: PackageRef,
        /// S3 bucket (required for first push of local-only packages)
        #[arg(short, long, requires = "origin")]
        bucket: Option<String>,
        /// Remote host (required for first push of local-only packages)
        /// Ex. open.quiltdata.com
        #[arg(short, long, requires = "bucket")]
        origin: Option<Host>,
        /// Workflow ID for the first push (requires --bucket/--origin).
        /// Ex. `"my_workflow"`
        /// Omit to use the bucket's default workflow.
        /// Meaningful only on a first push: a subsequent push uploads an
        /// already-created commit whose workflow was chosen at commit time.
        #[arg(short, long)]
        workflow: Option<String>,
        /// First push with no workflow (explicit opt-out; requires --bucket/--origin)
        #[arg(long, conflicts_with = "workflow")]
        no_workflow: bool,
    },
    /// Show or switch your active role on a Quilt stack
    ///
    /// The active role is server-side and global: it decides what every Quilt
    /// client signed in as you can read and write, this CLI and the desktop
    /// app alike. Listing marks the active role with a leading asterisk.
    Role {
        /// Quilt stack to read the role from.
        /// Ex. open.quiltdata.com
        #[arg(long)]
        host: Host,
        /// Switch to this role instead of listing the roles you hold
        #[arg(long, value_name = "ROLE")]
        set: Option<String>,
    },
    /// Status of the package: modified, up-to-date, outdated
    Status {
        #[command(flatten)]
        pkg: PackageRef,
        /// Print machine-readable JSON
        #[arg(long)]
        json: bool,
    },
    /// Undo the newest commit, restoring the revision before it
    ///
    /// Available while the package's commit chain still reaches back, which in
    /// practice means before its first push. Refuses if any tracked file has
    /// uncommitted changes.
    UndoCommit {
        #[command(flatten)]
        pkg: PackageRef,
    },
    /// Uninstall package from local domain
    Uninstall {
        #[command(flatten)]
        pkg: PackageRef,
    },
}

#[allow(
    clippy::too_many_lines,
    reason = "cohesive top-level CLI command dispatch"
)]
pub async fn init(args: Args) -> Result<Std, Error> {
    // NOTE: every command should have some domain,
    //       because domain stores credentials
    //       It's optional for user, but we use one anyway.
    //       If it is None, we use:
    //         * home directory ~/.local/share/com.quiltdata.quilt-sync`
    //         * or temporary directory
    let root_dir = get_domain_dir(args.domain)?;
    let m = Model::from(root_dir);

    // Preserve an existing home, honor an explicit --home override, and set
    // the default for a new domain on first use.
    initialize_home(&m, args.home).await?;

    match args.command {
        Commands::Browse { uri } => {
            let args = browse::Input { uri };

            log::debug!("Browsing {args:?}");
            Ok(browse::command(m, args).await)
        }
        Commands::Create {
            namespace,
            source,
            message,
        } => {
            let args = create::Input {
                namespace: namespace.try_into()?,
                source,
                message,
            };

            log::debug!("Creating {args:?}");
            Ok(create::command(m, args).await)
        }
        Commands::Commit {
            pkg,
            message,
            user_meta,
            workflow,
            no_workflow,
        } => {
            let namespace = pkg.resolve(&m).await?;
            let user_meta = match &user_meta {
                Some(object) => match serde_json::from_str(object)? {
                    serde_json::Value::Object(object) => {
                        UserMeta::Set(serde_json::Value::Object(object))
                    }
                    _ => {
                        return Err(Error::CommitMetaInvalid(object.clone()));
                    }
                },
                None => UserMeta::Keep,
            };
            let workflow = commit_workflow_intent(workflow.as_deref(), no_workflow)?;
            let args = commit::Input {
                message,
                namespace,
                user_meta,
                workflow,
                host_config: None,
            };

            log::debug!("Committing {args:?}");
            Ok(commit::command(m, args).await)
        }
        Commands::Install {
            namespace,
            path,
            uri,
        } => {
            let args = install::Input {
                namespace: parse_optional_namespace(namespace)?,
                paths: path,
                uri,
            };

            log::debug!("Installing {args:?}");
            Ok(install::command(m, args).await)
        }
        Commands::Login { code, host } => {
            if let Some(code) = code {
                let args = login::Input { code, host };

                log::debug!("Logging in {args:?}");
                Ok(login::command(m, args).await)
            } else {
                // TODO: Check the lineage, if there are some `package.remote.catalog`
                Ok(Std::Err(Error::LoginRequired(host)))
            }
        }
        Commands::List { json } => {
            log::info!("Listing installed packages");
            Ok(list::command(m, json).await)
        }
        Commands::Log { pkg } => {
            let namespace = pkg.resolve(&m).await?;
            let args = history::Input { namespace };

            log::debug!("Logging {args:?}");
            Ok(history::command(m, args).await)
        }
        Commands::Pull { pkg } => {
            let namespace = pkg.resolve(&m).await?;
            let args = pull::Input {
                namespace,
                host_config: None,
            };

            log::debug!("Pull {args:?}");
            Ok(pull::command(m, args).await)
        }
        Commands::Push {
            pkg,
            bucket,
            origin,
            workflow,
            no_workflow,
        } => {
            let namespace = pkg.resolve(&m).await?;
            // The workflow flags only take effect on a first push, where
            // set_remote→recommit resolves them. On a subsequent push the
            // workflow was already decided at commit time, so reject the flags
            // here rather than silently ignore them.
            if bucket.is_none() && (workflow.is_some() || no_workflow) {
                return Err(Error::WorkflowRequiresBucket);
            }
            let workflow = commit_workflow_intent(workflow.as_deref(), no_workflow)?;
            let args = push::Input {
                namespace,
                host_config: None,
                bucket,
                origin,
                workflow,
            };

            log::debug!("Pushing {args:?}");
            Ok(push::command(m, args).await)
        }
        Commands::Role { host, set } => {
            let args = role::Input { host, set };

            log::debug!("Role {args:?}");
            Ok(role::command(m, args).await)
        }
        Commands::Status { pkg, json } => {
            let namespace = pkg.resolve(&m).await?;
            let args = status::Input {
                namespace,
                host_config: None,
            };

            log::debug!("Status {args:?}");
            Ok(status::command(m, args, json).await)
        }
        Commands::UndoCommit { pkg } => {
            let namespace = pkg.resolve(&m).await?;
            let args = undo_commit::Input { namespace };

            log::debug!("Undoing commit {args:?}");
            Ok(undo_commit::command(m, args).await)
        }
        Commands::Uninstall { pkg } => {
            let namespace = pkg.resolve(&m).await?;
            let args = uninstall::Input { namespace };

            log::debug!("Uninstalling {args:?}");
            Ok(uninstall::command(m, args).await)
        }
    }
}

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("Domain directory is required. We store files and credentials there")]
    Domain,

    #[error("Could not determine the home directory. Pass --home to specify one")]
    Home,

    #[error("quilt_rs error: {0}")]
    Quilt(quilt_rs::Error),

    #[error(
        r"
Please visit https://{0}/code to get your code.
Then run:
> quilt_rs login --host {0} --code YOUR_CODE"
    )]
    LoginRequired(Host),

    #[error("Package {0} not found")]
    NamespaceNotFound(Namespace),

    #[error(
        "Could not infer a namespace from the current directory. Pass --namespace or run inside <home>/<prefix>/<name>"
    )]
    NamespaceRequired,

    #[error("Invalid JSON for user_meta object. Object is required")]
    CommitMetaInvalid(String),

    #[error("workflow id cannot be empty; omit --workflow to use the bucket's default workflow")]
    WorkflowEmpty,

    #[error(
        "--workflow/--no-workflow apply only to a first push; pass --bucket and --origin to set the remote, or omit them (the workflow was chosen at commit time)"
    )]
    WorkflowRequiresBucket,

    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),

    #[cfg(test)]
    #[error("Test failed: {0}")]
    Test(String),

    #[error("Failed to write or read: {0}")]
    Io(#[from] std::io::Error),
}

impl From<quilt_rs::Error> for Error {
    fn from(err: quilt_rs::Error) -> Error {
        Error::Quilt(err)
    }
}

impl From<quilt_uri::UriError> for Error {
    fn from(err: quilt_uri::UriError) -> Error {
        Error::Quilt(quilt_rs::Error::Uri(err))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::str::FromStr;
    use test_log::test;

    use crate::cli::model::create_model_in_temp_dir;
    use crate::cli::model::install_package_into_temp_dir;

    #[test]
    fn commit_workflow_intent_omit_maps_to_bucket_default() {
        assert_eq!(
            commit_workflow_intent(None, false).unwrap(),
            WorkflowIntent::BucketDefault
        );
    }

    #[test]
    fn commit_workflow_intent_no_workflow_flag_opts_out() {
        assert_eq!(
            commit_workflow_intent(None, true).unwrap(),
            WorkflowIntent::NoWorkflow
        );
    }

    #[test]
    fn commit_workflow_intent_named_id_maps_to_named() {
        assert_eq!(
            commit_workflow_intent(Some("x"), false).unwrap(),
            WorkflowIntent::Named("x".to_string())
        );
    }

    #[test]
    fn commit_workflow_intent_blank_id_is_rejected() {
        assert!(matches!(
            commit_workflow_intent(Some(""), false),
            Err(Error::WorkflowEmpty)
        ));
        assert!(matches!(
            commit_workflow_intent(Some("   "), false),
            Err(Error::WorkflowEmpty)
        ));
    }

    /// `--set` is what separates switching from listing, and dropping it
    /// would silently degrade `quilt role --set X` into a plain listing.
    #[test]
    fn role_set_flag_is_parsed() {
        let listing = Args::try_parse_from(["quilt", "role", "--host", "example.com"]).unwrap();
        assert!(matches!(listing.command, Commands::Role { set: None, .. }));

        let switching = Args::try_parse_from([
            "quilt",
            "role",
            "--host",
            "example.com",
            "--set",
            "ReadOnly",
        ])
        .unwrap();
        let Commands::Role { host, set } = switching.command else {
            panic!("expected the role command");
        };
        assert_eq!(host.to_string(), "example.com");
        assert_eq!(set.as_deref(), Some("ReadOnly"));
    }

    #[test]
    fn verbose_flag_is_global() {
        let before_subcommand = Args::try_parse_from(["quilt", "--verbose", "list"]).unwrap();
        assert!(before_subcommand.verbose);

        let after_subcommand = Args::try_parse_from(["quilt", "list", "--verbose"]).unwrap();
        assert!(after_subcommand.verbose);

        let default = Args::try_parse_from(["quilt", "list"]).unwrap();
        assert!(!default.verbose);
    }

    #[test]
    fn json_flag_is_available_on_read_commands() {
        let list = Args::try_parse_from(["quilt", "list", "--json"]).unwrap();
        assert!(matches!(list.command, Commands::List { json: true }));

        let status =
            Args::try_parse_from(["quilt", "status", "-n", "demo/sales", "--json"]).unwrap();
        assert!(matches!(
            status.command,
            Commands::Status { json: true, .. }
        ));

        let default = Args::try_parse_from(["quilt", "list"]).unwrap();
        assert!(matches!(default.command, Commands::List { json: false }));
    }

    #[test]
    fn package_namespace_flag_is_optional() {
        let inferred = Args::try_parse_from(["quilt", "status"]).unwrap();
        assert!(matches!(
            inferred.command,
            Commands::Status {
                pkg: PackageRef { namespace: None },
                json: false
            }
        ));

        let explicit =
            Args::try_parse_from(["quilt", "status", "--namespace", "demo/sales"]).unwrap();
        assert!(matches!(
            explicit.command,
            Commands::Status {
                pkg: PackageRef { namespace: Some(namespace) },
                json: false
            } if namespace == "demo/sales"
        ));
    }

    #[test]
    fn namespace_from_working_dir_uses_package_components() -> Result<(), Error> {
        let home = Path::new("/home/user/QuiltSync");
        let current_dir = Path::new("/home/user/QuiltSync/demo/sales/src");

        assert_eq!(
            namespace_from_working_dir(home, current_dir)?,
            Namespace::from(("demo", "sales"))
        );
        Ok(())
    }

    #[test]
    fn namespace_from_working_dir_requires_a_package_path() {
        let home = Path::new("/home/user/QuiltSync");

        assert!(matches!(
            namespace_from_working_dir(home, Path::new("/home/user/QuiltSync")),
            Err(Error::NamespaceRequired)
        ));
        assert!(matches!(
            namespace_from_working_dir(home, Path::new("/home/user/other/demo/sales")),
            Err(Error::NamespaceRequired)
        ));
    }

    #[test]
    fn test_parse_optional_namespace() -> Result<(), Error> {
        // Test None case
        assert!(parse_optional_namespace(None)?.is_none());

        // Test Some valid namespace
        let ns = parse_optional_namespace(Some("foo/bar".to_string()))?.unwrap();
        assert_eq!(ns.to_string(), "foo/bar");

        // Test Some invalid namespace
        let err = parse_optional_namespace(Some("invalid".to_string())).unwrap_err();
        assert!(matches!(err, Error::Quilt(_)));

        Ok(())
    }

    #[test]
    fn test_get_domain_dir() -> Result<(), Error> {
        // Test with provided directory
        let test_dir = PathBuf::from("/test/path");
        assert_eq!(get_domain_dir(Some(test_dir.clone()))?, test_dir);

        // Test with None (should use default location)
        if let Some(local_dir) = dirs::data_local_dir() {
            let expected = local_dir.join(DOMAIN_DIR_NAMESPACE);
            assert_eq!(get_domain_dir(None)?, expected);
        } else {
            // If data_local_dir() returns None, get_domain_dir should return Error::Domain
            assert!(matches!(get_domain_dir(None), Err(Error::Domain)));
        }

        Ok(())
    }

    #[test]
    fn test_get_default_home_dir() -> Result<(), Error> {
        let user_home = dirs::home_dir().ok_or(Error::Home)?;
        assert_eq!(
            get_default_home_dir()?,
            user_home.join(quilt_rs::DEFAULT_HOME_DIR_NAME)
        );
        Ok(())
    }

    #[test(tokio::test)]
    async fn test_list_uses_default_home_without_flag() -> Result<(), Error> {
        let domain_temp_dir = tempfile::tempdir()?;
        let list_args = Args {
            home: None,
            domain: Some(domain_temp_dir.path().to_path_buf()),
            verbose: false,
            command: Commands::List { json: false },
        };

        let mut output = Vec::new();
        let result = init(list_args).await?;
        print(result, &mut output, &mut Vec::new())?;
        assert_eq!(
            String::from_utf8(output).unwrap(),
            "No installed packages\n"
        );

        let stored_home = quilt_rs::LocalDomain::new(domain_temp_dir.path())
            .get_home()
            .await?;
        assert_eq!(stored_home.as_ref(), &get_default_home_dir()?);

        Ok(())
    }

    #[test(tokio::test)]
    async fn test_missing_home_lineage_is_repaired_without_flag() -> Result<(), Error> {
        let (model, domain_temp_dir) = Model::from_temp_dir()?;
        let paths = quilt_rs::paths::DomainPaths::new(domain_temp_dir.path().to_path_buf());
        std::fs::create_dir_all(paths.dot_quilt_dir())?;
        std::fs::write(paths.lineage(), br#"{"packages":{},"home":""}"#)?;

        initialize_home(&model, None).await?;

        assert_eq!(model.get_home().await?.as_ref(), &get_default_home_dir()?);
        Ok(())
    }

    #[test(tokio::test)]
    async fn test_existing_home_is_preserved_without_flag() -> Result<(), Error> {
        let (model, _domain_temp_dir) = Model::from_temp_dir()?;
        let home_temp_dir = tempfile::tempdir()?;
        model.set_home(home_temp_dir.path()).await?;

        initialize_home(&model, None).await?;

        assert_eq!(
            model.get_home().await?.as_ref(),
            &home_temp_dir.path().to_path_buf()
        );
        Ok(())
    }

    #[test(tokio::test)]
    async fn live_install() -> Result<(), Error> {
        use crate::cli::fixtures::packages::workflow_null as pkg;

        // Create temporary directory for domain
        let domain_temp_dir = tempfile::tempdir()?;
        let domain = Some(domain_temp_dir.path().to_path_buf());

        let working_temp_dir = tempfile::tempdir()?;
        let home = Some(working_temp_dir.path().to_path_buf());

        // First install the package
        let install_args = Args {
            home,
            domain,
            verbose: false,
            command: Commands::Install {
                namespace: Some(Namespace::from(pkg::NAMESPACE).to_string()),
                uri: pkg::URI.to_string(),
                path: None,
            },
        };
        let mut output = Vec::new();
        let result = init(install_args).await?;
        print(result, &mut output, &mut Vec::new())?;
        let output_str = String::from_utf8(output).unwrap();
        assert_eq!(
            output_str,
            format!(
                "Installed package \"{}\"\nNo paths installed\n",
                pkg::NAMESPACE_STR,
            )
        );

        Ok(())
    }

    #[test(tokio::test)]
    async fn live_commit_valid() -> Result<(), Error> {
        use crate::cli::fixtures::packages::workflow_null as pkg;

        let (_, _, temp_dir) = install_package_into_temp_dir(pkg::URI).await?;

        let commit_args = Args {
            home: Some(temp_dir.path().to_path_buf()),
            domain: Some(temp_dir.path().to_path_buf()),
            verbose: false,
            command: Commands::Commit {
                message: pkg::MESSAGE.to_string(),
                pkg: PackageRef {
                    namespace: Some(pkg::NAMESPACE_STR.to_string()),
                },
                user_meta: None,
                workflow: None,
                no_workflow: true,
            },
        };

        // Test init with valid arguments
        let mut output = Vec::new();
        let result = init(commit_args).await?;
        print(result, &mut output, &mut Vec::new())?;
        let output_str = String::from_utf8(output).unwrap();
        assert_eq!(
            output_str,
            "New commit \"095017e53f4c8e0a07c82e562d088aa0e0f7a9ecaf2dce74a7607fac9085e98f\" created\n".to_string()
        );

        Ok(())
    }

    #[test(tokio::test)]
    async fn live_commit_invalid() -> Result<(), Error> {
        use crate::cli::fixtures::packages::workflow_null as pkg;

        let (_, _, temp_dir) = install_package_into_temp_dir(pkg::URI).await?;

        let commit_args = Args {
            domain: Some(temp_dir.path().to_path_buf()),
            home: Some(temp_dir.path().to_path_buf()),
            verbose: false,
            command: Commands::Commit {
                message: "Any message".to_string(),
                pkg: PackageRef {
                    namespace: Some("in/valid".to_string()),
                },
                user_meta: None,
                workflow: None,
                no_workflow: true,
            },
        };

        // Test init with valid arguments
        let mut output = Vec::new();
        let result = init(commit_args).await?;
        print(result, &mut Vec::new(), &mut output)?;
        let output_str = String::from_utf8(output).unwrap();
        assert_eq!(output_str, "Package in/valid not found\n".to_string());

        Ok(())
    }

    /// The workflow flags are first-push-only: without `--bucket` there is no
    /// remote to set, so `--workflow` is rejected at the dispatch boundary.
    #[test(tokio::test)]
    async fn test_push_workflow_without_bucket_errors() -> Result<(), Error> {
        let (_, temp_dir) = create_model_in_temp_dir().await?;

        let push_args = Args {
            domain: Some(temp_dir.path().to_path_buf()),
            home: Some(temp_dir.path().to_path_buf()),
            verbose: false,
            command: Commands::Push {
                pkg: PackageRef {
                    namespace: Some("foo/bar".to_string()),
                },
                bucket: None,
                origin: None,
                workflow: Some("x".to_string()),
                no_workflow: false,
            },
        };

        assert!(matches!(
            init(push_args).await,
            Err(Error::WorkflowRequiresBucket)
        ));

        Ok(())
    }

    /// `--no-workflow` is likewise first-push-only and rejected without `--bucket`.
    #[test(tokio::test)]
    async fn test_push_no_workflow_without_bucket_errors() -> Result<(), Error> {
        let (_, temp_dir) = create_model_in_temp_dir().await?;

        let push_args = Args {
            domain: Some(temp_dir.path().to_path_buf()),
            home: Some(temp_dir.path().to_path_buf()),
            verbose: false,
            command: Commands::Push {
                pkg: PackageRef {
                    namespace: Some("foo/bar".to_string()),
                },
                bucket: None,
                origin: None,
                workflow: None,
                no_workflow: true,
            },
        };

        assert!(matches!(
            init(push_args).await,
            Err(Error::WorkflowRequiresBucket)
        ));

        Ok(())
    }

    /// With `--bucket`/`--origin` present the workflow flag is accepted: the
    /// boundary check passes and the command threads the intent into
    /// `push::Input`, reaching `push_package` (which then reports the missing
    /// local package rather than a workflow error).
    #[test(tokio::test)]
    async fn test_push_workflow_with_bucket_is_accepted() -> Result<(), Error> {
        let (_, temp_dir) = create_model_in_temp_dir().await?;

        let push_args = Args {
            domain: Some(temp_dir.path().to_path_buf()),
            home: Some(temp_dir.path().to_path_buf()),
            verbose: false,
            command: Commands::Push {
                pkg: PackageRef {
                    namespace: Some("foo/bar".to_string()),
                },
                bucket: Some("some-bucket".to_string()),
                origin: Some(Host::from_str("open.quiltdata.com").unwrap()),
                workflow: Some("x".to_string()),
                no_workflow: false,
            },
        };

        let mut output = Vec::new();
        let result = init(push_args).await?;
        print(result, &mut Vec::new(), &mut output)?;
        let output_str = String::from_utf8(output).unwrap();
        assert_eq!(output_str, "Package foo/bar not found\n");

        Ok(())
    }

    #[test(tokio::test)]
    async fn live_pull_valid() -> Result<(), Error> {
        use crate::cli::fixtures::packages::outdated as pkg;

        let (_, _, temp_dir) = install_package_into_temp_dir(pkg::URI).await?;

        let pull_args = Args {
            domain: Some(temp_dir.path().to_path_buf()),
            home: Some(temp_dir.path().to_path_buf()),
            verbose: false,
            command: Commands::Pull {
                pkg: PackageRef {
                    namespace: Some(pkg::NAMESPACE_STR.to_string()),
                },
            },
        };

        // Test init with valid arguments
        let mut output = Vec::new();
        let result = init(pull_args).await?;
        print(result, &mut output, &mut Vec::new())?;
        let output_str = String::from_utf8(output).unwrap();
        // No file group: `install` ran with `paths: None`, so this copy tracks
        // nothing and every path the revision changed falls outside the touch
        // set — nothing moved on disk, and claiming otherwise would be false.
        // The revision's own message is then the only thing the pull can report,
        // which is exactly why it is worth reporting: without it the line says
        // no more than it did before.
        assert_eq!(
            output_str,
            format!(
                "Revision \"{}\" pulled\nLatest revision: Today's Date: 2024-07-29 11:53:53\n",
                pkg::LATEST_TOP_HASH
            )
        );

        Ok(())
    }

    /// The report, end to end against a real package. This is the only test
    /// that proves the whole path — engine grouping, the CLI's wording, and a
    /// manifest pair that actually differs — rather than a hand-built delta.
    ///
    /// It is also the span case: `latest` is r3, so installing r1 and pulling
    /// crosses two revisions in one operation, and only r3's message is in hand.
    /// There is no parent pointer to walk, so nothing can report r2's.
    ///
    /// The silences are the load-bearing half. `install` takes no paths, so this
    /// copy tracks nothing: `modify.txt` and `keep.txt` were modified and
    /// `remove.txt` removed, and none may appear — nothing moved on disk, and
    /// naming them would report writes that did not happen.
    #[test(tokio::test)]
    async fn live_pull_reports_what_the_revision_brought() -> Result<(), Error> {
        use crate::cli::fixtures::packages::revision_report as pkg;

        let (_, _, temp_dir) = install_package_into_temp_dir(pkg::R1_URI).await?;

        let pull_args = Args {
            domain: Some(temp_dir.path().to_path_buf()),
            home: Some(temp_dir.path().to_path_buf()),
            verbose: false,
            command: Commands::Pull {
                pkg: PackageRef {
                    namespace: Some(pkg::NAMESPACE_STR.to_string()),
                },
            },
        };

        let mut output = Vec::new();
        let result = init(pull_args).await?;
        print(result, &mut output, &mut Vec::new())?;
        let output_str = String::from_utf8(output).unwrap();

        assert_eq!(
            output_str,
            format!(
                concat!(
                    "Revision \"{}\" pulled\n",
                    "7 files new, not downloaded:\n",
                    "  add/deeply/nested/directory/with/a/very-long-name/summary-of-everything.parquet\n",
                    "  add/five.txt\n",
                    "  add/four.txt\n",
                    "  add/one.txt\n",
                    "  add/six.txt\n",
                    "  add/three.txt\n",
                    "  add/two.txt\n",
                    "Latest revision: {}\n",
                ),
                pkg::R3_TOP_HASH,
                pkg::R3_MESSAGE,
            )
        );

        // Stated as its own assertion rather than left implicit in the string
        // above: these three changed on the remote and must appear in no group,
        // because this copy does not track them.
        //
        // Checked against the group lines only, not the whole output: the
        // author's message is prose and legitimately names files — r3's says
        // "modifies keep.txt" — so a substring search over everything would
        // fail on the message rather than on a group, which is what happened
        // when this was written the naive way.
        let groups = output_str
            .split("Latest revision:")
            .next()
            .expect("split always yields one part");
        for silent in ["modify.txt", "keep.txt", "remove.txt"] {
            assert!(
                !groups.contains(silent),
                "{silent} changed on the remote but nothing moved here, so no group may name it"
            );
        }
        Ok(())
    }

    /// The same fixture with its files actually checked out, which is what makes
    /// three of the four groups reachable: a tracked path the remote modified is
    /// rewritten (`updated`), a tracked path it dropped is deleted (`removed`),
    /// and its additions stay listed under the CLI's sparse scope.
    ///
    /// The pair with the test above is the point. Same revisions, same remote
    /// changes, and the report differs entirely — because what a pull *reports*
    /// follows what this copy tracks, not what the remote did. That is the claim
    /// the grouping rests on, and no unit test can make it against real
    /// manifests.
    ///
    /// The fourth group, `added` proper, is unreachable here by design: it needs
    /// whole-package scope, and the CLI always asks for the narrow one so that
    /// state a desktop wrote cannot change what a script does.
    #[test(tokio::test)]
    async fn live_pull_reports_updates_and_removals_for_tracked_paths() -> Result<(), Error> {
        use crate::cli::fixtures::packages::revision_report as pkg;
        use crate::cli::model::install_paths_into_temp_dir;

        let tracked = ["keep.txt", "modify.txt", "remove.txt"]
            .iter()
            .map(std::path::PathBuf::from)
            .collect();
        let (_, _, temp_dir) = install_paths_into_temp_dir(pkg::R1_URI, Some(tracked)).await?;

        let pull_args = Args {
            domain: Some(temp_dir.path().to_path_buf()),
            home: Some(temp_dir.path().to_path_buf()),
            verbose: false,
            command: Commands::Pull {
                pkg: PackageRef {
                    namespace: Some(pkg::NAMESPACE_STR.to_string()),
                },
            },
        };

        let mut output = Vec::new();
        let result = init(pull_args).await?;
        print(result, &mut output, &mut Vec::new())?;
        let output_str = String::from_utf8(output).unwrap();

        assert_eq!(
            output_str,
            format!(
                concat!(
                    "Revision \"{}\" pulled\n",
                    "7 files new, not downloaded:\n",
                    "  add/deeply/nested/directory/with/a/very-long-name/summary-of-everything.parquet\n",
                    "  add/five.txt\n",
                    "  add/four.txt\n",
                    "  add/one.txt\n",
                    "  add/six.txt\n",
                    "  add/three.txt\n",
                    "  add/two.txt\n",
                    "2 files updated:\n",
                    "  keep.txt\n",
                    "  modify.txt\n",
                    "1 file removed:\n",
                    "  remove.txt\n",
                    "Latest revision: {}\n",
                ),
                pkg::R3_TOP_HASH,
                pkg::R3_MESSAGE,
            )
        );
        Ok(())
    }

    /// Local work the remote did not touch survives the pull, and appears in no
    /// group — it is the user's change, not news from the remote.
    ///
    /// Installed from **r2** rather than r1 for a reason worth keeping: every
    /// path r1 holds is touched by r3, so from r1 there is nothing for a local
    /// edit to survive on without colliding. `add/one.txt` arrives in r2 and r3
    /// leaves it alone.
    #[test(tokio::test)]
    async fn live_pull_keeps_local_work_the_remote_did_not_touch() -> Result<(), Error> {
        use crate::cli::fixtures::packages::revision_report as pkg;
        use crate::cli::model::install_paths_into_temp_dir;

        let tracked = ["add/one.txt", "keep.txt"]
            .iter()
            .map(std::path::PathBuf::from)
            .collect();
        let (_, _, temp_dir) = install_paths_into_temp_dir(pkg::R2_URI, Some(tracked)).await?;

        let edited = temp_dir.path().join(pkg::NAMESPACE_STR).join("add/one.txt");
        std::fs::write(&edited, "MY LOCAL EDIT\n").expect("the path was just checked out");

        let pull_args = Args {
            domain: Some(temp_dir.path().to_path_buf()),
            home: Some(temp_dir.path().to_path_buf()),
            verbose: false,
            command: Commands::Pull {
                pkg: PackageRef {
                    namespace: Some(pkg::NAMESPACE_STR.to_string()),
                },
            },
        };

        let mut output = Vec::new();
        let result = init(pull_args).await?;
        print(result, &mut output, &mut Vec::new())?;
        let output_str = String::from_utf8(output).unwrap();

        assert_eq!(
            output_str,
            format!(
                concat!(
                    "Revision \"{}\" pulled\n",
                    "1 file new, not downloaded:\n",
                    "  add/six.txt\n",
                    "1 file updated:\n",
                    "  keep.txt\n",
                    "Latest revision: {}\n",
                ),
                pkg::R3_TOP_HASH,
                pkg::R3_MESSAGE,
            )
        );

        // The half a report cannot show: the edit is still there. A pull that
        // named nothing and quietly overwrote it would pass the assertion above.
        assert_eq!(
            std::fs::read_to_string(&edited).unwrap(),
            "MY LOCAL EDIT\n",
            "the pull overwrote local work the remote had not touched"
        );
        Ok(())
    }

    /// A path added on both sides with differing content blocks the whole pull,
    /// so there is no partial arrival and no report at all.
    ///
    /// The reconcile is atomic: `base` advances only when every path applies. A
    /// report here would describe files that did not move.
    #[test(tokio::test)]
    async fn live_pull_blocked_by_a_conflict_reports_nothing() -> Result<(), Error> {
        use crate::cli::fixtures::packages::revision_report as pkg;
        use crate::cli::model::install_paths_into_temp_dir;

        let tracked = vec![std::path::PathBuf::from("keep.txt")];
        let (_, _, temp_dir) = install_paths_into_temp_dir(pkg::R1_URI, Some(tracked)).await?;

        // Same logical key r2 adds, different bytes: the both-added arm.
        let root = temp_dir.path().join(pkg::NAMESPACE_STR).join("add");
        std::fs::create_dir_all(&root).expect("the package root exists");
        std::fs::write(root.join("one.txt"), "DIFFERENT CONTENT THAN THE REMOTE\n")
            .expect("just created the directory");

        let pull_args = Args {
            domain: Some(temp_dir.path().to_path_buf()),
            home: Some(temp_dir.path().to_path_buf()),
            verbose: false,
            command: Commands::Pull {
                pkg: PackageRef {
                    namespace: Some(pkg::NAMESPACE_STR.to_string()),
                },
            },
        };

        // The refusal travels as a `Std::Err`, not as an `Err` — the CLI's
        // output contract sends it to stderr and exits non-zero rather than
        // propagating. So the assertion is about what the user sees.
        let mut out = Vec::new();
        let mut errs = Vec::new();
        let result = init(pull_args).await?;
        print(result, &mut out, &mut errs).ok();
        let out = String::from_utf8(out).unwrap();
        let errs = String::from_utf8(errs).unwrap();

        assert!(
            errs.contains("add/one.txt"),
            "the refusal must name the conflicting path: {errs}"
        );
        // The claim worth testing: nothing was applied, so nothing is reported.
        // A report here would describe files that did not move.
        assert!(
            out.is_empty(),
            "a blocked pull applies nothing and must report nothing, got: {out}"
        );
        Ok(())
    }

    #[test(tokio::test)]
    async fn test_pull_invalid() -> Result<(), Error> {
        // Create temporary directory for domain
        let (_, temp_dir) = create_model_in_temp_dir().await?;

        let pull_args = Args {
            domain: Some(temp_dir.path().to_path_buf()),
            home: Some(temp_dir.path().to_path_buf()),
            verbose: false,
            command: Commands::Pull {
                pkg: PackageRef {
                    namespace: Some("in/valid".to_string()),
                },
            },
        };

        // Test init with invalid namespace
        let mut output = Vec::new();
        let result = init(pull_args).await?;
        print(result, &mut Vec::new(), &mut output)?;
        let output_str = String::from_utf8(output).unwrap();
        assert_eq!(output_str, "Package in/valid not found\n");

        Ok(())
    }

    #[test(tokio::test)]
    async fn live_uninstall_valid() -> Result<(), Error> {
        use crate::cli::fixtures::packages::default as pkg;

        let (_, _, temp_dir) = install_package_into_temp_dir(pkg::URI).await?;

        let uninstall_args = Args {
            domain: Some(temp_dir.path().to_path_buf()),
            home: Some(temp_dir.path().to_path_buf()),
            verbose: false,
            command: Commands::Uninstall {
                pkg: PackageRef {
                    namespace: Some(pkg::NAMESPACE_STR.to_string()),
                },
            },
        };

        // Test init with valid arguments
        let mut output = Vec::new();
        let result = init(uninstall_args).await?;
        print(result, &mut output, &mut Vec::new())?;
        let output_str = String::from_utf8(output).unwrap();
        assert_eq!(
            output_str,
            format!("Package {} successfully uninstalled\n", pkg::NAMESPACE_STR)
        );

        Ok(())
    }

    #[test(tokio::test)]
    async fn test_uninstall_invalid() -> Result<(), Error> {
        // Create temporary directory for domain
        let (_, temp_dir) = create_model_in_temp_dir().await?;

        let uninstall_args = Args {
            domain: Some(temp_dir.path().to_path_buf()),
            home: Some(temp_dir.path().to_path_buf()),
            verbose: false,
            command: Commands::Uninstall {
                pkg: PackageRef {
                    namespace: Some("in/valid".to_string()),
                },
            },
        };

        // Test init with invalid namespace
        let mut output = Vec::new();
        let result = init(uninstall_args).await?;
        print(result, &mut Vec::new(), &mut output)?;
        let output_str = String::from_utf8(output).unwrap();
        assert!(output_str.ends_with("The given package is not installed: in/valid\n"));

        Ok(())
    }

    #[test(tokio::test)]
    async fn test_list_invalid() -> Result<(), Error> {
        use std::fs::Permissions;
        use std::os::unix::fs::PermissionsExt;
        use tempfile::Builder;

        // Create write-only temporary directory to trigger permission error
        let write_only = Permissions::from_mode(0o200);
        let temp_dir = Builder::new().permissions(write_only).tempdir()?;

        let list_args = Args {
            domain: Some(temp_dir.path().to_path_buf()),
            home: Some(temp_dir.path().to_path_buf()),
            verbose: false,
            command: Commands::List { json: false },
        };

        // Default home initialization now reaches the same write-protected
        // lineage before the list command can render a command-level error.
        let err = init(list_args).await.unwrap_err();
        assert!(err.to_string().contains("Permission denied"));

        Ok(())
    }

    #[test(tokio::test)]
    async fn test_list_valid() -> Result<(), Error> {
        // Create temporary directory for domain
        let (_, temp_dir) = create_model_in_temp_dir().await?;

        let list_args = Args {
            domain: Some(temp_dir.path().to_path_buf()),
            home: Some(temp_dir.path().to_path_buf()),
            verbose: false,
            command: Commands::List { json: false },
        };

        // Test init with empty domain
        let mut output = Vec::new();
        let result = init(list_args).await?;
        print(result, &mut output, &mut Vec::new())?;
        let output_str = String::from_utf8(output).unwrap();
        assert_eq!(output_str, "No installed packages\n");

        Ok(())
    }

    #[test(tokio::test)]
    async fn test_install_invalid() -> Result<(), Error> {
        use crate::cli::fixtures::packages::invalid as pkg;

        // Create temporary directory for domain
        let temp_dir = tempfile::tempdir()?;
        let domain = Some(temp_dir.path().to_path_buf());
        let home = domain.clone();

        let install_args = Args {
            domain,
            home,
            verbose: false,
            command: Commands::Install {
                namespace: None,
                uri: pkg::URI.to_string(),
                path: None,
            },
        };

        // Test init with invalid URI
        let mut output = Vec::new();
        let result = init(install_args).await?;
        print(result, &mut Vec::new(), &mut output)?;
        let output_str = String::from_utf8(output).unwrap();
        assert_eq!(
            output_str,
            format!(
                "quilt_rs error: Invalid package URI: S3 package URI must contain a fragment: {}\n",
                pkg::URI
            )
        );

        Ok(())
    }

    #[test(tokio::test)]
    async fn live_browse_valid() -> Result<(), Error> {
        use crate::cli::fixtures::get_browse_output;
        use crate::cli::fixtures::packages::default as pkg;

        // Create temporary directory for domain
        let temp_dir = tempfile::tempdir()?;
        let uri = format!("{}&path={}", pkg::URI_LATEST, pkg::README_LK_ESCAPED);

        let browse_args = Args {
            domain: Some(temp_dir.path().to_path_buf()),
            home: Some(temp_dir.path().to_path_buf()),
            verbose: false,
            command: Commands::Browse { uri },
        };

        // Test init with valid URI
        let mut output = Vec::new();
        let result = init(browse_args).await?;
        print(result, &mut output, &mut Vec::new())?;
        let output_str = String::from_utf8(output).unwrap();
        assert_eq!(output_str, format!("{}\n", get_browse_output()?));

        Ok(())
    }

    #[test(tokio::test)]
    async fn test_browse_invalid() -> Result<(), Error> {
        use crate::cli::fixtures::packages::invalid as pkg;

        // Create temporary directory for domain
        let temp_dir = tempfile::tempdir()?;

        let browse_args = Args {
            domain: Some(temp_dir.path().to_path_buf()),
            home: Some(temp_dir.path().to_path_buf()),
            verbose: false,
            command: Commands::Browse {
                uri: pkg::URI.to_string(),
            },
        };

        // Test init with invalid URI
        let mut output = Vec::new();
        let result = init(browse_args).await?;
        print(result, &mut Vec::new(), &mut output)?;
        let output_str = String::from_utf8(output).unwrap();
        assert_eq!(
            output_str,
            format!(
                "quilt_rs error: Invalid package URI: S3 package URI must contain a fragment: {}\n",
                pkg::URI
            )
        );

        Ok(())
    }
}