loopflow 0.10.0

Run steps and flows with coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
use clap::{Args, Parser, Subcommand};

pub mod commands;
pub mod discovery;
pub mod output;
pub mod session;

#[derive(Parser, Debug)]
#[command(name = "lf")]
#[command(about = "Run steps and flows with coding agents")]
#[command(version)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Option<Commands>,

    /// List available steps and flows
    #[arg(short, long)]
    pub list: bool,

    /// Direction(s) to apply (repeatable or comma-separated)
    #[arg(
        short = 'd',
        long = "direction",
        value_delimiter = ',',
        short_alias = 'D'
    )]
    pub direction: Vec<String>,

    /// Exclude config default directions
    #[arg(long = "no-direction")]
    pub no_direction: bool,

    /// Docs paths, globs, or directories to include in context
    #[arg(long = "docs", value_delimiter = ',')]
    pub docs: Vec<String>,

    /// Include clipboard content in prompt
    #[arg(short = 'c', long = "clipboard", short_alias = 'C')]
    pub clipboard: bool,

    /// Model to use (harness or harness:model)
    #[arg(short = 'm', long = "model", short_alias = 'M')]
    pub model: Option<String>,

    /// Skip permission prompts
    #[arg(long)]
    pub yolo: bool,

    /// Run interactively
    #[arg(short = 'i', long = "interactive", short_alias = 'I')]
    pub interactive: bool,

    /// Run in batch/headless mode
    #[arg(short = 'b', long = "batch", short_alias = 'B')]
    pub batch: bool,

    /// Hand off to an interactive vendor session in the terminal (overrides session.launch)
    #[arg(long, conflicts_with = "ide")]
    pub tui: bool,

    /// Hand off to an interactive vendor session in the vendor app (overrides session.launch)
    #[arg(long)]
    pub ide: bool,

    /// Enable Chrome integration (Claude)
    #[arg(long)]
    pub chrome: bool,

    /// Disable Chrome integration (Claude)
    #[arg(long = "no-chrome", overrides_with = "chrome")]
    pub no_chrome: bool,

    /// Include files changed on branch
    #[arg(long = "diff-files")]
    pub diff_files: bool,

    /// Exclude files changed on branch
    #[arg(long = "no-diff-files", overrides_with = "diff_files")]
    pub no_diff_files: bool,

    /// Include raw git diff
    #[arg(long = "diff")]
    pub diff: bool,

    /// Exclude raw git diff
    #[arg(long = "no-diff", overrides_with = "diff")]
    pub no_diff: bool,

    /// Wave name for wave/ scoping
    #[arg(short = 'w', long = "wave", short_alias = 'W')]
    pub wave: Option<String>,

    /// Exclude loopflow operating guidance
    #[arg(long = "no-loopflow")]
    pub no_loopflow: bool,

    /// Run this invocation in a separate worktree targeting the current branch
    #[arg(long, conflicts_with_all = ["stack", "fork"])]
    pub dispatch: bool,

    /// Run this invocation in a worktree stacked on a parent run
    #[arg(long, value_name = "RUN_ID", conflicts_with_all = ["dispatch", "fork"])]
    pub stack: Option<String>,

    /// Run this invocation in a separate worktree forked from the review base
    #[arg(long, conflicts_with_all = ["dispatch", "stack"])]
    pub fork: bool,
}

impl Cli {
    fn toggle_setting(enabled: bool, disabled: bool) -> Option<bool> {
        if enabled {
            Some(true)
        } else if disabled {
            Some(false)
        } else {
            None
        }
    }

    /// Get chrome setting: Some(true) if --chrome, Some(false) if --no-chrome, None if neither.
    pub fn chrome_setting(&self) -> Option<bool> {
        Self::toggle_setting(self.chrome, self.no_chrome)
    }

    /// Get diff_files setting: Some(true) if --diff-files, Some(false) if --no-diff-files, None if neither.
    pub fn diff_files_setting(&self) -> Option<bool> {
        Self::toggle_setting(self.diff_files, self.no_diff_files)
    }

