fallow-cli 3.19.0

CLI for fallow, codebase intelligence for TypeScript and JavaScript
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
//! `fallow agent`: one-shot onboarding of coding-agent harnesses.
//!
//! `fallow agent install` composes the pieces that previously lived behind
//! separate entry points (`init --agents`, `hooks install --target agent`,
//! the README's MCP snippet, and the skill shipped under
//! `node_modules/fallow/skills/fallow`) into one idempotent pass per detected
//! harness. Every file or block it writes carries a versioned
//! `fallow:agent-install` marker so `status` can report it and `uninstall`
//! can remove exactly that content and nothing else.

mod guide;
mod hooks;
pub mod hosts;
mod mcp;
mod skill;
mod status;

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use serde::Serialize;

pub use crate::setup_hooks::Mode;
use crate::setup_hooks::home_dir;

pub use status::run_agent_status;

/// Marker grammar version. Bump when the marker format changes so `status`
/// can tell an older install apart from a corrupt one.
pub const MARKER_VERSION: &str = "v1";
/// Common prefix of every marker this command writes.
pub const MARKER_PREFIX: &str = "fallow:agent-install";
/// JSON envelope version of `agent install|status|uninstall`.
pub const SCHEMA_VERSION: u32 = 1;

/// A coding-agent harness fallow knows how to wire up.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, clap::ValueEnum)]
#[serde(rename_all = "snake_case")]
pub enum Harness {
    /// Claude Code: `.mcp.json`, `.claude/skills/`, `.claude/settings.json` gate, `CLAUDE.md` import.
    Claude,
    /// OpenAI Codex CLI: `.codex/config.toml`, `.agents/skills/`, `AGENTS.md` block.
    Codex,
    /// Cursor: `.cursor/mcp.json`, `.agents/skills/`, `AGENTS.md`.
    Cursor,
}

impl Harness {
    pub const ALL: [Self; 3] = [Self::Claude, Self::Codex, Self::Cursor];

    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Claude => "claude",
            Self::Codex => "codex",
            Self::Cursor => "cursor",
        }
    }

    pub const fn display_name(self) -> &'static str {
        match self {
            Self::Claude => "Claude Code",
            Self::Codex => "Codex",
            Self::Cursor => "Cursor",
        }
    }
}

/// `--harness` argument: explicit harnesses or automatic detection.
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum HarnessArg {
    /// Select every harness with evidence in the project, home directory, or environment.
    Auto,
    /// Claude Code.
    Claude,
    /// OpenAI Codex CLI.
    Codex,
    /// Cursor.
    Cursor,
}

/// One installable piece. `--without` skips it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, clap::ValueEnum)]
#[serde(rename_all = "snake_case")]
pub enum Step {
    /// `AGENTS.md` scaffold or task-map block, plus the `CLAUDE.md` import for Claude Code.
    Guide,
    /// The fallow skill under `.claude/skills/` or `.agents/skills/`.
    Skill,
    /// MCP server registration for the harness.
    Mcp,
    /// The commit and push gate (`fallow hooks install --target agent`).
    Hooks,
}

impl Step {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Guide => "guide",
            Self::Skill => "skill",
            Self::Mcp => "mcp",
            Self::Hooks => "hooks",
        }
    }
}

