git-loom 0.25.0

A Git CLI tool that weaves together multiple feature branches into integration branches
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
mod absorb;
mod add;
mod agent;
mod branch;
mod commit;
mod completions;
mod core;
mod diff;
mod drop;
mod fold;
mod git;
mod init;
mod push;
mod reword;
mod show;
mod split;
mod status;
mod swap;
mod switch;
mod trace;
mod tui;
mod update;

use crate::agent::AgentKind;
use crate::core::hunk_select::HunkArgs;
use crate::core::{agent_mode, graph, msg, repo, transaction};

use std::ffi::OsString;
use std::io::IsTerminal;
use std::sync::OnceLock;

use anyhow::Context;
use clap::builder::styling::{AnsiColor, Styles};
use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
use colored::control;

#[derive(ValueEnum, Clone, Copy)]
enum ThemeArg {
    /// Detect from terminal background color (default to dark if undetectable)
    Auto,
    /// Dark terminal background
    Dark,
    /// Light terminal background
    Light,
}

/// Terminal background the colors are tuned for.
#[derive(Clone, Copy, PartialEq)]
enum ThemeMode {
    Dark,
    Light,
}

// Help templates. `{h}`, `{l}` and `{p}` are the header, literal and
// placeholder styles and `{r}` resets; `apply_styles` substitutes them so the
// help output follows the terminal background and `--no-color`.
const ABOUT: &str = "\
{p}Weave your branches together{r}
Checkout the full docs here: https://narnaud.github.io/git-loom/";

const HELP_TEMPLATE: &str =
    "{about-with-newline}\n{usage-heading} {usage}{after-help}\n\n{h}Options:{r}\n{options}\n";

// Grouped command help, replacing clap's flat command list.
const GROUPED_COMMANDS: &str = "\
{h}Workflow:{r}
  {l}init{r}              Initialize a new integration branch
  {l}update{r}, {l}up{r}        Pull-rebase and update submodules
  {l}push{r}, {l}pr{r}          Push a branch to remote
  {l}agent{r}             Install the loom skill for AI agents

{h}Staging:{r}
  {l}add{r}               Stage files using short IDs or paths [{l}-p{r} for interactive hunks]

{h}Commits:{r}
  {l}commit{r}, {l}ci{r}        Create a commit on a feature branch [{l}-p{r} for interactive hunks]
  {l}fold{r}              Amend, fixup, or move commits [{l}-p{r} for interactive hunks] [{l}amend{r}, {l}am{r}, {l}fixup{r}, {l}mv{r}, {l}rub{r}]
  {l}absorb{r}            Auto-distribute changes into originating commits
  {l}split{r}             Split a commit into two [{l}-p{r} for interactive hunks]
  {l}swap{r}              Swap two commits
  {l}reword{r}, {l}rw{r}        Reword a commit message or rename a branch
  {l}drop{r}, {l}rm{r}          Drop a change, commit, or branch

{h}Branches:{r}
  {l}branch{r}, {l}br{r}        Manage feature branches (create, merge, unmerge)
  {l}switch{r}, {l}sw{r}        Switch to any branch for testing (without weaving)

{h}Inspection:{r}
  {l}status{r}            Show the branch-aware status ({p}default{r} command)
  {l}tui{r}               Interactive status TUI (tree + diff, with actions)
  {l}show{r}, {l}sh{r}          Show commit details (like git show)
  {l}diff{r}, {l}di{r}          Show a diff using short IDs (like git diff)
  {l}trace{r}             Show the latest command trace

{h}Recovery:{r}
  {l}continue{r}, {l}c{r}       Resume a paused operation after resolving conflicts
  {l}abort{r}, {l}a{r}          Cancel a paused operation and restore original state";