    /// Get diff setting: Some(true) if --diff, Some(false) if --no-diff, None if neither.
    pub fn diff_setting(&self) -> Option<bool> {
        Self::toggle_setting(self.diff, self.no_diff)
    }
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    /// Run an inline prompt
    #[command(name = ":")]
    Inline {
        #[arg(trailing_var_arg = true)]
        prompt: Vec<String>,
    },
    /// Git operations
    Op {
        #[command(subcommand)]
        op: OpsCommand,
    },
    /// Start a wave: a long-lived listener (journal, doors, live events over
    /// a loopback HTTP port; discovery via `wave/<name>/.wave-endpoint`)
    /// that spawns and supervises the wave's mind as a resident child
    /// process.
    #[command(name = "wave")]
    Wave {
        /// Wave name (matches wave/<name>/)
        name: String,
        /// Take over even if lfd reports another live wave-agent session
        #[arg(long)]
        force: bool,
        /// Serve dormant: listener only, no resident (health reads mind: null)
        #[arg(long, conflicts_with = "mind_only")]
        no_mind: bool,
        /// Run only the resident (the mind) against an existing listener
        #[arg(long, conflicts_with = "no_mind")]
        mind_only: bool,
    },
    /// Show token usage by repo and provider (from a running lfd)
    Usage,
    /// Show recent loopflow runs from the local ledger (all repos, local-only)
    Runs,
    /// Reconstruct one run from the local ledger: steps, durations, tokens, prompt logs
    Trace {
        /// Run id from `lf runs` (a unique prefix is enough)
        run_id: String,
    },
    /// Post a message into a wave's thread (worker reports, child-wave
    /// escalations, proactive FYIs). Reads stdin when TEXT is omitted.
    Chat {
        /// Message text (reads stdin when omitted — heredoc-friendly)
        #[arg(trailing_var_arg = true)]
        text: Vec<String>,
        /// Attribution label for machine speech (e.g. --from ci). Overrides
        /// the ambient label; absent = the ambient sender (env, else "cli").
        #[arg(long)]
        from: Option<String>,
        #[command(flatten)]
        target: WaveTargetArgs,
    },
    /// Follow a wave's live event stream (turns, mind state, memory) until
    /// killed. Defaults to the invoking context's wave; exits 0 with a note
    /// when no wave resolves.
    Sub {
        /// Wave name (default: the ambient wave — env, else worktree)
        wave: Option<String>,
        /// Emit raw frames as NDJSON instead of human lines
        #[arg(long)]
        json: bool,
    },
    /// Read or curate a wave's MEMORY.md (server-owned; bare `lf memory` = show)
    Memory {
        #[command(subcommand)]
        cmd: Option<MemoryCommand>,
        #[command(flatten)]
        target: WaveTargetArgs,
    },
    /// External: step/flow name (when no subcommand matches)
    #[command(external_subcommand)]
    External(Vec<String>),
}

/// Wave targeting shared by `lf chat` and `lf memory`: default is the
/// invoking context's wave (`LFD_WAVE_ID` env, else the worktree name).
#[derive(Args, Debug, Clone, Default)]
pub struct WaveTargetArgs {
    /// Target wave by name
    #[arg(short = 'w', long = "wave", conflicts_with = "parent")]
    pub wave: Option<String>,
    /// Target the invoking wave's parent (escalation up the wave tree)
    #[arg(long)]
    pub parent: bool,
}

#[derive(Subcommand, Debug)]
pub enum MemoryCommand {
    /// Print the wave's MEMORY.md
    Show {
        #[command(flatten)]
        target: WaveTargetArgs,
    },
    /// Replace MEMORY.md from stdin (written by the live server, journaled)
    Update {
        /// One-line summary journaled with the update (default: first line)
        #[arg(long)]
        summary: Option<String>,
        #[command(flatten)]
        target: WaveTargetArgs,
    },
    /// Append one curated fact as a bullet
    Add {
        /// The fact to append
        fact: String,
        #[command(flatten)]
        target: WaveTargetArgs,
    },
}

