plannotator-tui 0.11.7

Annotate Markdown in the terminal - standalone, and as a Herdr plugin.
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
//! Command-line entry points: the interactive viewer and the headless tools.
//!
//! This is the only module that prints to stdout.

#![allow(clippy::print_stdout, reason = "the CLI's job is to print")]

use std::io::{IsTerminal as _, Write as _, stdout};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::{Duration, Instant};

use anyhow::{Context, Result};
use plannotator_tui_schema::{DocumentSource, Kind};
use ratatui::crossterm::event::{
    self, DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste,
    EnableFocusChange, EnableMouseCapture, KeyboardEnhancementFlags, PopKeyboardEnhancementFlags,
    PushKeyboardEnhancementFlags,
};
use ratatui::crossterm::execute;

use crate::app::App;
use crate::config::Config;
use crate::delivery::command::DeliverCommand;
use crate::delivery::{Caller, Clipboard, Delivery, Discard, HerdrAgent};
use crate::doc::Document;
use crate::gate::{self, Decision, GateError, ReviewArgs};
use crate::hc::agent::HcAgent;
use crate::herdr::context::HerdrEnv;
use crate::layout::DocLayout;
use crate::rex::agent::RexAgent;

pub(crate) const USAGE: &str = "usage:
  plannotator-tui <file.md | folder> [--gate] [--json] [--require-approval] [--result-file <path>]
  plannotator-tui --export <file.md>
  plannotator-tui --bench <file.md>
  plannotator-tui --blocks <file.md>
  plannotator-tui --annotate <file.md> <quote> <text> [comment|looks_good|delete] [--occurrence N]
  plannotator-tui --annotate-block <file.md> <block> <text> [comment|looks_good|delete]
  plannotator-tui --snapshot <file.md> [cols rows scroll] [select-quote] [menu]
  plannotator-tui review [--staged | --unstaged | --base REF | --commit SHA | PR | --pick] [DIR]
  plannotator-tui config
  plannotator-tui --version
  plannotator-tui herdr open [file.md | folder] [--placement overlay|split|popup] [--deliver-to <pane>]
                             [--gate] [--result-file <path>]
  plannotator-tui herdr last [--placement P] [--deliver-to <pane>] [--newest]
  plannotator-tui herdr terminal [--lines N] [--placement P] [--deliver-to <pane>] [--print]
  plannotator-tui herdr review [--staged | --unstaged | --base REF | --commit SHA | PR | --pick] [--placement P]
                               [--deliver-to <pane>]
  plannotator-tui herdr pane
  plannotator-tui rex open [file.md | folder] [--block <id>] [--session <id>] [--paste]
                           [--placement split|popup|tab] [--gate] [--result-file <path>]
  plannotator-tui rex last [--block <id>] [--session <id>] [--newest] [--paste] [--placement P]
  plannotator-tui rex terminal [--block <id>] [--session <id>] [--lines N] [--paste] [--placement P] [--print]
  plannotator-tui rex find [--block <id>] [--session <id>] [--lines N] [--paste] [--placement P]
  plannotator-tui rex review [--staged | --unstaged | --base REF | --commit SHA | PR | --pick] [--block <id>]
                             [--session <id>] [--paste] [--placement P]
  plannotator-tui rex install [--dry-run | --print]
  plannotator-tui rex pane (open <path> [--gate [--result-file <path>]] | last <last args>
                            | terminal --block <id> [--lines N] | review <scope> <repo>)
  plannotator-tui pi list [--json]
  plannotator-tui pi send --session <id or name> < feedback.md
  plannotator-tui pi install [--dry-run | --print]
  plannotator-tui hc open [file.md | folder] [--terminal <t>] [--placement overlay|split|popup]
                          [--gate] [--result-file <path>]
  plannotator-tui hc last [--terminal <t>] [--placement P] [--newest] [--session <transcript>]
  plannotator-tui hc review [--staged | --unstaged | --base REF | --commit SHA | PR | --pick] [--terminal <t>]
                            [--placement P]
  plannotator-tui hc pane (open <path> [--gate [--result-file <path>]] | last <last args> | review <scope> <repo>)
  plannotator-tui last [--host claude|codex|pi|omp|copilot|droid|hermes|opencode|cmd|agy] [--pid N] [--session <transcript>]
                       [--session-id <id>] [--stdin] [--print] [--pick N] [--newest]";

/// Width the document gets when nothing else is known: the gutter subtracted, and the rail
/// and its gap when `[ui] notes_rail` always shows it, then held to the reading column
/// (`[ui] doc_width`; zero for none), so the first frame finds the text already wrapped to it.
fn doc_width(cols: u16, ui: &crate::config::UiConfig) -> usize {
    let rail = if ui.notes_rail == crate::notes_rail::RailStart::Shown { 1 + 36 } else { 0 };
    let room = cols.saturating_sub(2 + rail).max(20);
    let cap = ui.doc_width;
    usize::from(if cap > 0 { room.min(cap.max(20)) } else { room })
}

fn open_file(path: &PathBuf) -> Result<DocumentSource> {
    let content = std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    Ok(DocumentSource::file(path.clone(), content))
}