/// Style palette for the help output. Yellow is unreadable on a light
/// background, so headers move to blue and placeholders to magenta there.
/// Returns a plain palette (no escapes at all) when colors are disabled.
fn help_styles(mode: ThemeMode, color: bool) -> Styles {
    if !color {
        return Styles::plain();
    }
    let (header, literal, placeholder) = match mode {
        ThemeMode::Dark => (AnsiColor::Yellow, AnsiColor::Green, AnsiColor::Blue),
        ThemeMode::Light => (AnsiColor::Blue, AnsiColor::Green, AnsiColor::Magenta),
    };
    Styles::styled()
        .header(header.on_default().bold())
        .usage(header.on_default().bold())
        .literal(literal.on_default())
        .placeholder(placeholder.on_default())
}

/// Substitute the style markers of a help template.
fn apply_styles(template: &str, styles: &Styles) -> String {
    let header = styles.get_header();
    template
        .replace("{h}", &header.to_string())
        .replace("{l}", &styles.get_literal().to_string())
        .replace("{p}", &styles.get_placeholder().to_string())
        .replace("{r}", &format!("{header:#}"))
}

#[derive(Parser)]
#[command(name = "git-loom", version)]
struct Cli {
    /// Disable colored output
    #[arg(long)]
    no_color: bool,

    /// Machine-readable JSON status output for AI agents (see also LOOM_AGENT)
    #[arg(long, global = true)]
    agent: bool,

    /// Color theme for graph output
    #[arg(long, default_value = "auto")]
    theme: ThemeArg,

    /// Show files changed in each commit (optionally filtered to specific commits)
    #[arg(short = 'f', long = "files", num_args = 0.., hide = true)]
    files: Option<Vec<String>>,

    /// Number of commits to show at and before the base (default: loom.statusContext, else 1)
    #[arg(hide = true)]
    context: Option<usize>,

    /// Show all branches including hidden ones (those matching loom.hideBranchPattern)
    #[arg(short = 'a', long = "all", hide = true)]
    all: bool,

    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Subcommand)]
enum Command {
    // -- Workflow --
    /// Initialize a new integration branch tracking a remote
    Init {
        /// Branch name (defaults to "integration")
        name: Option<String>,
    },
    /// Pull-rebase the integration branch and update submodules
    #[command(visible_alias = "up")]
    Update {
        /// Remove local branches whose upstream tracking branch was deleted on remote
        #[arg(short, long)]
        yes: bool,
    },
    /// Push a feature branch to remote and optionally create a PR or Gerrit review
    #[command(visible_alias = "pr")]
    Push {
        /// Branch name or short ID (if not provided, will prompt interactively)
        branch: Option<String>,
        /// Push branch without creating a PR or Gerrit review
        #[arg(long)]
        no_pr: bool,
        /// Push with --force instead of --force-with-lease --force-if-includes
        #[arg(short = 'f', long)]
        force: bool,
    },
    /// Set up AI agent integration (unrelated to `init`)
    Agent(AgentCmd),

    // -- Staging --
    /// Stage files using short IDs, paths, or 'zz' for all
    Add {
        /// Files to stage (short IDs, filenames, or 'zz' for all)
        #[arg(num_args = 0..)]
        files: Vec<String>,
        /// Select hunks to stage: a picker, or `--hunks` from its listing
        #[arg(short = 'p', long = "patch")]
        patch: bool,
        /// Hunk ids from a `-p` listing, instead of picking them interactively
        // Comma-splitting happens in `hunk_select`; see `fold`.
        #[arg(long = "hunks", requires = "patch", requires = "hunks_from")]
        hunks: Vec<String>,
        /// Fingerprint of the listing `--hunks` was taken from
        #[arg(long = "hunks-from", requires = "hunks")]
        hunks_from: Option<String>,
        /// Arguments forwarded verbatim to `git add` (everything after `--`)
        #[arg(last = true, num_args = 0.., allow_hyphen_values = true, value_name = "GIT_ARG")]
        git_args: Vec<String>,
    },