#[derive(Subcommand, Debug)]
pub enum OpsCommand {
    /// Copy context to clipboard
    Cp {
        /// Patterns to exclude
        #[arg(short = 'e', long = "exclude")]
        exclude: Vec<String>,
        /// Files or directories to include
        paths: Vec<String>,
    },
    /// Check loopflow dependencies
    Doctor,
    /// Rebase current branch onto target (default: main)
    Rebase {
        /// Print the planned rebase strategy without mutating git
        #[arg(long)]
        plan: bool,
        /// Branch to rebase onto
        onto: Option<String>,
    },
    /// Push current branch to remote
    Push {
        #[arg(long)]
        force: bool,
    },
    /// Submit PR to merge queue
    Land {
        #[arg(long)]
        strict: bool,
        #[arg(long)]
        local: bool,
        #[arg(short = 'c', long = "create-pr")]
        create_pr: bool,
        #[arg(short = 'w', long = "worktree")]
        worktree: Option<String>,
        #[arg(short = 'm', long = "message")]
        message: Option<String>,
        #[arg(long = "title")]
        title: Option<String>,
        #[arg(long = "body")]
        body: Option<String>,
    },
    /// Create or update a PR
    Pr {
        #[arg(short = 'm', long = "model", short_alias = 'M')]
        model: Option<String>,
        #[arg(long = "title")]
        title: Option<String>,
        #[arg(long = "body")]
        body: Option<String>,
    },
    /// Update local main to match origin
    Sync,
    /// Sync loopflow steps into vendor Skills directories
    #[command(name = "sync-skills")]
    SyncSkills {
        /// Also write global vendor skill directories under ~/
        #[arg(long = "global")]
        global: bool,
        /// Confirm global writes without prompting
        #[arg(short = 'y', long = "yes")]
        yes: bool,
        /// Keep stale loopflow-generated skills
        #[arg(long = "no-prune")]
        no_prune: bool,
    },
    /// Rotate a recurring wave onto a fresh branch (pushed with upstream)
    Advance {
        /// Wave name (default: inferred from the worktree)
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
    },
    /// Create next iteration branch
    Next {
        #[arg(short = 'c', long = "create-pr")]
        create_pr: bool,
        #[arg(long = "no-rebase")]
        no_rebase: bool,
    },
    /// Commit changes
    Commit {
        #[arg(short = 'm', long = "message", short_alias = 'M')]
        message: Option<String>,
        #[arg(short = 'p', long = "push", short_alias = 'P')]
        push: bool,
        #[arg(long = "no-add")]
        no_add: bool,
    },
    /// Abandon branch: close PR, remove worktree, delete branch
    Abandon {
        /// Branch to abandon (default: current)
        branch: Option<String>,
        #[arg(short = 'f', long)]
        force: bool,
    },
    /// Remote branch operations
    Branches {
        #[command(subcommand)]
        cmd: BranchesCommand,
    },
    /// Worktree operations
    Wt {
        #[command(subcommand)]
        cmd: WtCommand,
    },
    /// Shell integration
    Shell {
        #[command(subcommand)]
        cmd: ShellCommand,
    },
    /// Release operations (run, check, notes, bump, tag, status)
    Release {
        #[command(subcommand)]
        cmd: ReleaseCommand,
    },
    /// Roadmap in Asana (show, update, init, status)
    Pm {
        #[command(subcommand)]
        cmd: PmCommand,
    },
    /// Provider authentication for local lf steps and ops
    Auth {
        #[command(subcommand)]
        cmd: AuthCommand,
    },
    /// Merge-queue maintenance for stacked wave runs
    Queue {
        #[command(subcommand)]
        cmd: QueueCommand,
    },
}

#[derive(Subcommand, Debug)]
pub enum QueueCommand {
    /// Run one reconcile pass: stack-status inference, draft/ready flips,
    /// lazy head rebase, queue-block attention writes
    Reconcile {
        /// Only this wave (default: every wave with queue state)
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
    },
}