/// A file opens on its own; a folder opens in folder mode on its first markdown file.
/// Interactive runs send to the Rex block, hc terminal or Herdr agent pane named by the
/// environment, else to the delivery command, else the clipboard; headless runs send nowhere.
pub(crate) fn delivery(interactive: bool) -> Box<dyn Delivery> {
    review_delivery(interactive, None)
}

/// [`delivery`] for a review of `path`, which a delivery command is told about. A launcher
/// names one agent for one review, so its target comes before a command set for every review.
fn review_delivery(interactive: bool, path: Option<&Path>) -> Box<dyn Delivery> {
    if !interactive {
        return Box::new(Discard);
    }
    agent_pane().or_else(|| deliver_command(path)).unwrap_or_else(|| Box::new(Clipboard))
}

/// `PLANNOTATOR_TUI_DELIVER_CMD`, else `[deliver] command`. A config that does not parse
/// is reported by `plannotator-tui config`, as for the theme.
fn deliver_command(path: Option<&Path>) -> Option<Box<dyn Delivery>> {
    let configured = Config::load().unwrap_or_default().deliver.command;
    let command = DeliverCommand::from_lookup(|k| std::env::var(k).ok(), configured.as_deref(), path)?;
    Some(Box::new(command))
}

/// A gated review sends to the same agent pane; without one its decision goes to the caller.
fn gate_delivery() -> Box<dyn Delivery> {
    agent_pane().unwrap_or_else(|| Box::new(Caller))
}

/// The Pi that started the review, or the Rex block, hc terminal or Herdr agent pane the
/// environment names, if any.
fn agent_pane() -> Option<Box<dyn Delivery>> {
    // Set only by Pi's `/plannotator-review`, for the review it runs in its own terminal. A
    // Pi that cannot be found refuses Send: the Rex block, hc terminal or Herdr pane in Pi's
    // environment is the one the review now runs in.
    match crate::pi::target::PiSession::from_lookup(|k| std::env::var(k).ok(), &crate::pi::root()) {
        Some(Ok(pi)) => return Some(Box::new(pi)),
        Some(Err(gone)) => return Some(Box::new(gone)),
        None => {}
    }
    if let Some(agent) = RexAgent::from_lookup(|k| std::env::var(k).ok()) {
        return Some(Box::new(agent));
    }
    if let Some(agent) = HcAgent::from_lookup(|k| std::env::var(k).ok()) {
        return Some(Box::new(agent));
    }
    let env = HerdrEnv::from_env();
    match env.delivery_target() {
        Some(target) if env.in_herdr => {
            let agent = target.agent.or_else(|| env.agent_in_pane(&target.pane));
            Some(Box::new(HerdrAgent::new(env.bin, target.pane, agent)))
        }
        _ => None,
    }
}

fn open_app(path: &PathBuf, width: usize, interactive: bool) -> Result<App> {
    open_review(path, width, review_delivery(interactive, Some(path)))
}

fn open_review(path: &PathBuf, width: usize, delivery: Box<dyn Delivery>) -> Result<App> {
    if path.is_dir() {
        App::open_folder(path, width, delivery)
    } else {
        App::open(open_file(path)?, width, delivery)
    }
}

/// The type word of `--annotate` and `--annotate-block`. `approve` is an older spelling of
/// `looks_good`, kept for callers that still pass it. Any other word is refused: a typo that
/// quietly became a comment would save the wrong kind of note.
fn parse_kind(word: &str) -> Result<Kind> {
    match word {
        "comment" => Ok(Kind::Comment),
        "looks_good" | "approve" => Ok(Kind::LooksGood),
        "delete" => Ok(Kind::Delete),
        other => anyhow::bail!("unknown type {other:?}: use comment, looks_good or delete\n{USAGE}"),
    }
}

/// What follows `--annotate <file> <quote> <text>`: an optional kind and `--occurrence N`
/// (1-based; the first occurrence when absent), in either order. `--annotate-block` reads
/// its kind the same way; a block is one place, so `occurrences` is false there and
/// `--occurrence` is an unknown flag.
fn annotate_options(rest: &[String], occurrences: bool) -> Result<(Kind, usize)> {
    let mut kind = None;
    let mut occurrence = 1;
    let mut items = rest.iter().map(String::as_str);
    while let Some(item) = items.next() {
        match item {
            "--occurrence" if occurrences => {
                occurrence = items
                    .next()
                    .and_then(|n| n.parse::<usize>().ok())
                    .filter(|n| *n >= 1)
                    .context("--occurrence takes a number from 1")?;
            }
            flag if flag.starts_with("--") => anyhow::bail!("unknown flag {flag}\n{USAGE}"),
            other if kind.is_none() => kind = Some(parse_kind(other)?),
            other => anyhow::bail!("unexpected argument {other:?}\n{USAGE}"),
        }
    }
    Ok((kind.unwrap_or(Kind::Comment), occurrence))
}

pub(crate) fn run(args: &[String]) -> Result<ExitCode> {
    if wants_decision(args) {
        return review_command(args);
    }
    tool(args).map(|()| ExitCode::SUCCESS)
}

/// A review with a decision flag, which may come before the path. Without one the
/// invocation means what it always has.
fn wants_decision(args: &[String]) -> bool {
    let decision_flag = |arg: &String| gate::FLAGS.contains(&arg.as_str());
    match args.first() {
        Some(first) if decision_flag(first) => true,
        Some(first)
            if first.starts_with('-')
                || matches!(first.as_str(), "config" | "herdr" | "rex" | "hc" | "pi" | "last" | "review") =>
        {
            false
        }
        Some(_) => args.iter().skip(1).any(decision_flag),
        None => false,
    }
}