    // -- Commits --
    /// Create a commit on a feature branch without leaving integration
    #[command(visible_alias = "ci")]
    Commit {
        /// Target feature branch (name or short ID)
        #[arg(short = 'b', long = "branch")]
        branch: Option<String>,
        /// Commit to the integration branch (loose commit), skipping the branch prompt
        #[arg(short = 'i', long = "integration", conflicts_with = "branch")]
        integration: bool,
        /// Commit message (if not provided, opens editor)
        #[arg(short, long)]
        message: Option<String>,
        /// Select hunks to stage before committing: a picker, or `--hunks`
        #[arg(short = 'p', long = "patch")]
        patch: bool,
        /// Hunk ids from a `-p` listing, instead of picking them interactively
        // Comma-splitting happens in `hunk_select`; see `fold`.
        #[arg(long = "hunks", requires = "patch", requires = "hunks_from")]
        hunks: Vec<String>,
        /// Fingerprint of the listing `--hunks` was taken from
        #[arg(long = "hunks-from", requires = "hunks")]
        hunks_from: Option<String>,
        /// Files to stage (short IDs, filenames, or 'zz' for all), none for all tracked changes
        files: Vec<String>,
        /// Arguments forwarded verbatim to `git commit` (everything after `--`)
        #[arg(last = true, num_args = 0.., allow_hyphen_values = true, value_name = "GIT_ARG")]
        git_args: Vec<String>,
    },
    /// Fold source(s) into a target (amend files, fixup commits, move commits, move files between commits)
    #[command(visible_aliases = ["amend", "am", "fixup", "mv", "rub"])]
    Fold {
        /// Create a new branch from the source commit(s) and move them there
        #[arg(short = 'c', long = "create")]
        create: bool,
        /// Select hunks to fold: a picker, or `--hunks` from its listing
        #[arg(short = 'p', long = "patch", conflicts_with = "create")]
        patch: bool,
        /// Move the source commit(s) directly above this commit
        #[arg(long, value_name = "COMMIT", conflicts_with_all = ["below", "create", "patch"])]
        above: Option<String>,
        /// Move the source commit(s) directly below this commit
        #[arg(long, value_name = "COMMIT", conflicts_with_all = ["create", "patch"])]
        below: Option<String>,
        /// Hunk ids from a `-p` listing, instead of picking them interactively
        // No `value_delimiter`: a path may contain a comma, so the commas are
        // split off in `hunk_select`, where the real ids are known.
        #[arg(long = "hunks", requires = "patch", requires = "hunks_from")]
        hunks: Vec<String>,
        /// Fingerprint of the listing `--hunks` was taken from
        #[arg(long = "hunks-from", requires = "hunks")]
        hunks_from: Option<String>,
        /// Source(s) and target: files, commits, or branches (last arg is the target, unless --above/--below names it)
        #[arg(required = true, num_args = 1..)]
        args: Vec<String>,
        /// Arguments forwarded verbatim to the `git commit` fold runs (everything after `--`)
        #[arg(last = true, num_args = 0.., allow_hyphen_values = true, value_name = "GIT_ARG")]
        git_args: Vec<String>,
    },
    /// Absorb working tree changes into the commits that introduced them
    Absorb {
        /// Show what would be absorbed without making changes
        #[arg(short = 'n', long)]
        dry_run: bool,
        /// Files to restrict absorption to (default: all tracked changed files)
        files: Vec<String>,
    },
    /// Split a commit into two sequential commits
    Split {
        /// Commit hash, short ID, or HEAD
        target: String,
        /// Message for the first commit (prompts if omitted)
        #[arg(short, long)]
        message: Option<String>,
        /// Pick hunks for the first commit: a picker, or `--hunks`
        #[arg(short = 'p', long = "patch")]
        patch: bool,
        /// Hunk ids from a `-p` listing, instead of picking them interactively
        // Comma-splitting happens in `hunk_select`; see `fold`.
        #[arg(long = "hunks", requires = "patch", requires = "hunks_from")]
        hunks: Vec<String>,
        /// Fingerprint of the listing `--hunks` was taken from
        #[arg(long = "hunks-from", requires = "hunks")]
        hunks_from: Option<String>,
        /// Files for the first commit (shows interactive picker if omitted)
        files: Vec<String>,
    },
    /// Reword a commit message or rename a branch
    #[command(visible_alias = "rw")]
    Reword {
        /// Branch name, shortID, or commit hash
        target: String,
        /// New message or branch name (if not provided, opens editor for commits)
        #[arg(short, long)]
        message: Option<String>,
    },
    /// Swap two commits within the same sequence
    Swap {
        /// First commit hash or short ID
        a: String,
        /// Second commit hash or short ID
        b: String,
    },
    /// Drop a local change, a commit, or a branch from history
    #[command(visible_alias = "rm")]
    Drop {
        /// Commit hash, branch name, file, short ID, or `zz`; several files at once
        #[arg(required = true)]
        targets: Vec<String>,
        /// Skip confirmation prompt
        #[arg(short, long)]
        yes: bool,
    },