#[derive(Subcommand, Debug)]
pub enum BranchesCommand {
    /// Preview remote branches by filter
    List {
        #[command(flatten)]
        filters: BranchFilterArgs,
    },
    /// Delete remote branches by filter
    Prune {
        #[command(flatten)]
        filters: BranchFilterArgs,
        /// Show what would be pruned without deleting anything
        #[arg(long = "dry-run")]
        dry_run: bool,
        /// Skip confirmation
        #[arg(short = 'y', long = "yes")]
        yes: bool,
    },
}

#[derive(Args, Debug, Clone)]
pub struct BranchFilterArgs {
    /// Branches authored by user (`@me` for current git user)
    #[arg(long = "user")]
    pub user: Option<String>,
    /// Branches whose name includes this wave segment
    #[arg(long = "wave")]
    pub wave: Option<String>,
    /// No commits in the last duration (for example 30d, 2w)
    #[arg(long = "stale")]
    pub stale: Option<String>,
    /// First unique commit before YYYY-MM-DD
    #[arg(long = "created-before")]
    pub created_before: Option<String>,
    /// Only branches already merged into main
    #[arg(long = "merged")]
    pub merged: bool,
    /// Include branches with open PRs
    #[arg(long = "include-open-prs")]
    pub include_open_prs: bool,
}

#[derive(Subcommand, Debug)]
pub enum PmCommand {
    /// Connect (or create) the wave's Asana project; write asana_project to GOAL.md
    Init {
        /// Wave name (auto-detected if omitted)
        wave: Option<String>,
        /// Wave name (flag form; same as positional wave)
        #[arg(short = 'w', long = "wave", conflicts_with_all = ["wave", "all"])]
        wave_flag: Option<String>,
        /// Initialize all waves under wave/
        #[arg(long, conflicts_with_all = ["wave", "wave_flag"])]
        all: bool,
    },
    /// Print the wave's live Asana roadmap
    Show {
        /// Wave name (auto-detected if omitted)
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
    },
    /// Create, edit, or close a roadmap task in Asana
    Update {
        /// Wave name (auto-detected if omitted)
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
        /// Existing task id to edit or close; omit to create a new task
        #[arg(long = "id")]
        id: Option<String>,
        /// Task title
        #[arg(long = "title")]
        title: String,
        /// Task notes/description
        #[arg(long = "notes")]
        notes: Option<String>,
        /// Set to `done` to close the task
        #[arg(long = "status")]
        status: Option<String>,
        /// PR URL to attach as a comment (the loop's write-back link)
        #[arg(long = "pr")]
        pr: Option<String>,
    },
    /// Show roadmap status for linked waves
    Status {
        /// Wave name (all PM-enabled waves if omitted)
        #[arg(short = 'w', long = "wave")]
        wave: Option<String>,
    },
}

#[derive(Subcommand, Debug)]
pub enum AuthCommand {
    /// Show authentication status for local credentials
    Status {
        /// Provider name (optional)
        provider: Option<String>,
    },
    /// Disconnect a provider from local lf credentials
    Disconnect {
        /// Provider name
        provider: String,
    },
    /// Store an API key from the provider's environment variable
    Configure {
        /// Provider name
        provider: String,
    },
    /// Start a provider auth flow explicitly
    Connect {
        /// Provider name
        provider: String,
    },
    /// External: provider name (so `lf op auth asana` works)
    #[command(external_subcommand)]
    External(Vec<String>),
}