/// Why a step was skipped or refused. The set is part of the JSON contract
/// (`docs/backwards-compatibility.md`); add a variant there when adding one
/// here.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Reason {
    /// A skill named `fallow` exists at the target without a fallow marker.
    SkillNameTaken,
    /// The shipped skill was not available at build time (crates.io builds).
    SkillNotEmbedded,
    /// No `fallow-mcp` launcher could be resolved.
    McpEntryUnavailable,
    /// A `fallow` MCP entry exists that fallow did not write.
    McpEntryForeign,
    /// The only launcher is an absolute path on this machine, unfit for a shared file.
    MachineLocalLauncher,
    /// `--approve` was not passed.
    ApprovalNotRequested,
    /// `.claude/settings.local.json` is tracked by git.
    SettingsLocalTracked,
    /// The harness stores this under a file fallow does not edit; a command is printed instead.
    ManualCommand,
    /// The harness has no supported surface for this step.
    UnsupportedHarness,
    /// The step is project-only and `--user` was passed.
    UserScopeUnsupported,
    /// An existing hook script has no fallow marker.
    UserEdited,
    /// The file is not valid JSON.
    InvalidJson,
    /// The file is not valid TOML.
    InvalidToml,
    /// The JSON document's top level is not an object.
    NotAnObject,
    /// Fallow markers exist but not as a start-then-end pair.
    ManagedBlockMalformed,
}

impl Reason {
    #[cfg_attr(
        not(test),
        allow(dead_code, reason = "read by the documentation drift test")
    )]
    pub const ALL: [Self; 15] = [
        Self::SkillNameTaken,
        Self::SkillNotEmbedded,
        Self::McpEntryUnavailable,
        Self::McpEntryForeign,
        Self::MachineLocalLauncher,
        Self::ApprovalNotRequested,
        Self::SettingsLocalTracked,
        Self::ManualCommand,
        Self::UnsupportedHarness,
        Self::UserScopeUnsupported,
        Self::UserEdited,
        Self::InvalidJson,
        Self::InvalidToml,
        Self::NotAnObject,
        Self::ManagedBlockMalformed,
    ];

    pub const fn as_str(self) -> &'static str {
        match self {
            Self::SkillNameTaken => "skill_name_taken",
            Self::SkillNotEmbedded => "skill_not_embedded",
            Self::McpEntryUnavailable => "mcp_entry_unavailable",
            Self::McpEntryForeign => "mcp_entry_foreign",
            Self::MachineLocalLauncher => "machine_local_launcher",
            Self::ApprovalNotRequested => "approval_not_requested",
            Self::SettingsLocalTracked => "settings_local_tracked",
            Self::ManualCommand => "manual_command",
            Self::UnsupportedHarness => "unsupported_harness",
            Self::UserScopeUnsupported => "user_scope_unsupported",
            Self::UserEdited => "user_edited",
            Self::InvalidJson => "invalid_json",
            Self::InvalidToml => "invalid_toml",
            Self::NotAnObject => "not_an_object",
            Self::ManagedBlockMalformed => "managed_block_malformed",
        }
    }
}

/// What happened to one path during install or uninstall.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StepStatus {
    /// File or block created or updated (or would be, under `--dry-run`).
    Written,
    /// Managed content removed (or would be, under `--dry-run`).
    Removed,
    /// Already in the desired state.
    Unchanged,
    /// Nothing to do for this harness or scope; `reason` says why.
    Skipped,
    /// Existing content is not fallow-managed; left untouched without `--force`.
    Refused,
    /// I/O or parse error; `detail` carries the message.
    Failed,
}

/// Whether a path is normally committed with the project or stays with the
/// person who ran the command.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Scope {
    Shared,
    Local,
}

/// One row of the install, uninstall, or status report.
#[derive(Clone, Debug, Serialize)]
pub struct StepReport {
    /// `None` for harness-neutral files such as `AGENTS.md` or `.agents/skills/`.
    pub harness: Option<Harness>,
    pub step: Step,
    pub status: StepStatus,
    pub scope: Scope,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<Reason>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
}

impl StepReport {
    pub fn new(harness: Option<Harness>, step: Step, status: StepStatus, scope: Scope) -> Self {
        Self {
            harness,
            step,
            status,
            scope,
            path: None,
            reason: None,
            detail: None,
        }
    }

    pub fn path(mut self, ctx: &Ctx, path: &Path) -> Self {
        self.path = Some(display_path(&ctx.root, ctx.home.as_deref(), path));
        self
    }

    pub fn reason(mut self, reason: Reason) -> Self {
        self.reason = Some(reason);
        self
    }