    // -- Branches --
    /// Manage feature branches (create, merge, unmerge)
    #[command(visible_alias = "br")]
    Branch(BranchCmd),

    /// Switch to any branch for testing without weaving it into the integration branch
    #[command(visible_alias = "sw")]
    Switch {
        /// Branch name or short ID (if not provided, shows interactive picker)
        branch: Option<String>,
    },

    // -- Inspection --
    /// Interactive status TUI: browse the tree, view diffs, and run actions
    Tui,
    /// Show the branch-aware status
    Status {
        /// Show files changed in each commit (optionally filtered to specific commits)
        #[arg(short = 'f', long = "files", num_args = 0.., value_name = "COMMIT")]
        files: Option<Vec<String>>,
        /// Number of commits to show at and before the base (default: loom.statusContext, else 1)
        context: Option<usize>,
        /// Show all branches including hidden ones (those matching loom.hideBranchPattern)
        #[arg(short = 'a', long = "all")]
        all: bool,
    },
    /// Show the diff and metadata for a commit (like `git show`)
    #[command(visible_alias = "sh")]
    Show {
        /// Commit hash, branch name, or short ID (defaults to the last commit on the current branch)
        target: Option<String>,
        /// Arguments forwarded verbatim to `git show` (everything after `--`)
        #[arg(last = true, num_args = 0.., allow_hyphen_values = true, value_name = "GIT_ARG")]
        git_args: Vec<String>,
    },
    /// Show a diff using short IDs (like `git diff`)
    #[command(visible_alias = "di")]
    Diff {
        /// Files, commits, or commit ranges (short IDs supported, e.g. `ma`, `d0`, `d0..3a`)
        #[arg(num_args = 0..)]
        args: Vec<String>,
        /// Show staged changes (index vs HEAD)
        #[arg(long = "staged", visible_alias = "cached", conflicts_with = "all")]
        staged: bool,
        /// Show all changes, both staged and unstaged (working tree vs HEAD)
        #[arg(short = 'a', long = "all")]
        all: bool,
        /// Arguments forwarded verbatim to `git diff` (everything after `--`)
        #[arg(last = true, num_args = 0.., allow_hyphen_values = true, value_name = "GIT_ARG")]
        git_args: Vec<String>,
    },
    /// Show the latest command trace
    Trace,

    // -- Recovery --
    /// Resume a paused loom operation after resolving conflicts
    #[command(visible_alias = "c")]
    Continue,
    /// Cancel a paused loom operation and restore original state
    #[command(visible_alias = "a")]
    Abort,

    // -- Hidden --
    /// Generate shell completions (powershell, clink)
    #[command(hide = true)]
    Completions {
        /// Shell to generate completions for (powershell, clink)
        shell: String,
    },
    /// Internal: used as GIT_SEQUENCE_EDITOR to write a pre-generated todo file
    #[command(hide = true)]
    InternalWriteTodo {
        /// Path to the source file containing the todo content
        #[arg(long = "source")]
        source: String,
        /// Path to the git rebase todo file (provided by git)
        todo_file: String,
    },
}

