mitosis-db 0.2.0

Copy-on-write Postgres clones for AI agent tasks on macOS APFS
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
use crate::budget;
use crate::client;
use crate::config::{Config, ConfigEntry};
use crate::daemon;
use crate::doctor;
use crate::envfile;
use crate::error::{ErrorCode, MitosisError, Result};
use crate::mcp;
use crate::names::{format_duration, parse_duration, validate_name};
use crate::paths::Home;
use crate::protocol::{
    CloneCreateArgs, CloneInfo, MigrateCmd, Request, Response, TemplateInfo, TemplateInitArgs,
    TemplateSetArgs, TemplateSettings, TemplateSource,
};
use crate::service;
use crate::templates::now;
use clap::{Parser, Subcommand};
use std::process::ExitCode;
use std::time::{Duration, Instant};

#[derive(Parser)]
#[command(
    name = "mitosis",
    version,
    about = "Copy-on-write Postgres clones for AI agent tasks"
)]
struct Cli {
    #[command(subcommand)]
    command: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// Build, refresh and list templates.
    Template {
        #[command(subcommand)]
        command: TemplateCmd,
    },
    /// Create a clone of a template and print its URL.
    Clone {
        #[arg(long, default_value = "main")]
        template: String,
        #[arg(long)]
        name: Option<String>,
        /// Time to live, like 30m, 2h or 1d.
        #[arg(long, default_value = "2h")]
        ttl: String,
        /// Keep fsync on (slower, survives a crash).
        #[arg(long)]
        durable: bool,
        /// Destroy a running clone of this name first (same URL, fresh data).
        #[arg(long)]
        fresh: bool,
        /// Never expire; needs --name. Destroy it with `mitosis destroy <name> --force`.
        #[arg(long)]
        protect: bool,
        /// Write the URL into this .env file (restored when the clone is destroyed).
        #[arg(long)]
        env_file: Option<std::path::PathBuf>,
        /// The variable to set in --env-file.
        #[arg(long, requires = "env_file")]
        env_var: Option<String>,
        /// How long to wait for room under the limits, like 30s or 2m; 0 fails at once.
        #[arg(long)]
        wait: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Print `DATABASE_URL=<url>` (or --var) for a running clone.
    Env {
        id_or_name: String,
        #[arg(long, default_value = "DATABASE_URL")]
        var: String,
    },
    /// List clones.
    List {
        #[arg(long)]
        json: bool,
    },
    /// Live view of clones, memory and disk against the limits (q to quit).
    Top,
    /// Destroy a clone by id or name.
    Destroy {
        id_or_name: String,
        /// Needed for a protected clone.
        #[arg(long)]
        force: bool,
        /// Also release the name's reserved port and password.
        #[arg(long)]
        forget: bool,
    },
    /// Make a running clone the newest generation of its template (or of --template).
    Promote {
        clone: String,
        /// Promote into this template instead of the clone's own; created when it does not exist.
        #[arg(long)]
        template: Option<String>,
    },
    /// Remove expired clones and leftovers.
    Gc,
    /// Check the home, config, daemon, Postgres installs and templates for problems.
    Doctor {
        /// Finish pending .env restores and run gc.
        #[arg(long)]
        fix: bool,
        #[arg(long)]
        json: bool,
    },
    /// Run the daemon in the foreground, or manage it.
    Daemon {
        #[command(subcommand)]
        command: Option<DaemonCmd>,
    },
    /// Serve the MCP tools over stdio.
    Mcp,
    /// Keep the daemon running from login (launchd user agent).
    Service {
        #[command(subcommand)]
        command: ServiceCmd,
    },
    /// Show the settings and where each value comes from, or change one.
    Config {
        #[command(subcommand)]
        command: Option<ConfigCmd>,
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand)]
enum ConfigCmd {
    /// Write a setting to config.toml and tell a running daemon to reload.
    Set {
        /// max_clones, min_free_disk, ram_budget, disk_budget, queue_wait or clone_disk_warn.
        key: String,
        /// A number, a size like 4GB, a duration like 60s, or off.
        value: String,
    },
}

#[derive(Subcommand)]
enum TemplateCmd {
    /// Build a template from a database URL or a seed command.
    Init {
        #[arg(default_value = "main")]
        name: String,
        /// Copy an existing database with pg_dump.
        #[arg(long, conflicts_with = "seed", required_unless_present = "seed")]
        from_url: Option<String>,
        /// Shell command run in this folder with DATABASE_URL set.
        #[arg(long)]
        seed: Option<String>,
        #[arg(long)]
        database: Option<String>,
        /// Migrations folder; the template is flagged stale when it changes.
        #[arg(long)]
        migrations: Option<std::path::PathBuf>,
        #[arg(long)]
        pg_version: Option<u32>,
        #[command(flatten)]
        settings: SettingsFlags,
    },
    /// Rebuild a template from its recorded source.
    Refresh {
        #[arg(default_value = "main")]
        name: String,
        /// Copy the current generation and run only the migrate command on it.
        #[arg(long)]
        layered: bool,
    },
    /// Change a template's settings.
    Set {
        #[arg(default_value = "main")]
        name: String,
        #[command(flatten)]
        settings: SettingsFlags,
        /// Restart automatic builds stopped by a rollback.
        #[arg(long)]
        resume: bool,
    },
    /// List templates.
    List {
        #[arg(long)]
        json: bool,
    },
    /// List a template's generations; `*` marks the current one.
    History {
        #[arg(default_value = "main")]
        name: String,
        #[arg(long)]
        json: bool,
    },
    /// Point a template back at an older generation and pause its scheduled refreshes.
    Rollback {
        #[arg(default_value = "main")]
        name: String,
        /// Generation number; the newest one older than the current by default.
        #[arg(long)]
        to: Option<u32>,
    },
    /// Move a template to a newer Postgres major with pg_upgrade.
    Upgrade {
        name: String,
        /// Target Postgres major, like 18.
        #[arg(long)]
        to: u32,
        /// Make a new template with this name instead; the original stays as it is.
        #[arg(long = "as")]
        as_name: Option<String>,
    },
}

/// Template settings shared by `template init` and `template set`.
#[derive(clap::Args)]
struct SettingsFlags {
    /// Age after which clones warn, like 7d.
    #[arg(long)]
    max_age: Option<String>,
    /// Generations to keep on disk (at least 1).
    #[arg(long)]
    keep: Option<u32>,
    /// Rebuild on a schedule, like 24h (at least 1m), or off.
    #[arg(long)]
    every: Option<String>,
    /// How scheduled rebuilds run.
    #[arg(long, value_parser = ["full", "layered"])]
    mode: Option<String>,
    /// Migration command for layered refreshes, run in this folder with DATABASE_URL set, or off.
    #[arg(long)]
    migrate: Option<String>,
    /// Run a layered refresh by itself when the migrations folder changes.
    #[arg(long, value_parser = ["on", "off"])]
    auto_migrate: Option<String>,
    /// When a clone's template is older than --max-age: warn, or also refresh in the background.
    #[arg(long, value_parser = ["warn", "refresh"])]
    on_stale: Option<String>,
}

/// A protocol enum from its snake_case name (clap already limited the choices).
fn enum_arg<T: serde::de::DeserializeOwned>(s: Option<String>) -> Result<Option<T>> {
    Ok(
        s.map(|s| serde_json::from_value(serde_json::Value::String(s)))
            .transpose()?,
    )
}

impl SettingsFlags {
    /// The max age in seconds, and the settings.
    fn parse(self) -> Result<(Option<u64>, TemplateSettings)> {
        let max_age_secs = self
            .max_age
            .as_deref()
            .map(parse_duration)
            .transpose()?
            .map(|d| d.as_secs());
        let (every_secs, every_off) = match self.every.as_deref() {
            Some("off") => (None, true),
            Some(d) => (Some(parse_duration(d)?.as_secs()), false),
            None => (None, false),
        };
        let (migrate, migrate_off) = match self.migrate {
            Some(c) if c == "off" => (None, true),
            // Runs where and with the PATH it would in this shell, like a seed.
            Some(command) => (
                Some(MigrateCmd {
                    command,
                    cwd: std::env::current_dir()?,
                    path: std::env::var("PATH").ok(),
                }),
                false,
            ),
            None => (None, false),
        };
        let settings = TemplateSettings {
            keep: self.keep,
            every_secs,
            every_off,
            every_mode: enum_arg(self.mode)?,
            migrate,
            migrate_off,
            auto_migrate: self.auto_migrate.map(|a| a == "on"),
            on_stale: enum_arg(self.on_stale)?,
        };
        Ok((max_age_secs, settings))
    }
}

#[derive(Subcommand)]
enum ServiceCmd {
    /// Install and start the login service for this binary and home.
    Install,
    /// Stop and remove the login service.
    Uninstall,
    /// Show whether the login service is installed and running.
    Status {
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand)]
enum DaemonCmd {
    /// Show whether the daemon is running.
    Status,
    /// Stop the daemon; clones keep running.
    Stop,
}

pub fn main() -> ExitCode {
    let cli = Cli::parse();
    let rt = match tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
    {
        Ok(rt) => rt,
        Err(e) => return fail(&MitosisError::from(e)),
    };
    match rt.block_on(run(cli)) {
        Ok(code) => code,
        Err(e) => fail(&e),
    }
}

fn fail(e: &MitosisError) -> ExitCode {
    eprintln!("error: {}", e.message);
    if let Some(hint) = &e.hint {
        eprintln!("hint: {hint}");
    }
    // Only `mitosis daemon` returns AlreadyRunning; `client::ensure_daemon` looks for this status.
    if e.code == ErrorCode::AlreadyRunning {
        // Under launchd a non-zero exit means "relaunch me": another daemon already serves, so stop quietly.
        if std::env::var_os("MITOSIS_SERVICE").is_some_and(|v| v == "1") {
            return ExitCode::SUCCESS;
        }
        return ExitCode::from(client::EXIT_ALREADY_RUNNING);
    }
    ExitCode::FAILURE
}

// Deliberately not `{r:?}`: a reply can hold a password-bearing URL. Same in `unexpected` in mcp.rs.
fn unexpected(_: Response) -> MitosisError {
    MitosisError::new(ErrorCode::ProtocolMismatch, "unexpected daemon reply")
        .with_hint("restart the daemon: mitosis daemon stop")
}

fn print_json<T: serde::Serialize>(v: &T) -> Result<()> {
    println!("{}", serde_json::to_string_pretty(v)?);
    Ok(())
}

async fn run(cli: Cli) -> Result<ExitCode> {
    let home = Home::from_env()?;
    match cli.command {
        Cmd::Daemon { command: None } => {
            let config = Config::load(&home)?;
            daemon::run(home, config).await?
        }
        Cmd::Mcp => mcp::serve_stdio(home).await?,
        Cmd::Service { command } => match command {
            ServiceCmd::Install => {
                service::install()?;
                let exe = std::env::current_exe()?;
                println!("service installed: the daemon starts at login");
                println!("binary    {}", exe.display());
                if exe.components().any(|c| c.as_os_str() == "target") {
                    eprintln!(
                        "warning: the service points at a build folder; it breaks if you run cargo clean (use cargo install for a stable path)"
                    );
                }
            }
            ServiceCmd::Uninstall => {
                service::uninstall()?;
                println!("service removed");
            }
            ServiceCmd::Status { json } => {
                let s = service::status()?;
                if json {
                    print_json(&s)?;
                } else {
                    println!("installed {}", s.installed);
                    println!("loaded    {}", s.loaded);
                    println!("running   {}", s.running);
                    if let Some(b) = &s.binary {
                        let gone = if s.binary_exists { "" } else { "  (missing)" };
                        println!("binary    {}{gone}", b.display());
                    }
                }
            }
        },
        Cmd::Config {
            command: None,
            json,
        } => {
            let entries = Config::describe(&home)?;
            if json {
                print_json(&entries)?;
            } else {
                print_config(&entries);
            }
        }
        Cmd::Config {
            command: Some(ConfigCmd::Set { key, value }),
            ..
        } => {
            Config::set_in_file(&home, &key, &value)?;
            // No daemon start: a stopped daemon reads the file when it next starts.
            client::request_if_running(&home, Request::ConfigReload).await?;
            println!("{key} = {}", value.trim());
        }
        Cmd::Template { command } => template(&home, command).await?,
        Cmd::Clone {
            template,
            name,
            ttl,
            durable,
            fresh,
            protect,
            env_file,
            env_var,
            wait,
            json,
        } => {
            validate_name("template", &template)?;
            if let Some(n) = &name {
                validate_name("clone", n)?;
            }
            let ttl_secs = parse_duration(&ttl)?.as_secs();
            let wait_secs = match wait.as_deref() {
                None => None,
                Some("0" | "0s") => Some(0),
                Some(w) => Some(parse_duration(w)?.as_secs()),
            };
            let args = CloneCreateArgs {
                template: template.clone(),
                name,
                ttl_secs,
                durable,
                fresh,
                protect,
                // The CLI exits right after printing the URL, so watching it would destroy the
                // clone at once: CLI clones live until their TTL or `mitosis destroy`.
                parent_pid: None,
                env: None,
                wait_secs,
            };
            let info = envfile::create_clone(&home, args, env_file, env_var).await?;
            for w in &info.warnings {
                eprintln!("warning: {w}");
            }
            if info.existing {
                eprintln!("note: clone {} was already running", info.id);
            }
            // Warnings are best effort: the clone already exists.
            if let Ok(Response::Templates { templates }) =
                client::request(&home, Request::TemplateList).await
            {
                for w in templates
                    .iter()
                    .filter(|t| t.name == template)
                    .flat_map(|t| &t.warnings)
                {
                    eprintln!("warning: {w}");
                }
            }
            if json {
                print_json(&info)?;
            } else {
                println!("{}", info.url);
            }
        }
        Cmd::Env { id_or_name, var } => {
            let clones = match client::request(&home, Request::CloneList).await? {
                Response::Clones { clones } => clones,
                other => return Err(unexpected(other)),
            };
            let c = clones
                .iter()
                .find(|c| c.id == id_or_name || c.name.as_deref() == Some(id_or_name.as_str()))
                .ok_or_else(|| {
                    MitosisError::new(
                        ErrorCode::CloneNotFound,
                        format!("clone {id_or_name} not found"),
                    )
                    .with_hint("see running clones with `mitosis list`")
                })?;
            println!("{var}={}", c.url);
        }
        Cmd::List { json } => {
            let clones = match client::request(&home, Request::CloneList).await? {
                Response::Clones { clones } => clones,
                other => return Err(unexpected(other)),
            };
            for w in envfile::finish_pending(&home).await {
                eprintln!("warning: {w}");
            }
            if json {
                print_json(&clones)?;
            } else {
                print_clones(&clones);
            }
        }
        Cmd::Top => top(&home).await?,
        Cmd::Destroy {
            id_or_name,
            force,
            forget,
        } => {
            let req = Request::CloneDestroy {
                id_or_name,
                force,
                forget,
            };
            match client::request(&home, req).await? {
                Response::Destroyed { id } => println!("{id}"),
                other => return Err(unexpected(other)),
            }
            for w in envfile::finish_pending(&home).await {
                eprintln!("warning: {w}");
            }
        }
        Cmd::Promote { clone, template } => {
            let req = Request::ClonePromote {
                id_or_name: clone.clone(),
                template,
            };
            match client::request(&home, req).await? {
                Response::TemplateBuilt(t) => println!(
                    "promoted {clone} to template {} generation {} (Postgres {}, {})",
                    t.name,
                    t.current_gen,
                    t.pg_major,
                    human_bytes(t.size_bytes)
                ),
                other => return Err(unexpected(other)),
            }
        }
        Cmd::Doctor { fix, json } => {
            let checks = doctor::run(&home, fix).await;
            if json {
                print_json(&checks)?;
            } else {
                print!("{}", doctor::render(&checks));
            }
            return Ok(ExitCode::from(doctor::exit_code(&checks)));
        }
        Cmd::Gc => match client::request(&home, Request::Gc).await? {
            Response::Gc(r) => {
                println!(
                    "adopted {}, destroyed {}, orphan folders removed {}, records dropped {}, failed {}",
                    r.adopted.len(),
                    r.destroyed.len(),
                    r.orphan_folders_removed.len(),
                    r.records_dropped.len(),
                    r.failed.len()
                );
                for f in &r.failed {
                    println!("failed: {}: {}", f.item, f.error);
                }
            }
            other => return Err(unexpected(other)),
        },
        Cmd::Daemon {
            command: Some(DaemonCmd::Status),
        } => match client::request_if_running(&home, Request::Status).await? {
            None => {
                println!("daemon is not running");
                return Ok(ExitCode::FAILURE);
            }
            Some(Response::Status(s)) => {
                println!("daemon is running");
                println!("pid       {}", s.pid);
                println!("version   {}", s.version);
                println!("service   {}", s.service);
                println!("home      {}", s.home.display());
                println!("clones    {}", s.clones);
                println!("templates {}", s.templates);
                println!(
                    "uptime    {}",
                    format_duration(Duration::from_secs(s.uptime_secs))
                );
            }
            Some(other) => return Err(unexpected(other)),
        },
        Cmd::Daemon {
            command: Some(DaemonCmd::Stop),
        } => {
            match client::request_if_running(&home, Request::Shutdown).await? {
                None => println!("daemon is not running"),
                Some(Response::Ok) => {
                    // The daemon removes its socket right after replying; wait so callers see it gone.
                    let deadline = Instant::now() + Duration::from_secs(5);
                    while home.daemon_sock().exists() && Instant::now() < deadline {
                        tokio::time::sleep(Duration::from_millis(50)).await;
                    }
                    println!("daemon stopped");
                }
                Some(other) => return Err(unexpected(other)),
            }
        }
    }
    Ok(ExitCode::SUCCESS)
}

fn print_config(entries: &[ConfigEntry]) {
    let width = entries.iter().map(|e| e.key.len()).max().unwrap_or(0);
    let vwidth = entries.iter().map(|e| e.value.len()).max().unwrap_or(0);
    for e in entries {
        println!(
            "{:<width$} = {:<vwidth$}  ({})",
            e.key,
            e.value,
            e.source.label()
        );
    }
}

async fn template(home: &Home, cmd: TemplateCmd) -> Result<()> {
    match cmd {
        TemplateCmd::Init {
            name,
            from_url,
            seed,
            database,
            migrations,
            pg_version,
            settings,
        } => {
            validate_name("template", &name)?;
            let (max_age_secs, settings) = settings.parse()?;
            let migrations = migrations
                .map(|dir| {
                    std::fs::canonicalize(&dir).map_err(|e| {
                        MitosisError::new(
                            ErrorCode::InvalidRequest,
                            format!("migrations folder {}: {e}", dir.display()),
                        )
                    })
                })
                .transpose()?;
            let source = match (from_url, seed) {
                (Some(url), _) => TemplateSource::Url { url },
                // The seed runs where and with the PATH it would in this shell.
                (None, Some(command)) => TemplateSource::Seed {
                    command,
                    cwd: Some(std::env::current_dir()?),
                    path: std::env::var("PATH").ok(),
                },
                (None, None) => unreachable!("clap requires --from-url or --seed"),
            };
            let args = TemplateInitArgs {
                name,
                source,
                database,
                migrations,
                max_age_secs,
                pg_major: pg_version,
                settings,
            };
            match client::request(home, Request::TemplateInit(args)).await? {
                Response::TemplateBuilt(t) => print_built(&t),
                other => return Err(unexpected(other)),
            }
        }
        TemplateCmd::Refresh { name, layered } => {
            validate_name("template", &name)?;
            let path = std::env::var("PATH").ok();
            let req = Request::TemplateRefresh {
                name,
                path,
                layered,
            };
            match client::request(home, req).await? {
                Response::TemplateBuilt(t) => print_built(&t),
                other => return Err(unexpected(other)),
            }
        }
        TemplateCmd::Set {
            name,
            settings,
            resume,
        } => {
            validate_name("template", &name)?;
            let (max_age_secs, settings) = settings.parse()?;
            let args = TemplateSetArgs {
                name,
                max_age_secs,
                settings,
                resume,
            };
            match client::request(home, Request::TemplateSet(args)).await? {
                Response::TemplateBuilt(t) => {
                    println!("template {} settings saved", t.name);
                    if t.paused {
                        println!("{}", paused_line(&t.name));
                    }
                }
                other => return Err(unexpected(other)),
            }
        }
        TemplateCmd::List { json } => {
            let templates = match client::request(home, Request::TemplateList).await? {
                Response::Templates { templates } => templates,
                other => return Err(unexpected(other)),
            };
            for t in &templates {
                for w in &t.warnings {
                    eprintln!("warning: {}: {w}", t.name);
                }
                if let Some(e) = &t.last_error {
                    eprintln!("last error: {}: {e}", t.name);
                }
            }
            if json {
                print_json(&templates)?;
            } else {
                print_table(
                    &[
                        "NAME", "GEN", "PAUSED", "PG", "DATABASE", "SIZE", "AGE", "SOURCE",
                    ],
                    templates
                        .iter()
                        .map(|t| {
                            vec![
                                t.name.clone(),
                                format!("{}/{}", t.current_gen, t.generations),
                                if t.paused { "paused" } else { "-" }.to_string(),
                                t.pg_major.to_string(),
                                t.database.clone(),
                                human_bytes(t.size_bytes),
                                format_duration(Duration::from_secs(t.age_secs)),
                                source_cell(&t.source),
                            ]
                        })
                        .collect(),
                );
            }
        }
        TemplateCmd::History { name, json } => {
            validate_name("template", &name)?;
            let (template, generations, paused) =
                match client::request(home, Request::TemplateHistory { name }).await? {
                    Response::Generations {
                        template,
                        generations,
                        paused,
                    } => (template, generations, paused),
                    other => return Err(unexpected(other)),
                };
            if json {
                print_json(&serde_json::json!({
                    "template": template,
                    "paused": paused,
                    "generations": generations,
                }))?;
            } else {
                if paused {
                    println!("{}", paused_line(&template));
                }
                let now = now();
                print_table(
                    &["GEN", "KIND", "BUILT", "PG", "SIZE", "CURRENT"],
                    generations
                        .iter()
                        .map(|g| {
                            let ago = u64::try_from(now - g.built_at).unwrap_or(0);
                            vec![
                                g.gen.to_string(),
                                serde_json::to_value(g.kind)
                                    .ok()
                                    .and_then(|v| v.as_str().map(String::from))
                                    .unwrap_or_default(),
                                format!("{} ago", format_duration(Duration::from_secs(ago))),
                                g.pg_major.to_string(),
                                human_bytes(g.size_bytes),
                                if g.current { "*" } else { "" }.to_string(),
                            ]
                        })
                        .collect(),
                );
            }
        }
        TemplateCmd::Rollback { name, to } => {
            validate_name("template", &name)?;
            match client::request(home, Request::TemplateRollback { name, to }).await? {
                Response::TemplateBuilt(t) => println!(
                    "template {} now uses generation {} (scheduled refreshes paused)",
                    t.name, t.current_gen
                ),
                other => return Err(unexpected(other)),
            }
        }
        TemplateCmd::Upgrade { name, to, as_name } => {
            validate_name("template", &name)?;
            if let Some(n) = &as_name {
                validate_name("template", n)?;
            }
            let req = Request::TemplateUpgrade {
                name: name.clone(),
                to,
                as_name,
            };
            match client::request(home, req).await? {
                Response::TemplateBuilt(t) => println!(
                    "upgraded {name} to Postgres {}: template {} generation {} ({})",
                    t.pg_major,
                    t.name,
                    t.current_gen,
                    human_bytes(t.size_bytes)
                ),
                other => return Err(unexpected(other)),
            }
        }
    }
    Ok(())
}

/// The template's source for the table: the URL (the daemon already masked its password) or
/// the seed command, cut to one short line.
fn source_cell(source: &TemplateSource) -> String {
    const MAX: usize = 48;
    let text = match source {
        TemplateSource::Url { url } => url.clone(),
        TemplateSource::Seed { command, .. } => {
            format!(
                "seed: {}",
                command.split_whitespace().collect::<Vec<_>>().join(" ")
            )
        }
        TemplateSource::Promoted { clone_id } => format!("promoted from {clone_id}"),
    };
    if text.chars().count() <= MAX {
        return text;
    }
    let cut: String = text.chars().take(MAX - 1).collect();
    format!("{cut}…")
}

fn paused_line(name: &str) -> String {
    format!(
        "paused: automatic builds stopped — run \"mitosis template refresh {name}\" or \"mitosis template set {name} --resume\""
    )
}

fn print_built(t: &TemplateInfo) {
    println!(
        "template {} built (Postgres {}, {})",
        t.name,
        t.pg_major,
        human_bytes(t.size_bytes)
    );
}

fn print_clones(clones: &[CloneInfo]) {
    let now = now();
    let secs = |s: i64| format_duration(Duration::from_secs(u64::try_from(s).unwrap_or(0)));
    let opt_bytes = |b: Option<u64>| b.map_or("-".to_string(), human_bytes);
    print_table(
        &[
            "ID",
            "NAME",
            "TEMPLATE",
            "PORT",
            "AGE",
            "TTL LEFT",
            "RAM",
            "EXTRA DISK",
            "FLAGS",
        ],
        clones
            .iter()
            .map(|c| {
                vec![
                    c.id.clone(),
                    c.name.clone().unwrap_or_else(|| "-".into()),
                    c.template.clone(),
                    c.port.to_string(),
                    secs(now - c.created_at),
                    if c.protected {
                        "never".into()
                    } else {
                        secs(c.expires_at - now)
                    },
                    opt_bytes(c.rss_bytes),
                    opt_bytes(c.own_disk_bytes),
                    flags(c),
                ]
            })
            .collect(),
    );
}

/// `!` for a clone past its disk warning, then `protected`.
fn flags(c: &CloneInfo) -> String {
    let mut f = Vec::new();
    if c.disk_warn {
        f.push("!");
    }
    if c.protected {
        f.push("protected");
    }
    f.join(" ")
}

/// Puts the terminal in no-echo, no-line-buffer mode on the alternate screen, and puts it back on
/// drop, so every way out of `top` (q, Ctrl-C, an error, a panic) leaves a usable terminal.
struct RawTerminal {
    saved: nix::sys::termios::Termios,
}

impl RawTerminal {
    fn enter() -> Result<RawTerminal> {
        use nix::sys::termios::{
            tcgetattr, tcsetattr, LocalFlags, SetArg, SpecialCharacterIndices as C,
        };
        let stdin = std::io::stdin();
        let saved = tcgetattr(&stdin).map_err(|_| {
            MitosisError::new(ErrorCode::InvalidRequest, "mitosis top needs a terminal")
                .with_hint("run it in a terminal, or use `mitosis list --json`")
        })?;
        let mut raw = saved.clone();
        // ISIG off: Ctrl-C arrives as a byte, so this process can clean up before it exits.
        raw.local_flags
            .remove(LocalFlags::ICANON | LocalFlags::ECHO | LocalFlags::ISIG);
        // A read returns after 2 s (in tenths of a second) or at the first key.
        raw.control_chars[C::VMIN as usize] = 0;
        raw.control_chars[C::VTIME as usize] = 20;
        tcsetattr(&stdin, SetArg::TCSANOW, &raw)
            .map_err(|e| MitosisError::new(ErrorCode::Internal, format!("terminal: {e}")))?;
        let term = RawTerminal { saved };
        print!("\x1b[?1049h\x1b[?25l");
        let _ = std::io::Write::flush(&mut std::io::stdout());
        Ok(term)
    }
}

impl Drop for RawTerminal {
    fn drop(&mut self) {
        let _ = nix::sys::termios::tcsetattr(
            std::io::stdin(),
            nix::sys::termios::SetArg::TCSANOW,
            &self.saved,
        );
        print!("\x1b[?25h\x1b[?1049l");
        let _ = std::io::Write::flush(&mut std::io::stdout());
    }
}

/// Waits up to 2 s for a key; true when it asks to quit (`q` or Ctrl-C).
fn quit_key() -> bool {
    use std::io::Read;
    let mut b = [0u8; 1];
    matches!(std::io::stdin().read(&mut b), Ok(1) if matches!(b[0], b'q' | b'Q' | 3))
}

fn draw_top(u: &budget::Usage) {
    let now = now();
    let secs = |s: i64| format_duration(Duration::from_secs(u64::try_from(s).unwrap_or(0)));
    let opt_bytes = |b: Option<u64>| b.map_or("-".to_string(), human_bytes);
    let of = |used: String, cap: Option<u64>| match cap {
        Some(c) => format!("{used} / {}", human_bytes(c)),
        None => format!("{used} / no limit"),
    };
    print!("\x1b[H\x1b[2J");
    println!("mitosis top    q to quit, refreshes every 2s\n");
    print_table(
        &[
            "ID",
            "NAME",
            "TEMPLATE",
            "TTL LEFT",
            "RAM",
            "EXTRA DISK",
            "FLAGS",
        ],
        u.clones
            .iter()
            .map(|c| {
                vec![
                    c.id.clone(),
                    c.name.clone().unwrap_or_else(|| "-".into()),
                    c.template.clone(),
                    if c.protected {
                        "never".into()
                    } else {
                        secs(c.expires_at - now)
                    },
                    opt_bytes(c.rss_bytes),
                    opt_bytes(c.own_disk_bytes),
                    [(c.disk_warn, "!"), (c.protected, "protected")]
                        .iter()
                        .filter(|(on, _)| *on)
                        .map(|(_, t)| *t)
                        .collect::<Vec<_>>()
                        .join(" "),
                ]
            })
            .collect(),
    );
    println!(
        "\nclones  {} / {}\nram     {}\ndisk    {}\nfree    {}\nqueued  {}",
        u.clones.len(),
        u.max_clones,
        of(human_bytes(u.ram_bytes), u.ram_budget),
        of(human_bytes(u.disk_bytes), u.disk_budget),
        human_bytes(u.free_disk_bytes),
        u.queued
    );
    let _ = std::io::Write::flush(&mut std::io::stdout());
}

async fn top(home: &Home) -> Result<()> {
    let _terminal = RawTerminal::enter()?;
    loop {
        match client::request(home, Request::Usage).await? {
            Response::Usage(u) => draw_top(&u),
            other => return Err(unexpected(other)),
        }
        let quit = tokio::task::spawn_blocking(quit_key)
            .await
            .map_err(|e| MitosisError::new(ErrorCode::Internal, format!("terminal: {e}")))?;
        if quit {
            return Ok(());
        }
    }
}

/// Left-aligned columns separated by two spaces.
fn print_table(headers: &[&str], rows: Vec<Vec<String>>) {
    let mut widths: Vec<usize> = headers.iter().map(|h| h.len()).collect();
    for row in &rows {
        for (w, cell) in widths.iter_mut().zip(row) {
            *w = (*w).max(cell.chars().count());
        }
    }
    let line = |cells: Vec<&str>| {
        let parts: Vec<String> = cells
            .iter()
            .zip(&widths)
            .map(|(c, w)| format!("{c:<w$}"))
            .collect();
        println!("{}", parts.join("  ").trim_end());
    };
    line(headers.to_vec());
    for row in &rows {
        line(row.iter().map(String::as_str).collect());
    }
}

/// Decimal units: 512 B, 3.4 kB, 34 MB, 1.2 GB.
fn human_bytes(b: u64) -> String {
    if b < 1000 {
        return format!("{b} B");
    }
    let mut v = b as f64;
    let mut unit = "B";
    for u in ["kB", "MB", "GB", "TB", "PB"] {
        if v < 1000.0 {
            break;
        }
        v /= 1000.0;
        unit = u;
    }
    if v < 10.0 {
        format!("{v:.1} {unit}")
    } else {
        format!("{v:.0} {unit}")
    }
}

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