    pub fn detail(mut self, detail: impl Into<String>) -> Self {
        self.detail = Some(detail.into());
        self
    }

    pub fn failed(
        harness: Option<Harness>,
        step: Step,
        scope: Scope,
        message: impl Into<String>,
    ) -> Self {
        Self::new(harness, step, StepStatus::Failed, scope).detail(message)
    }
}

/// A follow-up the user or agent may run after the install. Unlike the
/// read-only `next_steps[]` of analysis commands, these can mutate harness
/// config, which `mutating` states per entry.
#[derive(Clone, Debug, Serialize)]
pub struct NextAction {
    pub id: &'static str,
    pub command: String,
    pub reason: String,
    pub mutating: bool,
}

/// Render a path relative to the project root, as `~/...` under the home
/// directory, and absolute only when it is under neither.
pub fn display_path(root: &Path, home: Option<&Path>, path: &Path) -> String {
    let root_rel = path.strip_prefix(root).ok();
    let home_rel = home.and_then(|home| path.strip_prefix(home).ok());
    let root_len = root.as_os_str().len();
    let home_len = home.map_or(0, |home| home.as_os_str().len());
    match (root_rel, home_rel) {
        (Some(rel), Some(_)) if root_len >= home_len => slashes(rel),
        (Some(rel), None) => slashes(rel),
        (_, Some(rel)) => format!("~/{}", slashes(rel)),
        (None, None) => slashes(path),
    }
}

fn slashes(path: &Path) -> String {
    path.display().to_string().replace('\\', "/")
}

/// Options for `fallow agent install`.
pub struct AgentInstallOptions<'a> {
    pub root: &'a Path,
    /// True when `--root` was passed explicitly; otherwise the git toplevel wins.
    pub root_explicit: bool,
    pub harnesses: &'a [HarnessArg],
    pub user: bool,
    pub without: &'a [Step],
    pub dry_run: bool,
    pub force: bool,
    pub approve: bool,
    pub gitignore_claude: bool,
}

/// Options for `fallow agent uninstall`.
pub struct AgentUninstallOptions<'a> {
    pub root: &'a Path,
    pub root_explicit: bool,
    pub harnesses: &'a [HarnessArg],
    pub user: bool,
    pub dry_run: bool,
    pub force: bool,
}

/// Shared execution context for every step.
pub struct Ctx {
    pub root: PathBuf,
    pub home: Option<PathBuf>,
    pub user: bool,
    pub dry_run: bool,
    pub force: bool,
    pub approve: bool,
    pub gitignore_claude: bool,
    pub mode: Mode,
}

impl Ctx {
    /// Base directory for a harness-owned file: `$HOME` under `--user`,
    /// otherwise the project root.
    pub fn scope_base(&self) -> Result<&Path, String> {
        if self.user {
            self.home.as_deref().ok_or_else(|| {
                "Cannot resolve the user home directory; unset --user or set $HOME.".to_string()
            })
        } else {
            Ok(&self.root)
        }
    }

    pub const fn scope(&self) -> Scope {
        if self.user {
            Scope::Local
        } else {
            Scope::Shared
        }
    }
}

#[derive(Serialize)]
struct Report {
    kind: &'static str,
    schema_version: u32,
    fallow_version: &'static str,
    root: String,
    mode: Mode,
    dry_run: bool,
    harnesses: Vec<Harness>,
    /// True when the harness list came from detection rather than `--harness`.
    detected: bool,
    evidence: Vec<hosts::Detection>,
    steps: Vec<StepReport>,
    next_actions: Vec<NextAction>,
}

/// Pick the project root: an explicit `--root` is used as given; otherwise
/// the git toplevel of the resolved root, so running from a monorepo package
/// directory still writes `.mcp.json` and `AGENTS.md` where the harnesses
/// read them.
pub fn resolve_root(root: &Path, root_explicit: bool) -> PathBuf {
    if root_explicit {
        return dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    }
    crate::base_worktree::git_toplevel(root)
        .unwrap_or_else(|| dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()))
}