#[derive(Args)]
struct AgentCmd {
    #[command(subcommand)]
    action: AgentAction,
}

#[derive(Subcommand)]
enum AgentAction {
    /// Install the loom skill for an AI agent
    Init {
        /// AI agent to install the skill for
        // Named `kind`, not `agent`: the global `--agent` flag already owns
        // that clap id and the two would collide inside this subcommand.
        #[arg(value_enum, default_value = "claude", value_name = "AGENT")]
        kind: AgentKind,

        /// Install into the repository (e.g. .claude/skills/) instead of the home directory
        #[arg(long, conflicts_with = "dir")]
        project: bool,

        /// Override the install base directory (the skills/git-loom/SKILL.md suffix is appended)
        #[arg(long, hide = true)]
        dir: Option<std::path::PathBuf>,
    },
}

#[derive(Args)]
#[command(args_conflicts_with_subcommands = true)]
struct BranchCmd {
    #[command(subcommand)]
    action: Option<BranchAction>,

    #[command(flatten)]
    new_args: BranchNewArgs,
}

#[derive(Subcommand)]
enum BranchAction {
    /// Create a new feature branch
    #[command(visible_alias = "create")]
    New(BranchNewArgs),

    /// Weave an existing branch into the integration branch
    Merge {
        /// Branch name (if not provided, shows interactive picker)
        branch: Option<String>,

        /// Also show remote branches without a local counterpart
        #[arg(short = 'a', long = "all")]
        all: bool,
    },

    /// Remove a branch from the integration branch (keeps the branch ref)
    Unmerge {
        /// Branch name or short ID (if not provided, shows interactive picker)
        branch: Option<String>,
    },
}

#[derive(Args, Clone)]
struct BranchNewArgs {
    /// Branch name (if not provided, will prompt interactively)
    name: Option<String>,

    /// Target commit, branch, or shortID (defaults to upstream base)
    #[arg(short = 't', long = "target")]
    target: Option<String>,
}

/// Message shown when a command is blocked by a paused loom operation.
///
/// `interrupted` tells whether git still has a rebase or merge going: if not,
/// the user likely finished it by hand, and `loom continue` only has the
/// post-rebase bookkeeping left to do.
fn paused_state_message(command: &str, interrupted: bool) -> String {
    if interrupted {
        format!(
            "A `loom {command}` is paused, with a rebase or merge still in progress.\n\
             Resolve what stopped it, then run `loom continue` to resume, or `loom abort` to cancel."
        )
    } else {
        format!(
            "A `loom {command}` is paused, but no rebase is in progress.\n\
             If you finished it yourself, run `loom continue` to wrap up and clear the state.\n\
             Run `loom abort` to discard it instead."
        )
    }
}

/// Message shown when git has a rebase or merge in progress that no loom state
/// file describes — an operation that failed before it could save state, or one
/// the user started with raw git.
fn stray_rebase_message(rebasing: bool, step: Option<(usize, usize)>) -> String {
    let what = if rebasing { "rebase" } else { "merge" };
    let progress = match step {
        Some((current, total)) => format!(" (stopped at step {current}/{total})"),
        None => String::new(),
    };
    format!(
        "A git {what} is in progress{progress}, but no loom operation is recorded.\n\
         Resolve any conflicts and run `loom continue` to finish it, or `loom abort` to cancel it."
    )
}