    #[test]
    fn clap_definition_is_valid() {
        Cli::command().debug_assert();
    }

    #[test]
    fn sizes() {
        assert_eq!(human_bytes(0), "0 B");
        assert_eq!(human_bytes(999), "999 B");
        assert_eq!(human_bytes(3_400), "3.4 kB");
        assert_eq!(human_bytes(34_000_000), "34 MB");
        assert_eq!(human_bytes(1_200_000_000), "1.2 GB");
    }

    #[test]
    fn source_cells_are_short() {
        let url = TemplateSource::Url {
            url: "postgres://u:***@h/db".into(),
        };
        assert_eq!(source_cell(&url), "postgres://u:***@h/db");
        let seed = TemplateSource::Seed {
            command: format!("psql \"$DATABASE_URL\"\n  -f {}", "x".repeat(80)),
            cwd: None,
            path: None,
        };
        let cell = source_cell(&seed);
        assert!(
            cell.starts_with("seed: psql \"$DATABASE_URL\" -f xx"),
            "{cell}"
        );
        assert_eq!(cell.chars().count(), 48);
        assert!(cell.ends_with('…') && !cell.contains('\n'));
    }

    #[test]
    fn init_needs_exactly_one_source() {
        assert!(Cli::try_parse_from(["mitosis", "template", "init"]).is_err());
        assert!(Cli::try_parse_from([
            "mitosis",
            "template",
            "init",
            "--seed",
            "x",
            "--from-url",
            "y"
        ])
        .is_err());
        assert!(Cli::try_parse_from(["mitosis", "template", "init", "--seed", "x"]).is_ok());
    }

    #[test]
    fn settings_flags_parse() {
        let cli = Cli::try_parse_from([
            "mitosis",
            "template",
            "set",
            "main",
            "--keep",
            "2",
            "--every",
            "off",
            "--mode",
            "layered",
            "--migrate",
            "make migrate",
            "--auto-migrate",
            "on",
            "--on-stale",
            "refresh",
            "--max-age",
            "1d",
            "--resume",
        ])
        .unwrap();
        let Cmd::Template {
            command: TemplateCmd::Set {
                settings, resume, ..
            },
        } = cli.command
        else {
            panic!("wrong command")
        };
        assert!(resume);
        let (max_age, s) = settings.parse().unwrap();
        assert_eq!(max_age, Some(86_400));
        assert_eq!(s.keep, Some(2));
        assert!(s.every_off && s.every_secs.is_none());
        assert_eq!(s.every_mode, Some(crate::protocol::RefreshMode::Layered));
        assert_eq!(s.migrate.unwrap().command, "make migrate");
        assert_eq!(s.auto_migrate, Some(true));
        assert_eq!(s.on_stale, Some(crate::protocol::OnStale::Refresh));
        assert!(Cli::try_parse_from(["mitosis", "template", "set", "--mode", "fast"]).is_err());
    }
}