fn tool(args: &[String]) -> Result<()> {
    let arg = |i: usize| args.get(i).map(String::as_str);
    let path = |i: usize| arg(i).map(|p| crate::workspace_paths::absolute(Path::new(p))).context(USAGE);
    match arg(0) {
        Some("--bench") => bench(&path(1)?),
        Some("--export") => {
            let target = path(1)?;
            let app = open_app(&target, 100, false)?;
            print!("{}", if target.is_dir() { app.folder_feedback()? } else { app.feedback() });
            Ok(())
        }
        Some("--blocks") => {
            let mut app = open_app(&path(1)?, 100, false)?;
            for line in app.describe_blocks() {
                println!("{line}");
            }
            Ok(())
        }
        Some("--annotate") => {
            let mut app = open_app(&path(1)?, 100, false)?;
            let quote = arg(2).context(USAGE)?;
            let body = arg(3).context(USAGE)?.to_owned();
            let (kind, occurrence) = annotate_options(args.get(4..).unwrap_or_default(), true)?;
            app.add_quote_annotation_at(quote, occurrence, kind, body)
        }
        Some("--annotate-block") => {
            let mut app = open_app(&path(1)?, 100, false)?;
            let block: usize = arg(2).and_then(|s| s.parse().ok()).context(USAGE)?;
            let body = arg(3).context(USAGE)?.to_owned();
            let (kind, _) = annotate_options(args.get(4..).unwrap_or_default(), false)?;
            app.add_block_annotation(block, kind, body)
        }
        Some("--snapshot") => {
            let cols: u16 = arg(2).and_then(|s| s.parse().ok()).unwrap_or(140);
            let rows: u16 = arg(3).and_then(|s| s.parse().ok()).unwrap_or(40);
            let scroll: i64 = arg(4).and_then(|s| s.parse().ok()).unwrap_or(0);
            // A trailing `menu` opens the Review menu; a quote may come before it.
            let menu = args.get(5..).is_some_and(|rest| rest.last().is_some_and(|last| last == "menu"));
            let select = arg(5).filter(|quote| *quote != "menu");
            snapshot(&path(1)?, cols, rows, scroll, select, menu)
        }
        Some("--version" | "-V") => {
            println!("plannotator-tui {}", env!("CARGO_PKG_VERSION"));
            Ok(())
        }
        Some("config") => show_config(),
        Some("herdr") => herdr_command(args.get(1..).unwrap_or_default()),
        Some("rex") => crate::rex::cli::run(args.get(1..).unwrap_or_default()),
        Some("hc") => crate::hc::cli::run(args.get(1..).unwrap_or_default()),
        Some("pi") => crate::pi::cli::run(args.get(1..).unwrap_or_default()),
        Some("last") => last_command(args.get(1..).unwrap_or_default()),
        Some("review") => code_review(args.get(1..).unwrap_or_default()),
        Some(flag) if flag.starts_with("--") => anyhow::bail!("unknown flag {flag}\n{USAGE}"),
        Some(_) => interactive(&path(0)?),
        None => anyhow::bail!(USAGE),
    }
}

/// `plannotator-tui review [--staged | --base REF | --commit SHA | PR] [DIR]`: a git diff, with notes
/// for the agent (`src/review/`).
fn code_review(args: &[String]) -> Result<()> {
    #[cfg(unix)]
    {
        crate::review::cli::run(args)
    }
    #[cfg(not(unix))]
    {
        let _ = args;
        anyhow::bail!("code review is not available on Windows yet")
    }
}

/// `plannotator-tui config`: where the file is and what is in effect.
fn show_config() -> Result<()> {
    let home = std::env::home_dir().unwrap_or_else(|| PathBuf::from("/"));
    let path = crate::config::config_path(|k| std::env::var(k).ok(), &home);
    let mut config = Config::load_from(&path)?;
    // `PLANNOTATOR_TUI_THEME` overrides the file, so the file's value is not the effective one.
    config.ui.theme = crate::theme::effective_setting(|key| std::env::var(key).ok(), config.ui.theme)?;
    // So does `PLANNOTATOR_TUI_DELIVER_CMD`.
    let env = |k: &str| std::env::var(k).ok();
    if let Some(command) = DeliverCommand::from_lookup(env, config.deliver.command.as_deref(), None) {
        config.deliver.command = Some(command.line().to_owned());
    }
    let state = if path.is_file() { "" } else { " (not present; defaults)" };
    println!("# {}{state}", path.display());
    print!("{}", config.to_toml()?);
    Ok(())
}

/// `plannotator-tui <file | folder> [--gate] [--json] [--require-approval] [--result-file PATH]`:
/// the review ends with one decision, printed on stdout and published to the result file
/// (decision 17). Under a strict flag every failure is a [`GateError`].
fn review_command(args: &[String]) -> Result<ExitCode> {
    let strict = gate::is_strict(args);
    gated_review(args).map_err(|err| if strict { GateError(err).into() } else { err })
}