fn main() {
    let cli = parse_cli(&std::env::args_os().collect::<Vec<_>>());

    // Explicit opt-in only — never inferred from a missing terminal. The
    // sequence-editor subprocess is excluded: it inherits LOOM_AGENT from its
    // parent loom process, but its stderr flows through git and must stay clean.
    // `completions` too: its script is for a shell to source, never an agent.
    let never_agent = matches!(
        cli.command,
        Some(Command::InternalWriteTodo { .. }) | Some(Command::Completions { .. })
    );
    agent_mode::set(
        !never_agent
            && (cli.agent
                || std::env::var_os("LOOM_AGENT").is_some_and(|v| !v.is_empty() && v != "0")),
    );

    if !colors_enabled(cli.no_color, msg::human_stream_is_terminal()) {
        control::set_override(false);
    }

    // Completions don't need git, handle before version check
    if let Some(Command::Completions { shell }) = cli.command {
        finish_and_exit(completions::run(shell));
    }

    // Agent setup needs no git or repo either (unless --project), works while
    // an operation is paused, and is never trace-logged.
    if let Some(Command::Agent(cmd)) = cli.command {
        let result = match cmd.action {
            AgentAction::Init { kind, project, dir } => agent::init::run(kind, project, dir),
        };
        finish_and_exit(result);
    }

    if let Err(e) = git::check_git_version() {
        finish_and_exit(Err(e));
    }

    // Initialize logger for commands that modify the repo (skip for
    // InternalWriteTodo — it runs as a subprocess — and Status/Trace/Show which
    // are read-only). Tui browsing is read-only too; it initializes the logger
    // itself when an action runs.
    let should_log = !matches!(
        cli.command,
        Some(Command::InternalWriteTodo { .. })
            | Some(Command::Trace)
            | Some(Command::Show { .. })
            | Some(Command::Diff { .. })
            | Some(Command::Tui)
    );
    if should_log && let Ok(repo) = repo::open_repo() {
        let git_dir = repo.path().to_path_buf();
        let cmd_line = std::env::args().collect::<Vec<_>>().join(" ");
        if matches!(cli.command, Some(Command::Abort) | Some(Command::Continue)) {
            trace::init_appending(&git_dir, &cmd_line);
        } else {
            trace::init(&git_dir, &cmd_line);
        }
    }

    // Check for a paused loom operation and block most commands if one exists.
    // Exempt: show, trace, continue, abort, completions, internal-write-todo.
    let is_exempt = matches!(
        cli.command,
        Some(Command::Show { .. })
            | Some(Command::Diff { .. })
            | Some(Command::Trace)
            | Some(Command::Continue)
            | Some(Command::Abort)
            | Some(Command::Completions { .. })
            | Some(Command::InternalWriteTodo { .. })
    );
    if !is_exempt && let Ok(repo) = repo::open_repo() {
        let git_dir = repo.path().to_path_buf();
        let rebasing = git::rebase_is_in_progress(&git_dir);
        let interrupted = rebasing || git::merge_is_in_progress(&git_dir);
        if let Ok(Some(state)) = transaction::load(&git_dir) {
            finish_and_exit(Err(anyhow::anyhow!(paused_state_message(
                &state.command,
                interrupted
            ))));
        } else if interrupted {
            let step = if rebasing {
                git::rebase_progress(&git_dir)
            } else {
                None
            };
            finish_and_exit(Err(anyhow::anyhow!(stray_rebase_message(rebasing, step))));
        }
    }

    // The status TUI is a full-screen terminal UI — same rule as the hunk
    // pickers (a guard in tui::app::run backstops future call paths).
    if agent_mode::enabled() && matches!(cli.command, Some(Command::Tui)) {
        finish_and_exit(Err(anyhow::anyhow!(
            "the TUI is interactive and unavailable in agent mode\n\
             Use `loom status` instead"
        )));
    }

    let theme = graph_theme(resolve_theme_mode(cli.theme));

    let result = match cli.command {
        None => status::run(cli.files, cli.context, cli.all, theme),
        Some(Command::Status {
            files,
            context,
            all,
        }) => status::run(files, context, all, theme),
        Some(Command::Tui) => tui::app::run(theme),
        Some(Command::Init { name }) => init::run(name),
        Some(Command::Add {
            files,
            patch,
            hunks,
            hunks_from,
            git_args,
        }) => add::run(
            files,
            patch,
            HunkArgs::new(hunks, hunks_from),
            git_args,
            &theme,
        ),
        Some(Command::Switch { branch }) => switch::run(branch),
        Some(Command::Branch(cmd)) => match cmd.action {
            Some(BranchAction::New(args)) => branch::new::run(args.name, args.target),
            Some(BranchAction::Merge { branch, all }) => branch::merge::run(branch, all),
            Some(BranchAction::Unmerge { branch }) => branch::unmerge::run(branch),
            None => branch::new::run(cmd.new_args.name, cmd.new_args.target),
        },
        Some(Command::Reword { target, message }) => reword::run(target, message),
        Some(Command::Commit {
            branch,
            integration,
            message,
            patch,
            hunks,
            hunks_from,
            files,
            git_args,
        }) => commit::run(
            branch,
            integration,
            message,
            patch.then_some(HunkArgs::new(hunks, hunks_from)),
            files,
            git_args,
            &theme,
        ),
        Some(Command::Swap { a, b }) => swap::run(a, b),
        Some(Command::Drop { targets, yes }) => drop::run(targets, yes),
        Some(Command::Absorb { dry_run, files }) => absorb::run(dry_run, files),
        Some(Command::Show { target, git_args }) => show::run(target, git_args),
        Some(Command::Diff {
            args,
            staged,
            all,
            git_args,
        }) => diff::run(args, staged, all, git_args),
        Some(Command::Split {
            target,
            message,
            patch,
            hunks,
            hunks_from,
            files,
        }) => split::run(
            target,
            message,
            patch,
            HunkArgs::new(hunks, hunks_from),
            files,
            &theme,
        ),
        Some(Command::Push {
            branch,
            no_pr,
            force,
        }) => push::run(branch, no_pr, force),
        Some(Command::Update { yes }) => update::run(yes),
        Some(Command::Fold {
            create,
            patch,
            above,
            below,
            hunks,
            hunks_from,
            args,
            git_args,
        }) => {
            let anchor = above
                .map(fold::Anchor::Above)
                .or(below.map(fold::Anchor::Below));
            fold::run(
                create,
                patch,
                anchor,
                HunkArgs::new(hunks, hunks_from),
                args,
                git_args,
                &theme,
            )
        }
        Some(Command::Trace) => trace::run(),
        Some(Command::Continue) => transaction::continue_run(),
        Some(Command::Abort) => transaction::abort_run(),
        Some(Command::Completions { .. }) | Some(Command::Agent(_)) => unreachable!(),
        Some(Command::InternalWriteTodo { source, todo_file }) => {
            handle_write_todo(&source, &todo_file)
        }
    };

    trace::finalize();

    finish_and_exit(result);
}