#[derive(Subcommand, Debug)]
pub enum ReleaseCommand {
    /// Run the full release workflow end-to-end
    Run {
        /// Version to release: patch|minor|major|X.Y.Z (default: patch)
        version: Option<String>,
        #[arg(short = 't', long = "target")]
        target: Option<String>,
    },
    /// Check if PRs have merged since the last tag
    Check {
        #[arg(short = 't', long = "target")]
        target: Option<String>,
    },
    /// Generate release notes for a version
    Notes {
        /// Version (e.g. 0.9.6)
        version: String,
        #[arg(long = "prev-tag")]
        prev_tag: Option<String>,
        #[arg(short = 't', long = "target")]
        target: Option<String>,
    },
    /// Bump version in manifest files
    Bump {
        /// Version to bump to (e.g. 0.9.6)
        version: String,
        #[arg(short = 't', long = "target")]
        target: Option<String>,
    },
    /// Create a git tag and push it
    Tag {
        /// Version to tag (e.g. 0.9.6)
        version: String,
        #[arg(short = 't', long = "target")]
        target: Option<String>,
    },
    /// Check release workflow status
    Status {
        #[arg(short = 't', long = "target")]
        target: Option<String>,
    },
}

#[derive(Subcommand, Debug)]
pub enum WtCommand {
    /// Create a new worktree
    Create {
        /// Worktree name (creates ../NAME)
        name: String,
        #[arg(short = 'b', long = "base")]
        base: Option<String>,
        /// Stack under a parent branch (defaults to current branch when no value is passed)
        #[arg(short = 's', long = "stack", value_name = "PARENT", num_args = 0..=1, default_missing_value = "__current__")]
        stack: Option<String>,
        /// Force a root branch from the default branch
        #[arg(long = "main", conflicts_with_all = ["base", "stack", "fork"])]
        main: bool,
        /// Create an independent root branch from the review base
        #[arg(long, conflicts_with_all = ["base", "stack", "main"])]
        fork: bool,
        /// Print the placement plan without creating a worktree
        #[arg(long)]
        plan: bool,
    },
    /// Switch to a worktree
    Switch {
        /// Worktree name or full branch name to switch to
        name: String,
    },
    /// List worktrees
    List {
        #[arg(long)]
        format: Option<String>,
        #[arg(long)]
        full: bool,
        #[arg(long)]
        sync: bool,
    },
    /// Remove worktrees whose branches have been merged
    Prune {
        /// Show what would be pruned without removing anything
        #[arg(long)]
        dry_run: bool,
        /// Also prune fresh worktrees (no commits beyond main)
        #[arg(long)]
        include_fresh: bool,
    },
    /// Remove a worktree
    #[command(alias = "rm")]
    Remove {
        /// Worktree name to remove
        name: String,
        #[arg(short = 'f', long = "force")]
        force: bool,
    },
    /// Show CI status for current branch
    Ci {
        #[arg(short = 'w', long = "watch")]
        watch: bool,
        #[arg(short = 'l', long = "logs")]
        logs: bool,
    },
}