fn gated_review(args: &[String]) -> Result<ExitCode> {
    let options = ReviewArgs::parse(args).map_err(|err| anyhow::anyhow!("{err:#}\n{USAGE}"))?;
    let path = crate::workspace_paths::absolute(&options.path);
    anyhow::ensure!(path.exists(), "{}: no such file or folder", path.display());
    let result_file = options.result_file.as_deref().map(crate::workspace_paths::absolute);
    if let Some(file) = &result_file {
        gate::check_result_file(file)?;
    }
    // The review draws on stdout. Redirected, nobody could see it and the gate would wait
    // forever; the result file is how a script captures the decision.
    anyhow::ensure!(
        stdout().is_terminal(),
        "stdout is not a terminal: the review is drawn there; read the decision from --result-file instead"
    );
    let mode = options.mode();
    let decision = run_review(|width| {
        let mut app = open_review(&path, width, gate_delivery())?;
        app.gate = mode;
        Ok(app)
    })?
    .unwrap_or(Decision::Dismissed);
    // Stdout first, as Plannotator does: if the file cannot be published, the decision has
    // still reached the caller once.
    let mut out = stdout().lock();
    if options.json {
        let line = if options.strict() { decision.strict_json() } else { decision.json(&path) };
        writeln!(out, "{line}")?;
    } else if let Some(text) = decision.plain(&gate::context_line(&path, path.is_dir())) {
        writeln!(out, "{text}")?;
    }
    out.flush()?;
    if let Some(file) = &result_file {
        gate::publish(file, &decision.strict_json())?;
    }
    Ok(ExitCode::from(decision.exit_code(options.require_approval)))
}

/// `plannotator-tui herdr open [PATH] [--placement P] [--deliver-to PANE] [--gate]
/// [--result-file PATH]`; `herdr last` takes `--newest` on top, which `open` has nothing to
/// skip. A gated open with a result file fails as a [`GateError`], like the direct gate.
fn herdr_command(args: &[String]) -> Result<()> {
    let strict = args.first().is_some_and(|sub| sub == "open") && gate::is_strict(args);
    herdr_launch(args).map_err(|err| if strict { GateError(err).into() } else { err })
}

fn herdr_launch(args: &[String]) -> Result<()> {
    use crate::herdr::launch::{OpenArgs, agent_get, agent_identity, plan, plan_last, process_info, run};
    let sub = args.first().map(String::as_str);
    if sub == Some("pane") {
        return herdr_pane();
    }
    if sub == Some("terminal") {
        return herdr_terminal(args.get(1..).unwrap_or_default());
    }
    if sub == Some("review") {
        return herdr_review(args.get(1..).unwrap_or_default());
    }
    if !matches!(sub, Some("open" | "last")) {
        anyhow::bail!(USAGE);
    }
    let mut open = OpenArgs::default();
    let mut rest = args.get(1..).unwrap_or_default().iter();
    while let Some(arg) = rest.next() {
        match arg.as_str() {
            "--placement" => {
                let value = rest.next().context("--placement needs a value")?;
                open.placement = Some(value.parse()?);
            }
            "--deliver-to" => {
                open.deliver_to = Some(rest.next().context("--deliver-to needs a value")?.clone());
            }
            "--newest" if sub == Some("last") => open.newest = true,
            "--newest" => {
                anyhow::bail!("--newest is only for `herdr last`; `herdr open` has no picker to skip")
            }
            "--gate" if sub == Some("open") => open.gate = true,
            "--result-file" if sub == Some("open") => {
                let value = rest.next().filter(|v| !v.starts_with("--"));
                let value = value.context("missing value for --result-file")?;
                open.result_file = Some(crate::workspace_paths::absolute(Path::new(value)));
            }
            "--gate" | "--result-file" => anyhow::bail!("{arg} is only for `herdr open`"),
            flag if flag.starts_with("--") => anyhow::bail!("unknown flag {flag}\n{USAGE}"),
            path if open.path.is_none() => open.path = Some(PathBuf::from(path)),
            extra => anyhow::bail!("unexpected argument {extra:?}\n{USAGE}"),
        }
    }
    if let Some(file) = &open.result_file {
        anyhow::ensure!(open.gate, "--result-file requires --gate");
        // The pane publishes when the review ends; a name that is already taken would only
        // fail then, after the review.
        gate::check_result_file(file)?;
    }
    let env = HerdrEnv::from_env();
    let config = Config::load()?;
    let cwd = std::env::current_dir().context("current directory")?;
    let launch = if sub == Some("last") {
        let probe = plan(&env, &config, OpenArgs { path: None, ..open.clone() }, &cwd)?;
        let pane = probe.deliver.as_ref().map(|t| t.pane.clone()).or(probe.target_pane);
        let pane = pane.context("no agent pane to read: not focused on one and no --deliver-to")?;
        let agent = agent_get(&env, &pane);
        let process = match agent.as_deref().and_then(agent_identity) {
            Some(_) => None,
            None => Some(process_info(&env, &pane)?),
        };
        plan_last(&env, &config, open, &cwd, process.as_deref(), agent.as_deref())?
    } else {
        plan(&env, &config, open, &cwd)?
    };
    run(&env, &launch)
}