fn select_harnesses(
    requested: &[HarnessArg],
    root: &Path,
    home: Option<&Path>,
) -> (Vec<Harness>, bool, Vec<hosts::Detection>) {
    let auto = requested.is_empty() || requested.contains(&HarnessArg::Auto);
    let evidence = hosts::detect(root, home);
    if auto {
        let harnesses = evidence.iter().map(|d| d.harness).collect();
        return (harnesses, true, evidence);
    }
    let mut harnesses: Vec<Harness> = Harness::ALL
        .into_iter()
        .filter(|harness| {
            requested.iter().any(|arg| match arg {
                HarnessArg::Claude => *harness == Harness::Claude,
                HarnessArg::Codex => *harness == Harness::Codex,
                HarnessArg::Cursor => *harness == Harness::Cursor,
                HarnessArg::Auto => false,
            })
        })
        .collect();
    harnesses.dedup();
    (harnesses, false, evidence)
}

/// Entry point for `fallow agent install`.
pub fn run_agent_install(
    opts: &AgentInstallOptions<'_>,
    output: fallow_config::OutputFormat,
    json_style: crate::json_style::JsonStyle,
) -> ExitCode {
    let root = resolve_root(opts.root, opts.root_explicit);
    let home = home_dir();
    let (harnesses, detected, evidence) = select_harnesses(opts.harnesses, &root, home.as_deref());
    let ctx = Ctx {
        root: root.clone(),
        home,
        user: opts.user,
        dry_run: opts.dry_run,
        force: opts.force,
        approve: opts.approve,
        gitignore_claude: opts.gitignore_claude,
        mode: Mode::Install,
    };
    let skip = |step: Step| opts.without.contains(&step);

    let mut steps: Vec<StepReport> = Vec::new();
    if !skip(Step::Guide) {
        steps.extend(guide::install(&ctx, &harnesses));
    }
    if !skip(Step::Skill) {
        steps.extend(skill::install(&ctx, &harnesses));
    }
    let mcp_command = if skip(Step::Mcp) {
        None
    } else {
        let command = mcp::resolve_command(&root);
        steps.extend(mcp::install(&ctx, &harnesses, command.as_ref()));
        command
    };
    if !skip(Step::Hooks) {
        steps.extend(hooks::install(&ctx, &harnesses));
    }

    let next_actions = next_actions(&ctx, &harnesses, detected, mcp_command.as_ref(), &steps);
    let report = Report {
        kind: "agent-install",
        schema_version: SCHEMA_VERSION,
        fallow_version: env!("CARGO_PKG_VERSION"),
        root: slashes(&root),
        mode: Mode::Install,
        dry_run: opts.dry_run,
        harnesses,
        detected,
        evidence,
        steps,
        next_actions,
    };
    render(&report, output, json_style)
}

/// Entry point for `fallow agent uninstall`.
pub fn run_agent_uninstall(
    opts: &AgentUninstallOptions<'_>,
    output: fallow_config::OutputFormat,
    json_style: crate::json_style::JsonStyle,
) -> ExitCode {
    let root = resolve_root(opts.root, opts.root_explicit);
    let home = home_dir();
    let (harnesses, detected, evidence) = select_harnesses(opts.harnesses, &root, home.as_deref());
    let ctx = Ctx {
        root: root.clone(),
        home,
        user: opts.user,
        dry_run: opts.dry_run,
        force: opts.force,
        approve: false,
        gitignore_claude: false,
        mode: Mode::Uninstall,
    };

    let mut steps: Vec<StepReport> = Vec::new();
    steps.extend(hooks::uninstall(&ctx, &harnesses));
    steps.extend(mcp::uninstall(&ctx, &harnesses));
    steps.extend(skill::uninstall(&ctx, &harnesses));
    steps.extend(guide::uninstall(&ctx, &harnesses));

    let report = Report {
        kind: "agent-uninstall",
        schema_version: SCHEMA_VERSION,
        fallow_version: env!("CARGO_PKG_VERSION"),
        root: slashes(&root),
        mode: Mode::Uninstall,
        dry_run: opts.dry_run,
        harnesses,
        detected,
        evidence,
        steps,
        next_actions: Vec::new(),
    };
    render(&report, output, json_style)
}