/// Report the command result and exit.
///
/// In agent mode the last line of stdout is always a single JSON status (see
/// spec 019); prompts answered structurally (the `NeedsInput` marker) skip the
/// human error line because the JSON is the message.
fn finish_and_exit(result: anyhow::Result<()>) -> ! {
    if agent_mode::enabled() {
        // Advisory only, and before `finish` so the notice reaches the JSON
        // `messages`: an agent that loaded a stale skill cannot notice a newer
        // one by itself (spec 019).
        agent::init::report_outdated_skills();
        if let Err(e) = &result
            && e.downcast_ref::<agent_mode::NeedsInput>().is_none()
        {
            msg::error(&e.to_string());
        }
        std::process::exit(agent_mode::finish(&result));
    }
    if let Err(e) = result {
        msg::error(&e.to_string());
        std::process::exit(1);
    }
    std::process::exit(0);
}

/// Build the CLI and parse `args`. The help text is generated here rather than
/// in the derive attributes because clap renders it while parsing, before
/// `main` gets a chance to look at `--no-color` or the terminal background.
fn parse_cli(args: &[OsString]) -> Cli {
    // Clap renders help on stdout whatever agent mode does with the rest.
    let color = colors_enabled(
        args.iter().any(|arg| arg == "--no-color"),
        std::io::stdout().is_terminal(),
    );
    // Only a colored help needs a theme. Resolving it unconditionally would
    // also pin the one-shot detection here, before `main` has read `--agent`,
    // and make every piped run pay a terminal query for a color it discards.
    let mode = if color {
        resolve_theme_mode(early_theme(args))
    } else {
        ThemeMode::Dark
    };
    let styles = help_styles(mode, color);
    let mut command = Cli::command()
        .styles(styles.clone())
        .about(apply_styles(ABOUT, &styles))
        .after_help(apply_styles(GROUPED_COMMANDS, &styles))
        .help_template(apply_styles(HELP_TEMPLATE, &styles));
    if !color {
        command = command.color(clap::ColorChoice::Never);
    }
    let matches = command.get_matches_from(args);
    match Cli::from_arg_matches(&matches) {
        Ok(cli) => cli,
        Err(err) => err.exit(),
    }
}