/// `plannotator-tui herdr terminal [--lines N] [--placement P] [--deliver-to PANE] [--print]`:
/// review the focused pane's recent output. The read happens here first so a pane with
/// nothing to show fails before a review pane opens; `--print` stops after it.
fn herdr_terminal(args: &[String]) -> Result<()> {
    use crate::herdr::launch::{OpenArgs, TerminalRead, plan_terminal, run};
    use crate::herdr::terminal;
    let mut open = OpenArgs::default();
    let mut lines = crate::terminal::DEFAULT_LINES;
    let mut print = false;
    let mut rest = args.iter();
    while let Some(arg) = rest.next() {
        match arg.as_str() {
            "--lines" => lines = lines_value(rest.next())?,
            "--placement" => {
                let value = rest.next().context("--placement needs a value")?;
                open.placement = Some(value.parse()?);
            }
            "--deliver-to" => {
                open.deliver_to = Some(rest.next().context("--deliver-to needs a value")?.clone());
            }
            "--print" => print = true,
            other => anyhow::bail!("unexpected argument {other:?}\n{USAGE}"),
        }
    }
    let env = HerdrEnv::from_env();
    let pane = env.reviewed_pane().context("no focused pane to read")?;
    let text = terminal::read(&env, &pane, lines)?;
    if print {
        print!("{}", crate::terminal::document(&text));
        return Ok(());
    }
    let config = Config::load()?;
    let cwd = std::env::current_dir().context("current directory")?;
    let launch = plan_terminal(&env, &config, open, &cwd, TerminalRead { pane, lines })?;
    run(&env, &launch)
}

/// `plannotator-tui herdr review …`: a code review of the focused pane's repository.
fn herdr_review(args: &[String]) -> Result<()> {
    #[cfg(unix)]
    {
        crate::review::herdr::launch(args)
    }
    #[cfg(not(unix))]
    {
        let _ = args;
        anyhow::bail!("code review is not available on Windows yet")
    }
}

/// The pane side of a code-review launcher (`herdr review`, `rex review`, `hc review`).
pub(crate) fn review_pane(scope: &str, repo: Option<&Path>) -> Result<()> {
    #[cfg(unix)]
    {
        crate::review::scope::pane(scope, repo)
    }
    #[cfg(not(unix))]
    {
        let _ = (scope, repo);
        anyhow::bail!("code review is not available on Windows yet")
    }
}

/// The pane entrypoint: Herdr runs this in the opened pane; the environment says what to show.
fn herdr_pane() -> Result<()> {
    let env = HerdrEnv::from_env();
    let result = if let Some(pane) = env.terminal_pane.clone() {
        crate::herdr::terminal::run(&env, &pane)
    } else if env.has_message_source() {
        crate::last::run(&crate::last::LastOptions {
            host: env.host.clone(),
            pid: env.message_pid,
            session: env.session.clone(),
            session_id: env.session_id.clone(),
            pick: picker_count(),
            newest: env.newest,
            ..crate::last::LastOptions::default()
        })
    } else if let Some(scope) = &env.review {
        review_pane(scope, env.repo.as_deref())
    } else {
        let path = env.file.clone().unwrap_or(std::env::current_dir().context("current directory")?);
        if env.gate { gated_pane(&path, env.result_file.as_deref()) } else { interactive(&path) }
    };
    // The pane closes when we exit; an error that flashes by is an error nobody can read.
    if let Err(err) = &result {
        wait_on_error(err);
    }
    result
}

/// `--lines`: a count from 1.
pub(crate) fn lines_value(value: Option<&String>) -> Result<u32> {
    value.and_then(|n| n.parse::<u32>().ok()).filter(|n| *n >= 1).context("--lines takes a number from 1")
}

/// Show `err` in a pane that is about to close, until Enter.
pub(crate) fn wait_on_error(err: &anyhow::Error) {
    #[allow(clippy::print_stderr, reason = "the pane is the only place this can be read")]
    {
        eprintln!("plannotator-tui: {err:#}\n\npress enter to close");
    }
    let mut line = String::new();
    let _ = std::io::stdin().read_line(&mut line);
}

/// `[last] pick`. A config that fails to parse gives the default rather than failing the lookup.
fn picker_count() -> usize {
    Config::load().unwrap_or_default().last.pick
}

/// `plannotator-tui last [--host H] [--pid N] [--session PATH] [--stdin] [--print] [--pick N]
/// [--newest]`.
pub(crate) fn last_command(args: &[String]) -> Result<()> {
    crate::last::run(&last_options(args, picker_count())?)
}

/// `last`'s arguments, offering `pick` messages unless `--pick` says otherwise.
fn last_options(args: &[String], pick: usize) -> Result<crate::last::LastOptions> {
    let mut options = crate::last::LastOptions { pick, ..crate::last::LastOptions::default() };
    let mut rest = args.iter();
    while let Some(arg) = rest.next() {
        match arg.as_str() {
            "--host" => options.host = Some(rest.next().context("--host needs a value")?.clone()),
            "--pid" => options.pid = Some(rest.next().context("--pid needs a value")?.parse()?),
            "--session" => {
                options.session = Some(PathBuf::from(rest.next().context("--session needs a value")?));
            }
            "--session-id" => {
                options.session_id = Some(rest.next().context("--session-id needs a value")?.clone());
            }
            "--stdin" => options.stdin = true,
            "--print" => options.print = true,
            "--pick" => options.pick = rest.next().context("--pick needs a value")?.parse()?,
            "--newest" => options.newest = true,
            other => anyhow::bail!("unknown argument {other}\n{USAGE}"),
        }
    }
    Ok(options)
}