fn next_actions(
    ctx: &Ctx,
    harnesses: &[Harness],
    detected: bool,
    mcp_command: Option<&mcp::McpCommand>,
    steps: &[StepReport],
) -> Vec<NextAction> {
    let mut next: Vec<NextAction> = Vec::new();
    if detected && harnesses.is_empty() {
        next.push(NextAction {
            id: "choose-harness",
            command: "fallow agent install --harness claude".to_string(),
            reason: "No harness was detected; pass --harness claude, codex, or cursor to wire one explicitly."
                .to_string(),
            mutating: true,
        });
    }
    if let Some(command) = mcp_command {
        if harnesses.contains(&Harness::Codex) && !ctx.user {
            next.push(NextAction {
                id: "codex-mcp-add",
                command: format!("codex mcp add fallow -- {}", command.shell_words()),
                reason: "A project-level .codex/config.toml only applies once Codex trusts the project; the user-level entry works immediately."
                    .to_string(),
                mutating: true,
            });
        }
        if harnesses.contains(&Harness::Claude) && ctx.user {
            next.push(NextAction {
                id: "claude-mcp-add-user",
                command: format!("claude mcp add --scope user fallow -- {}", command.shell_words()),
                reason: "fallow does not edit ~/.claude.json; register the user-scope server through the Claude CLI."
                    .to_string(),
                mutating: true,
            });
        }
        let approval_skipped = steps.iter().any(|step| {
            step.harness == Some(Harness::Claude)
                && step.step == Step::Mcp
                && step.reason == Some(Reason::ApprovalNotRequested)
        });
        if approval_skipped {
            next.push(NextAction {
                id: "claude-approve-mcp",
                command: "fallow agent install --harness claude --approve".to_string(),
                reason: "Claude Code asks before starting a project-scoped MCP server; --approve records that approval for you in .claude/settings.local.json."
                    .to_string(),
                mutating: true,
            });
        }
    }
    if !has_config_file(&ctx.root) {
        next.push(NextAction {
            id: "recommend-config",
            command: "fallow recommend --format json".to_string(),
            reason: "No fallow config was found; recommend proposes one from the detected stack without writing anything."
                .to_string(),
            mutating: false,
        });
    }
    next
}

fn has_config_file(root: &Path) -> bool {
    [
        ".fallowrc.json",
        ".fallowrc.jsonc",
        "fallow.toml",
        ".fallow.toml",
    ]
    .iter()
    .any(|name| root.join(name).is_file())
}

fn render(
    report: &Report,
    output: fallow_config::OutputFormat,
    json_style: crate::json_style::JsonStyle,
) -> ExitCode {
    let blocked = report
        .steps
        .iter()
        .any(|step| matches!(step.status, StepStatus::Refused | StepStatus::Failed));
    let exit = if blocked {
        ExitCode::from(2)
    } else {
        ExitCode::SUCCESS
    };
    match output {
        fallow_config::OutputFormat::Json => match json_style.serialize(report) {
            Ok(json) => {
                crate::report::sink::outln!("{json}");
                exit
            }
            Err(error) => crate::error::emit_error_with_style(
                &format!("failed to serialize agent report: {error}"),
                2,
                output,
                json_style,
            ),
        },
        fallow_config::OutputFormat::Human => {
            print_human(report);
            exit
        }
        _ => crate::error::emit_error("agent commands support human and json output", 2, output),
    }
}

fn print_human(report: &Report) {
    eprint!("{}", render_human(report));
}