#[derive(Subcommand, Debug)]
pub enum ShellCommand {
    /// Print shell integration code
    Init {
        /// Shell to generate for (bash, zsh, fish)
        shell: Option<String>,
    },
    /// Install shell integration to config file
    Install {
        /// Shell to install for (bash, zsh, fish)
        shell: Option<String>,
    },
    /// Run a shell directive
    Directive {
        #[arg(trailing_var_arg = true)]
        command: Vec<String>,
    },
}

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

    #[test]
    fn pm_init_accepts_positional_wave() {
        let cli = Cli::try_parse_from(["lf", "op", "pm", "init", "pm"]).expect("parse");
        let Some(Commands::Op {
            op:
                OpsCommand::Pm {
                    cmd:
                        PmCommand::Init {
                            wave,
                            wave_flag,
                            all,
                        },
                },
        }) = cli.command
        else {
            panic!("expected pm init command");
        };

        assert_eq!(wave.as_deref(), Some("pm"));
        assert_eq!(wave_flag, None);
        assert!(!all);
    }

    #[test]
    fn pm_init_accepts_all_flag() {
        let cli = Cli::try_parse_from(["lf", "op", "pm", "init", "--all"]).expect("parse");
        let Some(Commands::Op {
            op:
                OpsCommand::Pm {
                    cmd:
                        PmCommand::Init {
                            wave,
                            wave_flag,
                            all,
                        },
                },
        }) = cli.command
        else {
            panic!("expected pm init command");
        };

        assert_eq!(wave, None);
        assert_eq!(wave_flag, None);
        assert!(all);
    }

    #[test]
    fn pm_show_accepts_wave_flag() {
        let cli =
            Cli::try_parse_from(["lf", "op", "pm", "show", "--wave", "goals"]).expect("parse");
        let Some(Commands::Op {
            op: OpsCommand::Pm {
                cmd: PmCommand::Show { wave },
            },
        }) = cli.command
        else {
            panic!("expected pm show command");
        };
        assert_eq!(wave.as_deref(), Some("goals"));
    }

    #[test]
    fn pm_update_parses_create_and_close() {
        let cli = Cli::try_parse_from([
            "lf", "op", "pm", "update", "--title", "Ship it", "--notes", "details",
        ])
        .expect("parse");
        let Some(Commands::Op {
            op:
                OpsCommand::Pm {
                    cmd:
                        PmCommand::Update {
                            wave,
                            id,
                            title,
                            notes,
                            status,
                            pr,
                        },
                },
        }) = cli.command
        else {
            panic!("expected pm update command");
        };
        assert_eq!(wave, None);
        assert_eq!(id, None);
        assert_eq!(title, "Ship it");
        assert_eq!(notes.as_deref(), Some("details"));
        assert_eq!(status, None);
        assert_eq!(pr, None);

        let cli = Cli::try_parse_from([
            "lf",
            "op",
            "pm",
            "update",
            "--id",
            "123",
            "--title",
            "Ship it",
            "--status",
            "done",
            "--pr",
            "https://github.com/acme/repo/pull/7",
        ])
        .expect("parse");
        let Some(Commands::Op {
            op:
                OpsCommand::Pm {
                    cmd: PmCommand::Update { id, status, pr, .. },
                },
        }) = cli.command
        else {
            panic!("expected pm update command");
        };
        assert_eq!(id.as_deref(), Some("123"));
        assert_eq!(status.as_deref(), Some("done"));
        assert_eq!(pr.as_deref(), Some("https://github.com/acme/repo/pull/7"));
    }

    #[test]
    fn chat_parses_text_and_targeting() {
        let cli = Cli::try_parse_from(["lf", "chat", "shipped", "the", "parser"]).expect("parse");
        let Some(Commands::Chat { text, from, target }) = cli.command else {
            panic!("expected chat command");
        };
        assert_eq!(text, vec!["shipped", "the", "parser"]);
        assert_eq!(from, None);
        assert_eq!(target.wave, None);
        assert!(!target.parent);

        // No text: stdin is the body. Flags come before the trailing text.
        let cli = Cli::try_parse_from(["lf", "chat", "--parent"]).expect("parse");
        let Some(Commands::Chat { text, target, .. }) = cli.command else {
            panic!("expected chat command");
        };
        assert!(text.is_empty());
        assert!(target.parent);

        let cli = Cli::try_parse_from(["lf", "chat", "--wave", "goals", "hi"]).expect("parse");
        let Some(Commands::Chat { text, target, .. }) = cli.command else {
            panic!("expected chat command");
        };
        assert_eq!(text, vec!["hi"]);
        assert_eq!(target.wave.as_deref(), Some("goals"));

        // Machine speech declares itself: --from rides ahead of the text
        // (the webhook gatekeeper's planned argv).
        let cli =
            Cli::try_parse_from(["lf", "chat", "--wave", "goals", "--from", "ci", "CI failed"])
                .expect("parse");
        let Some(Commands::Chat { text, from, .. }) = cli.command else {
            panic!("expected chat command");
        };
        assert_eq!(text, vec!["CI failed"]);
        assert_eq!(from.as_deref(), Some("ci"));

        // --wave and --parent are mutually exclusive.
        assert!(Cli::try_parse_from(["lf", "chat", "--wave", "goals", "--parent", "x"]).is_err());
    }

    #[test]
    fn memory_parses_bare_show_update_and_add() {
        let cli = Cli::try_parse_from(["lf", "memory", "--wave", "goals"]).expect("parse");
        let Some(Commands::Memory { cmd, target }) = cli.command else {
            panic!("expected memory command");
        };
        assert!(cmd.is_none(), "bare memory is show");
        assert_eq!(target.wave.as_deref(), Some("goals"));

        let cli =
            Cli::try_parse_from(["lf", "memory", "update", "--summary", "learned"]).expect("parse");
        let Some(Commands::Memory {
            cmd: Some(MemoryCommand::Update { summary, .. }),
            ..
        }) = cli.command
        else {
            panic!("expected memory update");
        };
        assert_eq!(summary.as_deref(), Some("learned"));

        let cli =
            Cli::try_parse_from(["lf", "memory", "add", "one fact", "--parent"]).expect("parse");
        let Some(Commands::Memory {
            cmd: Some(MemoryCommand::Add { fact, target }),
            ..
        }) = cli.command
        else {
            panic!("expected memory add");
        };
        assert_eq!(fact, "one fact");
        assert!(target.parent);
    }

    #[test]
    fn op_advance_parses_optional_wave() {
        let cli = Cli::try_parse_from(["lf", "op", "advance"]).expect("parse");
        assert!(matches!(
            cli.command,
            Some(Commands::Op {
                op: OpsCommand::Advance { wave: None }
            })
        ));

        let cli = Cli::try_parse_from(["lf", "op", "advance", "-w", "goals"]).expect("parse");
        let Some(Commands::Op {
            op: OpsCommand::Advance { wave },
        }) = cli.command
        else {
            panic!("expected op advance command");
        };
        assert_eq!(wave.as_deref(), Some("goals"));
    }

    #[test]
    fn branches_list_accepts_filters() {
        let cli = Cli::try_parse_from([
            "lf", "op", "branches", "list", "--user", "@me", "--stale", "60d",
        ])
        .expect("parse");
        let Some(Commands::Op {
            op:
                OpsCommand::Branches {
                    cmd:
                        BranchesCommand::List {
                            filters:
                                BranchFilterArgs {
                                    user,
                                    stale,
                                    merged,
                                    ..
                                },
                        },
                },
        }) = cli.command
        else {
            panic!("expected branches list command");
        };

        assert_eq!(user.as_deref(), Some("@me"));
        assert_eq!(stale.as_deref(), Some("60d"));
        assert!(!merged);
    }

    #[test]
    fn branches_prune_accepts_yes_and_dry_run() {
        let cli = Cli::try_parse_from([
            "lf",
            "op",
            "branches",
            "prune",
            "--wave",
            "redesign",
            "--dry-run",
            "-y",
        ])
        .expect("parse");
        let Some(Commands::Op {
            op:
                OpsCommand::Branches {
                    cmd:
                        BranchesCommand::Prune {
                            filters: BranchFilterArgs { wave, .. },
                            dry_run,
                            yes,
                        },
                },
        }) = cli.command
        else {
            panic!("expected branches prune command");
        };

        assert_eq!(wave.as_deref(), Some("redesign"));
        assert!(dry_run);
        assert!(yes);
    }

    #[test]
    fn op_pr_accepts_model_override() {
        let cli = Cli::try_parse_from(["lf", "op", "pr", "-m", "codex"]).expect("parse");
        let Some(Commands::Op {
            op: OpsCommand::Pr { model, title, body },
        }) = cli.command
        else {
            panic!("expected pr command");
        };

        assert_eq!(model.as_deref(), Some("codex"));
        assert_eq!(title, None);
        assert_eq!(body, None);
    }

    #[test]
    fn top_level_model_reaches_op_command() {
        let cli = Cli::try_parse_from(["lf", "-m", "codex", "op", "pr"]).expect("parse");
        let Some(Commands::Op {
            op: OpsCommand::Pr { model, title, body },
        }) = cli.command
        else {
            panic!("expected pr command");
        };

        assert_eq!(cli.model.as_deref(), Some("codex"));
        assert_eq!(model, None);
        assert_eq!(title, None);
        assert_eq!(body, None);
    }
}