/// A gated review in a Herdr, Rex or hc pane: the agent hears the decision through delivery,
/// and the result file, when asked for, records it. The pane has no caller reading its stdout.
pub(crate) fn gated_pane(path: &PathBuf, result_file: Option<&Path>) -> Result<()> {
    if let Some(file) = result_file {
        gate::check_result_file(file)?;
    }
    let decision = run_review(|width| {
        let mut app = open_review(path, width, gate_delivery())?;
        app.gate = gate::Gate::Approve;
        Ok(app)
    })?
    .unwrap_or(Decision::Dismissed);
    match result_file {
        Some(file) => gate::publish(file, &decision.strict_json()),
        None => Ok(()),
    }
}

pub(crate) fn interactive(path: &PathBuf) -> Result<()> {
    run_ui(|width| open_app(path, width, true))
}

/// Own the terminal for one app: `build` gets the document width the screen allows.
pub(crate) fn run_ui(build: impl FnOnce(usize) -> Result<App>) -> Result<()> {
    run_review(build).map(drop)
}

/// `run_ui`, returning how a gated review ended; `None` for an ordinary one.
fn run_review(build: impl FnOnce(usize) -> Result<App>) -> Result<Option<Decision>> {
    with_terminal(|terminal, session| {
        let width = doc_width(terminal.size().map_or(120, |s| s.width), &session.config.ui);
        let mut app = build(width)?;
        app.shift_enter = session.shift_enter;
        app.keys = session.config.keys;
        app.ui = session.config.ui;
        app.start_notes_rail();
        app.editor = crate::editor::from_env(|key| std::env::var(key).ok());
        if let Some(notice) = session.config_notice {
            app.add_notice(notice);
        }
        event_loop(terminal, app)
    })
}

/// What a screen learns while the terminal is being taken over.
pub(crate) struct Session {
    pub(crate) config: Config,
    /// The config file could not be loaded and the defaults are in force: the line that
    /// says so, for the screen's footer.
    pub(crate) config_notice: Option<String>,
    /// Whether the terminal reports Shift+Enter distinctly (kitty keyboard protocol).
    pub(crate) shift_enter: bool,
}

/// Own the terminal for `run`: palette, alternate screen, mouse, paste and keyboard modes
/// on the way in, all of it undone on the way out, whatever `run` returns. Document and
/// code reviews both start here.
pub(crate) fn with_terminal<T>(
    run: impl FnOnce(&mut ratatui::DefaultTerminal, Session) -> Result<T>,
) -> Result<T> {
    // Settle the palette before the screen is ours: the background-colour query talks to
    // the terminal directly, and it must not race the alternate screen or the event loop.
    // A config that fails to parse never kept the plain TUI from starting; it still does
    // not, but the screen says so in its footer. `plannotator-tui config` reports it too.
    let (config, config_notice) = Config::load_for_screen(&Config::path());
    crate::theme::install(
        crate::theme::resolve(|key| std::env::var(key).ok(), config.ui.theme, crate::theme::detect)?,
        &config.colors,
    );
    let mut terminal = ratatui::init();
    // From here a code review's git runs in the background, off the terminal.
    plannotator_tui_review::children::screen_taken(true);
    #[cfg(unix)]
    crate::hangup::watch();
    // ratatui's hook leaves the alternate screen and raw mode on a panic. The modes this app
    // turns on go first, or the shell is left with mouse, focus and paste reports; the hook
    // is in place before any of them is on. Whether the keyboard flags were pushed is only
    // known once the terminal answers below.
    let pushed = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let flags = std::sync::Arc::clone(&pushed);
    std::panic::set_hook(release_first(
        move || release_input(flags.load(std::sync::atomic::Ordering::Acquire)),
        std::panic::take_hook(),
    ));
    crate::layout::keep_hook_off_layout_threads();
    execute!(stdout(), EnableMouseCapture)?;
    // Shift+Enter is only distinguishable from Enter where the kitty keyboard protocol
    // holds end to end (terminal, and any multiplexer in between). Ask for it; the flag
    // gates the compose box's hint so it never advertises a key that cannot arrive.
    let shift_enter = ratatui::crossterm::terminal::supports_keyboard_enhancement().unwrap_or(false);
    pushed.store(shift_enter, std::sync::atomic::Ordering::Release);
    claim_input(shift_enter);
    let result = run(&mut terminal, Session { config, config_notice, shift_enter });
    release_input(shift_enter);
    ratatui::restore();
    plannotator_tui_review::children::screen_taken(false);
    result
}

/// Bracketed paste and, where the terminal has it, the kitty keyboard protocol. Mouse
/// capture is the caller's: the first claim turns it on before the keyboard query.
fn claim_input(shift_enter: bool) {
    // Focus changes tell the code review the pointer left, so a drag whose release went
    // elsewhere ends; the document screen ignores them.
    let _ = execute!(stdout(), EnableBracketedPaste, EnableFocusChange);
    if shift_enter {
        let _ = execute!(
            stdout(),
            PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
        );
    }
}