fn render_human(report: &Report) -> String {
    use std::fmt::Write as _;
    let mut out = String::new();
    let suffix = if report.dry_run { " (dry run)" } else { "" };
    let _ = writeln!(out, "fallow agent {}{suffix}", report.mode.as_str());
    let _ = writeln!(out, "  root: {}", report.root);
    let names: Vec<&str> = report.harnesses.iter().map(|h| h.as_str()).collect();
    let origin = if report.detected {
        "detected"
    } else {
        "from --harness"
    };
    if names.is_empty() {
        let _ = writeln!(
            out,
            "  harnesses: none {origin}; harness-neutral files only"
        );
    } else {
        let _ = writeln!(out, "  harnesses: {} ({origin})", names.join(", "));
    }

    let shared_header = if report.mode == Mode::Install {
        "Shared with your team (commit these):"
    } else {
        "Shared with your team:"
    };
    for (header, scope) in [
        (shared_header, Scope::Shared),
        ("Local to you:", Scope::Local),
    ] {
        let rows: Vec<&StepReport> = report
            .steps
            .iter()
            .filter(|step| step.scope == scope)
            .collect();
        if rows.is_empty() {
            continue;
        }
        out.push('\n');
        let _ = writeln!(out, "{header}");
        for step in rows {
            out.push_str(&render_step(step, report.dry_run));
        }
    }

    let refused = report
        .steps
        .iter()
        .filter(|step| step.status == StepStatus::Refused)
        .count();
    let failed = report
        .steps
        .iter()
        .filter(|step| step.status == StepStatus::Failed)
        .count();
    if refused + failed > 0 {
        out.push('\n');
        let mut parts: Vec<String> = Vec::new();
        if refused > 0 {
            parts.push(format!(
                "{refused} step{} refused (existing content is not fallow-managed; pass --force to replace it)",
                if refused == 1 { "" } else { "s" }
            ));
        }
        if failed > 0 {
            parts.push(format!(
                "{failed} step{} failed",
                if failed == 1 { "" } else { "s" }
            ));
        }
        let _ = writeln!(
            out,
            "{}; every other step still ran. Exit code 2.",
            parts.join(", ")
        );
    } else if report.mode == Mode::Uninstall
        && report
            .steps
            .iter()
            .all(|step| matches!(step.status, StepStatus::Unchanged | StepStatus::Skipped))
    {
        out.push('\n');
        let _ = writeln!(out, "Nothing to remove.");
    }

    if !report.next_actions.is_empty() {
        out.push('\n');
        let _ = writeln!(out, "Next:");
        for next in &report.next_actions {
            let _ = writeln!(out, "  {}", next.command);
            let _ = writeln!(out, "    {}", next.reason);
        }
    }
    out
}

fn render_step(step: &StepReport, dry_run: bool) -> String {
    let status = match (step.status, dry_run) {
        (StepStatus::Written, true) => "would write",
        (StepStatus::Written, false) => "written",
        (StepStatus::Removed, true) => "would remove",
        (StepStatus::Removed, false) => "removed",
        (StepStatus::Unchanged, _) => "unchanged",
        (StepStatus::Skipped, _) => "skipped",
        (StepStatus::Refused, _) => "refused",
        (StepStatus::Failed, _) => "failed",
    };
    let label = match step.harness {
        Some(harness) => format!("{} ({})", step.step.as_str(), harness.as_str()),
        None => step.step.as_str().to_string(),
    };
    let path = step.path.as_deref().unwrap_or("-");
    let mut note = String::new();
    if let Some(reason) = step.reason {
        note.push_str(reason.as_str());
    }
    if let Some(detail) = &step.detail {
        if !note.is_empty() {
            note.push_str(": ");
        }
        note.push_str(detail);
    }
    if note.is_empty() {
        format!("  {path:<40}  {status:<13}  {label}\n")
    } else {
        format!("  {path:<40}  {status:<13}  {label:<16}  {note}\n")
    }
}

#[cfg(test)]
mod tests;