/// Whether colored output should be emitted at all. `is_terminal` is the
/// probe of whichever stream the text goes to: help is always stdout, while
/// runtime output follows agent mode onto stderr.
fn colors_enabled(no_color: bool, is_terminal: bool) -> bool {
    !no_color
        && std::env::var_os("NO_COLOR").is_none()
        && std::env::var_os("TERM").is_none_or(|v| v != "dumb")
        && is_terminal
}

/// Read `--theme` from the raw args, for the same reason as `parse_cli`.
/// Unknown values fall back to `Auto`; clap reports them during the real parse.
fn early_theme(args: &[OsString]) -> ThemeArg {
    let mut rest = args.iter().skip(1).filter_map(|arg| arg.to_str());
    while let Some(arg) = rest.next() {
        let value = match arg.strip_prefix("--theme") {
            Some("") => rest.next(),
            Some(tail) => tail.strip_prefix("="),
            None => continue,
        };
        if let Some(value) = value
            && let Ok(theme) = ThemeArg::from_str(value, true)
        {
            return theme;
        }
    }
    ThemeArg::Auto
}

fn resolve_theme_mode(arg: ThemeArg) -> ThemeMode {
    match arg {
        ThemeArg::Dark => ThemeMode::Dark,
        ThemeArg::Light => ThemeMode::Light,
        ThemeArg::Auto => detect_theme_mode(),
    }
}

/// Query the terminal for its background color, at most once per run.
fn detect_theme_mode() -> ThemeMode {
    static DETECTED: OnceLock<ThemeMode> = OnceLock::new();
    *DETECTED.get_or_init(|| {
        // The stream the colors it picks are written to: stderr in agent mode
        // (spec 019). Reached from `parse_cli` only for a colored help, which
        // is stdout and not in agent mode, so the answer is the right one
        // whichever call gets here first.
        if !msg::human_stream_is_terminal() {
            return ThemeMode::Dark;
        }
        use terminal_colorsaurus::{QueryOptions, ThemeMode as Detected, theme_mode};
        match theme_mode(QueryOptions::default()) {
            Ok(Detected::Light) => ThemeMode::Light,
            _ => ThemeMode::Dark,
        }
    })
}

fn graph_theme(mode: ThemeMode) -> graph::Theme {
    match mode {
        ThemeMode::Dark => graph::Theme::dark(),
        ThemeMode::Light => graph::Theme::light(),
    }
}

fn handle_write_todo(source: &str, todo_file: &str) -> anyhow::Result<()> {
    // Save the original git todo to a sidecar file (for logging)
    if let Ok(original) = std::fs::read_to_string(todo_file) {
        let sidecar = format!("{}.original", source);
        let _ = std::fs::write(sidecar, original);
    }

    let content = std::fs::read_to_string(source)
        .with_context(|| format!("Failed to read source file '{}'", source))?;
    std::fs::write(todo_file, content)
        .with_context(|| format!("Failed to write todo file '{}'", todo_file))?;
    Ok(())
}

#[cfg(test)]
#[path = "main_test.rs"]
mod tests;