/// Undo `claim_input` and mouse capture, in reverse order.
pub(crate) fn release_input(shift_enter: bool) {
    if shift_enter {
        let _ = execute!(stdout(), PopKeyboardEnhancementFlags);
    }
    let _ = execute!(stdout(), DisableFocusChange, DisableBracketedPaste);
    let _ = execute!(stdout(), DisableMouseCapture);
}

type PanicHook = Box<dyn Fn(&std::panic::PanicHookInfo<'_>) + Send + Sync + 'static>;

/// A panic hook that runs `release` and then `previous`.
fn release_first(release: impl Fn() + Send + Sync + 'static, previous: PanicHook) -> PanicHook {
    Box::new(move |info| {
        release();
        previous(info);
    })
}

/// Give the terminal to the editor until it exits, then take the screen back. The outer
/// error is the terminal failing to come back, which ends the app; the inner one is the
/// editor failing to start, which the app reports and survives.
fn run_editor(
    terminal: &mut ratatui::DefaultTerminal,
    shift_enter: bool,
    request: &crate::editor::EditorRequest,
) -> Result<std::io::Result<std::process::ExitStatus>> {
    use ratatui::crossterm::{cursor, terminal as term};
    release_input(shift_enter);
    ratatui::restore();
    let _ = execute!(stdout(), cursor::Show);
    let outcome = match crate::editor::command(request) {
        Some(mut command) => command.status(),
        None => Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "the editor command is empty")),
    };
    term::enable_raw_mode().context("taking the terminal back from the editor")?;
    execute!(stdout(), term::EnterAlternateScreen, EnableMouseCapture)
        .context("taking the terminal back from the editor")?;
    claim_input(shift_enter);
    // The editor drew over the screen ratatui remembers; draw the next frame in full.
    terminal.clear()?;
    Ok(outcome)
}

fn event_loop(terminal: &mut ratatui::DefaultTerminal, mut app: App) -> Result<Option<Decision>> {
    app.clipboard = true;
    app.start_pi_link();
    let mut dirty = true;
    while !app.quit {
        if let Some(request) = app.take_editor_request() {
            let outcome = run_editor(terminal, app.shift_enter, &request)?;
            app.editor_returned(&request, outcome);
            dirty = true;
        }
        dirty |= app.poll_background();
        if dirty {
            let started = Instant::now();
            terminal.draw(|frame| app.draw(frame))?;
            app.record_frame(started.elapsed().as_secs_f64() * 1000.0);
            dirty = false;
        }
        // A selection held past the text's edge scrolls on the tick.
        let wait = if app.background_pending() {
            Duration::from_millis(25)
        } else if app.held_at_edge() {
            crate::ui::drag::STEP
        } else {
            Duration::from_millis(250)
        };
        if event::poll(wait)? {
            app.handle_event(&event::read()?)?;
            dirty = true;
            // Coalesce bursts (wheel, drag) into one redraw.
            // Keys typed after `open-in-editor` belong to the editor, not to this loop.
            while !app.wants_editor() && event::poll(Duration::ZERO)? {
                app.handle_event(&event::read()?)?;
            }
        }
    }
    Ok(app.take_decision())
}

/// Headless timing of the expensive paths: parse, per-block render + align, reflow, and search.
fn bench(path: &PathBuf) -> Result<()> {
    let source = open_file(path)?;
    let bytes = source.content.len();
    let t = Instant::now();
    let doc = Document::parse(source.content);
    let parse_ms = t.elapsed().as_secs_f64() * 1000.0;

    let t = Instant::now();
    let mut lazy = DocLayout::start(&doc, 100);
    let start_ms = t.elapsed().as_secs_f64() * 1000.0;
    let (first_blocks, first_rows) = (lazy.blocks.len(), lazy.total_rows);
    lazy.finish();
    let finish_ms = t.elapsed().as_secs_f64() * 1000.0;

    let t = Instant::now();
    let mut layout = DocLayout::build(&doc, 100);
    let build_ms = t.elapsed().as_secs_f64() * 1000.0;

    let reflow: Vec<String> = [60usize, 140, 80, 120]
        .into_iter()
        .map(|width| {
            let t = Instant::now();
            layout.reflow(width);
            format!("{width}→{:.1}ms", t.elapsed().as_secs_f64() * 1000.0)
        })
        .collect();

    let t = Instant::now();
    let hits = (0..layout.total_rows).step_by(7).filter(|&row| layout.block_at_row(row).is_some()).count();
    let lookup_us = t.elapsed().as_secs_f64() * 1e6 / (layout.total_rows / 7).max(1) as f64;

    let t = Instant::now();
    let index = crate::doc_search::Index::of(&layout);
    let index_ms = t.elapsed().as_secs_f64() * 1000.0;
    // What each keystroke of a typed query costs: one search of the whole text.
    let searches: Vec<String> = ["e", "th", "the", "plugin", "Plugin", "no such text anywhere"]
        .into_iter()
        .map(|query| {
            let t = Instant::now();
            let found = index.find(query).len();
            format!("{query:?} {found}→{:.1}ms", t.elapsed().as_secs_f64() * 1000.0)
        })
        .collect();

    let cells: usize = layout.blocks.iter().flat_map(|b| b.rows.iter()).map(|r| r.cells.len()).sum();
    let mapped: usize =
        layout.blocks.iter().flat_map(|b| b.rows.iter()).flat_map(|r| r.cells.iter()).flatten().count();

    println!("{}: {bytes} bytes, {} blocks", path.display(), doc.blocks.len());
    println!("parse+split          {parse_ms:8.1} ms");
    println!("first screens        {start_ms:8.1} ms  ({first_blocks} blocks, {first_rows} rows)");
    println!("  rest in background {finish_ms:8.1} ms  (until every block is laid out)");
    println!("render+align+wrap    {build_ms:8.1} ms  ({} rows)", layout.total_rows);
    println!("reflow               {}", reflow.join("  "));
    println!("row lookup           {lookup_us:8.3} µs avg ({hits} hits)");
    println!("search index         {index_ms:8.1} ms");
    println!("search               {}", searches.join("  "));
    println!("cells mapped         {mapped}/{cells} ({:.1}%)", mapped as f64 * 100.0 / cells.max(1) as f64);
    Ok(())
}

/// Draw one frame into an in-memory backend and print it as text, followed by a mark map:
/// `#` comment, `+` looks good, `-` delete, `%` selected or highlighted.
fn snapshot(
    path: &PathBuf,
    cols: u16,
    rows: u16,
    scroll: i64,
    select: Option<&str>,
    menu: bool,
) -> Result<()> {
    use ratatui::backend::TestBackend;
    use ratatui::style::Modifier;
    let mut terminal = ratatui::Terminal::new(TestBackend::new(cols, rows))?;
    let mut app = open_app(path, doc_width(cols, &crate::config::UiConfig::default()), false)?;
    terminal.draw(|frame| app.draw(frame))?;
    app.scroll_for_snapshot(scroll);
    if let Some(quote) = select {
        app.select_quote_for_snapshot(quote)?;
    }
    if menu {
        app.open_review_menu();
    }
    terminal.draw(|frame| app.draw(frame))?;
    let buffer = terminal.backend().buffer();
    let mut marks = Vec::new();
    for y in 0..buffer.area.height {
        let mut line = String::new();
        let mut mark = String::new();
        for x in 0..buffer.area.width {
            let Some(cell) = buffer.cell((x, y)) else { continue };
            line.push_str(cell.symbol());
            let style = cell.style();
            mark.push(if style.add_modifier.contains(Modifier::REVERSED) {
                '%'
            } else if style.add_modifier.contains(Modifier::CROSSED_OUT) {
                '-'
            } else if style.bg == Some(crate::theme::palette().approve_bg) {
                '+'
            } else if style.bg == Some(crate::theme::palette().comment_bg) {
                '#'
            } else {
                ' '
            });
        }
        println!("{}", line.trim_end());
        marks.push(mark);
    }
    if marks.iter().any(|m| !m.trim().is_empty()) {
        println!("--- marks ---");
        for m in marks {
            println!("{}", m.trim_end());
        }
    }
    Ok(())
}

#[cfg(test)]
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
mod tests {
    use super::{doc_width, last_options};
    use crate::config::UiConfig;
    use crate::notes_rail::RailStart;

    fn args(list: &[&str]) -> Vec<String> {
        list.iter().map(|&arg| arg.to_owned()).collect()
    }

    #[test]
    fn last_offers_the_configured_count_and_pick_overrides_it() {
        assert_eq!(last_options(&args(&["--newest"]), 60).expect("parses").pick, 60);
        assert_eq!(last_options(&args(&["--pick", "5"]), 60).expect("parses").pick, 5);
    }

    #[test]
    fn a_panic_turns_the_input_modes_off_before_the_hook_that_gives_the_screen_back() {
        use std::sync::{Arc, Mutex};
        use std::thread;
        // Only this thread's panic is recorded; any other test's goes to the hook as before.
        let here = thread::current().id();
        let order = Arc::new(Mutex::new(Vec::new()));
        let original: Arc<super::PanicHook> = Arc::new(std::panic::take_hook());
        let (released, given_back, others) = (Arc::clone(&order), Arc::clone(&order), Arc::clone(&original));
        let previous: super::PanicHook = Box::new(move |info| {
            if thread::current().id() == here {
                given_back.lock().expect("order").push("screen");
            } else {
                others(info);
            }
        });
        let release = move || {
            if thread::current().id() == here {
                released.lock().expect("order").push("input modes");
            }
        };
        std::panic::set_hook(super::release_first(release, previous));
        #[allow(clippy::panic, reason = "the hook runs on a panic")]
        let outcome = std::panic::catch_unwind(|| std::panic::panic_any("on purpose"));
        drop(std::panic::take_hook());
        std::panic::set_hook(Box::new(move |info| original(info)));
        assert!(outcome.is_err());
        assert_eq!(*order.lock().expect("order"), ["input modes", "screen"]);
    }

    #[test]
    fn the_first_frames_width_leaves_out_a_rail_unless_it_always_shows() {
        let fill = UiConfig { doc_width: 0, ..UiConfig::default() };
        assert_eq!(doc_width(120, &UiConfig { notes_rail: RailStart::Shown, ..fill }), 120 - 2 - 1 - 36);
        assert_eq!(doc_width(120, &UiConfig { notes_rail: RailStart::Hidden, ..fill }), 118);
        assert_eq!(doc_width(120, &fill), 118, "when-notes: the rail comes with the first note");
        assert_eq!(doc_width(120, &UiConfig::default()), 80);
    }
}