ah-cli 0.3.0

Agent History Search - cross-agent session full-text search CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
use std::path::PathBuf;
use std::process::{Command, Stdio};

use crate::agents::common::canonical_home;
use crate::cli::{
    Field, FilterArgs, InteractiveArgs, ListProjectsArgs, ListProjectsResolvedArgs, MemoryArgs,
    MemoryField, MemoryResolvedArgs, ProjectField, ResumeArgs, SearchArgs, ShowArgs, SortOrder,
};
use crate::memory;
use crate::output::{self, compute_column_widths, format_columns, sanitize_for_display};
use crate::pipeline;
use crate::projects;
use crate::remote;
use crate::resolver::{self, shell_quote};

const PREVIEW_SELECTORS: &[&str] = &["fzf", "sk"];

/// Print selected session fields as TSV. Delegates to
/// `show::emit_session_meta_tsv` so the post-selection output stays
/// byte-identical to `ah show -o ...` (no truncation, query/search-mode
/// threading, running/pid enrichment, TSV escaping). Validates `-q` early
/// when `matched` is requested so a malformed regex surfaces an error
/// instead of silently producing an empty `matched` column — matches the
/// non-interactive `show.rs::run` behaviour.
fn print_session_fields(
    path: &str,
    fields: &[Field],
    query: &str,
    search_mode: crate::cli::SearchMode,
) -> Result<(), String> {
    if !query.is_empty() && fields.contains(&Field::Matched) {
        match search_mode {
            crate::cli::SearchMode::All => regex::bytes::Regex::new(&format!("(?iu){}", query))
                .map(drop)
                .map_err(|e| format!("Invalid regex '{}': {}", query, e))?,
            crate::cli::SearchMode::Prompt => regex::Regex::new(&format!("(?i){}", query))
                .map(drop)
                .map_err(|e| format!("Invalid regex '{}': {}", query, e))?,
        }
    }
    let pb = std::path::PathBuf::from(path);
    let home = canonical_home();
    crate::show::emit_session_meta_tsv(&pb, &home, fields, query, search_mode)
}

/// Reverse shell_quote: strip surrounding single quotes and unescape.
fn strip_shell_quote(s: &str) -> String {
    if s.len() >= 2 && s.starts_with('\'') && s.ends_with('\'') {
        s[1..s.len() - 1].replace("'\"'\"'", "'")
    } else {
        s.to_string()
    }
}

fn resolve_selector(ia: &InteractiveArgs) -> String {
    ia.selector
        .clone()
        .or_else(|| std::env::var("AH_SELECTOR").ok().filter(|s| !s.is_empty()))
        .unwrap_or_else(|| "fzf".to_string())
}

fn use_preview(ia: &InteractiveArgs, selector: &str) -> bool {
    let selector_bin = selector.rsplit('/').next().unwrap_or(selector);
    !ia.no_preview && PREVIEW_SELECTORS.contains(&selector_bin)
}

/// Detect the fzf version so the preview-search binds can be gated on the
/// features they need (see `push_preview_search_binds`).
///
/// Stock fzf prints `MAJOR.MINOR.PATCH (build info)` to stdout, but
/// distro/packaged builds may prepend `fzf ` or include other prefixes.
/// Scan the entire output for the first `MAJOR.MINOR` numeric substring
/// rather than relying on the first whitespace token, so we don't silently
/// disable the feature on supported fzf with non-standard version banners.
fn fzf_version(selector: &str) -> Option<(u32, u32)> {
    let output = std::process::Command::new(selector)
        .arg("--version")
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let stdout = String::from_utf8_lossy(&output.stdout);
    static VERSION_RE: std::sync::LazyLock<regex::Regex> =
        std::sync::LazyLock::new(|| regex::Regex::new(r"(\d+)\.(\d+)").unwrap());
    let caps = VERSION_RE.captures(&stdout)?;
    Some((caps[1].parse().unwrap_or(0), caps[2].parse().unwrap_or(0)))
}

/// Build LTSV-format input for selector (legacy mode). The hidden key
/// (column 1) is round-tripped through `unescape_tsv` after fzf selection,
/// so it gets the **lossless** encoder; visible display values are never
/// decoded again, so they get the **simple** encoder so backslashes appear
/// verbatim in the picker (a project field like `C:\Users\foo` shows
/// without doubled backslashes).
fn build_ltsv_input<KeyEsc, ValEsc>(
    key_label: &str,
    keys: &[String],
    rows: &[Vec<String>],
    field_names: &[String],
    key_escape: KeyEsc,
    val_escape: ValEsc,
) -> String
where
    KeyEsc: Fn(&str) -> String,
    ValEsc: Fn(&str) -> String,
{
    let mut input = String::new();
    for (i, key) in keys.iter().enumerate() {
        input.push_str(&format!("{}:{}", key_label, key_escape(key)));
        for (j, val) in rows[i].iter().enumerate() {
            input.push('\t');
            input.push_str(&format!("{}:{}", field_names[j], val_escape(val)));
        }
        input.push('\n');
    }
    input
}

pub fn run_log(args: &SearchArgs, ia: &InteractiveArgs, filter: &FilterArgs) -> Result<(), String> {
    let ltsv = args.ltsv();
    let selector = resolve_selector(ia);
    let preview = use_preview(ia, &selector);

    let default_display = || {
        vec![
            Field::Agent,
            Field::Project,
            Field::ModifiedAt,
            Field::Title,
        ]
    };

    let output_fields = match args.common.parse_fields()? {
        Some(fields) if fields.is_empty() => {
            return Err(
                "-o/--fields requires at least one field name (got empty list)".to_string(),
            );
        }
        Some(fields) => Some(crate::cli::hoist_path_first(fields)),
        None => None,
    };

    // Display columns come from --interactive-display only. We deliberately
    // do NOT fall back to `-o` here: doing so would force the candidate
    // pipeline to resolve heavy fields (`transcript`, `messages`, `matched`,
    // …) for every session before fzf even opens, and `matched` in particular
    // would be silently empty (the picker pipeline uses
    // `default_with_title_limit(30)` rather than the query-aware opts), which
    // drops every candidate. Keep the picker showing the cheap default
    // columns and let the user opt in via --interactive-display.
    // log -i picker uses default_with_title_limit(30) (not query-aware), so
    // matched would always be empty — disallow.
    let display_fields = ia
        .parse_display_fields(false)?
        .unwrap_or_else(default_display);

    let sort_field = args.sort_field()?;
    let mut resolve_fields = vec![Field::Path, Field::Id];
    for f in &display_fields {
        if *f != Field::Path && *f != Field::Id {
            resolve_fields.push(*f);
        }
    }
    // Don't pre-resolve `output_fields` here: doing so would force every
    // candidate session to be parsed for heavy fields like `transcript` /
    // `messages` / `responses` *before* fzf even opens. The selected session
    // is re-resolved with the full output field set in print_session_fields.
    let _ = &output_fields;
    if !resolve_fields.contains(&sort_field) {
        resolve_fields.push(sort_field);
    }

    let query = filter.query.clone().unwrap_or_default();
    let result = pipeline::run_pipeline(&pipeline::PipelineParams {
        resolve_fields: resolve_fields.clone(),
        resolve_opts: resolver::ResolveOpts::default_with_title_limit(30),
        filters: filter.to_filters(),
        since: filter.since_time()?,
        until: filter.until_time()?,
        query,
        search_mode: filter.search_mode(),
        sort_field,
        sort_order: SortOrder::Desc,
        collect_limit: filter.limit,
        running: filter.running,
        require_resume_cmd: false,
    })?;
    let mut sessions = result.sessions;

    remote::merge_into_sessions(
        &mut sessions,
        filter,
        &resolve_fields,
        sort_field,
        SortOrder::Desc,
    )?;

    if sessions.is_empty() {
        return Err("No sessions found.".to_string());
    }

    // Extract keys (shell-quoted paths) and display rows
    let visible_fields: Vec<&Field> = display_fields
        .iter()
        .filter(|f| **f != Field::Path)
        .collect();
    let keys: Vec<String> = sessions
        .iter()
        .map(|s| shell_quote(s.fields.get(&Field::Path).map(|v| v.as_str()).unwrap_or("")))
        .collect();
    let rows: Vec<Vec<String>> = sessions
        .iter()
        .map(|s| {
            visible_fields
                .iter()
                .map(|f| sanitize_for_display(s.fields.get(f).map(|v| v.as_str()).unwrap_or("")))
                .collect()
        })
        .collect();

    let (input, with_nth) = if ltsv {
        let field_names: Vec<String> = visible_fields
            .iter()
            .map(|f| f.name().to_string())
            .collect();
        let mut inp = String::new();
        for (i, key) in keys.iter().enumerate() {
            // The `path:` value is round-tripped through `unescape_tsv` after
            // fzf selection, so encode losslessly. Display values use the
            // simple escape since they're never decoded.
            inp.push_str(&format!("path:{}", output::escape_tsv_lossless(key)));
            inp.push('\t');
            let marker = if sessions[i]
                .fields
                .get(&Field::Running)
                .is_some_and(|v| v == "true")
            {
                "\x1b[32mR\x1b[0m "
            } else {
                "  "
            };
            inp.push_str(marker);
            for (j, val) in rows[i].iter().enumerate() {
                inp.push_str(&format!("{}:{}", field_names[j], output::escape_tsv(val)));
                if j < rows[i].len() - 1 {
                    inp.push('\t');
                }
            }
            inp.push('\n');
        }
        let count = visible_fields.len();
        (inp, format!("--with-nth=2..{}", count + 2))
    } else {
        let widths = compute_column_widths(&rows);
        let colors: Vec<&str> = visible_fields
            .iter()
            .map(|f| output::field_color(f))
            .collect();
        let mut inp = String::new();
        for (i, key) in keys.iter().enumerate() {
            inp.push_str(key);
            inp.push('\t');
            let marker = if sessions[i]
                .fields
                .get(&Field::Running)
                .is_some_and(|v| v == "true")
            {
                "\x1b[32mR\x1b[0m "
            } else {
                "  "
            };
            inp.push_str(marker);
            inp.push_str(&format_columns(&rows[i], &widths, &colors));
            inp.push('\n');
        }
        (inp, "--with-nth=2..".to_string())
    };

    let mut selector_args: Vec<String> = vec![
        "--ansi".to_string(),
        "--no-sort".to_string(),
        "--delimiter=\t".to_string(),
        with_nth,
    ];

    if preview {
        let exe = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("ah"));
        let exe_quoted = shell_quote(&exe.to_string_lossy());
        if ltsv {
            // The key column is already shell-quoted, so use fzf raw mode.
            selector_args.push(format!(
                "--preview=p={{r1}}; p=${{p#path:}}; p=$(printf '%b' \"$p\"); {} show --color \"$p\"",
                exe_quoted
            ));
        } else {
            selector_args.push(format!("--preview={} show --color {{r1}}", exe_quoted));
        }
        selector_args.push("--preview-window=right:60%:wrap".to_string());
        push_preview_search_binds(&mut selector_args, &exe_quoted, ltsv, "path", &selector);
    }

    let selected = match run_selector(&selector, &selector_args, &input)? {
        Some(s) => s,
        None => return Ok(()),
    };

    let first = selected.split('\t').next().unwrap_or("");
    let quoted = first.strip_prefix("path:").unwrap_or(first);
    // In LTSV mode the `path:` value was `escape_tsv`d before being fed to
    // the selector (paths with literal tabs/newlines could otherwise break
    // the row); decode it back here so the recovered path matches what
    // exists on disk.
    let path = if ltsv {
        strip_shell_quote(&output::unescape_tsv(quoted))
    } else {
        strip_shell_quote(quoted)
    };
    if path.is_empty() {
        return Ok(());
    }

    match &output_fields {
        Some(fields) => {
            // Remote picks (tagged `name:/path` by `merge_into_sessions`) are
            // not local files; forward via SSH and re-tag the path column.
            if let Some((remote_def, remote_path)) = remote::parse_remote_path(&path) {
                remote::run_remote_show_meta(remote_def, remote_path, fields, filter)?;
            } else {
                print_session_fields(
                    &path,
                    fields,
                    &filter.query.clone().unwrap_or_default(),
                    filter.search_mode(),
                )?;
            }
        }
        None => println!("{}", path),
    }
    Ok(())
}

pub fn run_project(
    args: &ListProjectsArgs,
    ia: &InteractiveArgs,
    filter: &FilterArgs,
) -> Result<(), String> {
    let ltsv = args.ltsv();
    let selector = resolve_selector(ia);
    let preview = use_preview(ia, &selector);

    let resolved = ListProjectsResolvedArgs::from_interactive(args)?;

    // Remote projects not supported in interactive mode (cwd is not a local path)
    if !filter.remote.is_empty() {
        eprintln!(
            "Warning: --remote is ignored in interactive project mode (use non-interactive listing)"
        );
    }

    let records = projects::build_project_records(&resolved, filter)?;

    let display_tail: Vec<ProjectField> = resolved
        .fields
        .iter()
        .copied()
        .filter(|f| *f != ProjectField::Cwd)
        .collect();

    let keys: Vec<String> = records
        .iter()
        .map(|r| {
            r.get(&ProjectField::Cwd)
                .map(|s| s.as_str())
                .unwrap_or("")
                .to_string()
        })
        .collect();
    let rows: Vec<Vec<String>> = records
        .iter()
        .map(|r| {
            display_tail
                .iter()
                .map(|pf| sanitize_for_display(r.get(pf).map(|s| s.as_str()).unwrap_or("")))
                .collect()
        })
        .collect();

    let (input, with_nth) = if ltsv {
        let field_names: Vec<String> = display_tail.iter().map(|f| f.name().to_string()).collect();
        // The hidden `cwd:` key is round-tripped through `unescape_tsv`
        // after selection, so use the lossless encoder. Display values are
        // never decoded; encode them with the simple `escape_tsv` so
        // backslashes appear verbatim in the picker.
        let inp = build_ltsv_input(
            "cwd",
            &keys,
            &rows,
            &field_names,
            output::escape_tsv_lossless,
            output::escape_tsv,
        );
        let count = display_tail.len();
        let wn = if count == 0 {
            "--with-nth=1".to_string()
        } else {
            format!("--with-nth=2..{}", count + 1)
        };
        (inp, wn)
    } else {
        let widths = compute_column_widths(&rows);
        let colors: Vec<&str> = display_tail
            .iter()
            .map(|f| output::project_field_color(f))
            .collect();
        let mut inp = String::new();
        for (i, key) in keys.iter().enumerate() {
            inp.push_str(key);
            inp.push('\t');
            inp.push_str(&format_columns(&rows[i], &widths, &colors));
            inp.push('\n');
        }
        (inp, "--with-nth=2..".to_string())
    };

    let mut selector_args: Vec<String> = vec![
        "--ansi".to_string(),
        "--no-sort".to_string(),
        "--delimiter=\t".to_string(),
        with_nth,
    ];

    if preview {
        let exe = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("ah"));
        let exe_quoted = shell_quote(&exe.to_string_lossy());
        if ltsv {
            // In LTSV mode, {1} is "cwd:'/quoted/path'" — strip prefix via shell
            selector_args.push(format!(
                "--preview=p={{1}}; p=${{p#cwd:}}; p=$(printf '%b' \"$p\"); {} log -d \"$p\" -o agent,modified_at,title --color",
                exe_quoted
            ));
        } else {
            selector_args.push(format!(
                "--preview={} log -d {{1}} -o agent,modified_at,title --color",
                exe_quoted
            ));
        }
        selector_args.push("--preview-window=right:60%:wrap".to_string());
    }

    let selected = match run_selector(&selector, &selector_args, &input)? {
        Some(s) => s,
        None => return Ok(()),
    };

    let first = selected.split('\t').next().unwrap_or("");
    let cwd_raw = first.strip_prefix("cwd:").unwrap_or(first);
    // Symmetric to escape_tsv applied when building the LTSV input.
    let cwd = if ltsv {
        output::unescape_tsv(cwd_raw)
    } else {
        cwd_raw.to_string()
    };
    if cwd.is_empty() {
        return Ok(());
    }

    println!("{}", cwd);
    Ok(())
}

pub fn run_show(args: &ShowArgs, ia: &InteractiveArgs, filter: &FilterArgs) -> Result<(), String> {
    let selector = resolve_selector(ia);
    let preview = use_preview(ia, &selector);

    let meta_fields = args.meta_fields()?;

    let default_display = || {
        vec![
            Field::Agent,
            Field::Project,
            Field::ModifiedAt,
            Field::Title,
        ]
    };

    // show -i pipeline uses query-aware ResolveOpts below, so matched
    // populates correctly here — allow it in --interactive-display.
    let display_fields = ia
        .parse_display_fields(true)?
        .unwrap_or_else(default_display);

    let mut resolve_fields = vec![Field::Path, Field::Id, Field::ModifiedAt];
    for f in &display_fields {
        if !resolve_fields.contains(f) {
            resolve_fields.push(*f);
        }
    }
    // Don't pre-resolve `meta_fields` for the selector pass — heavy fields
    // would slow down `ah show -i -o transcript` significantly. The selected
    // session is re-resolved in print_session_fields.
    let _ = &meta_fields;

    let query = filter.query.clone().unwrap_or_default();
    let resolve_opts =
        resolver::ResolveOpts::new(&query, 500, 30).with_search_mode(filter.search_mode());
    let result = pipeline::run_pipeline(&pipeline::PipelineParams {
        resolve_fields: resolve_fields.clone(),
        resolve_opts,
        filters: filter.to_filters(),
        since: filter.since_time()?,
        until: filter.until_time()?,
        query,
        search_mode: filter.search_mode(),
        sort_field: Field::ModifiedAt,
        sort_order: SortOrder::Desc,
        collect_limit: filter.limit,
        running: filter.running,
        require_resume_cmd: false,
    })?;
    let mut sessions = result.sessions;

    remote::merge_into_sessions(
        &mut sessions,
        filter,
        &resolve_fields,
        Field::ModifiedAt,
        SortOrder::Desc,
    )?;

    if sessions.is_empty() {
        return Err("No sessions found.".to_string());
    }

    let visible_fields: Vec<&Field> = display_fields
        .iter()
        .filter(|f| **f != Field::Path)
        .collect();
    let keys: Vec<String> = sessions
        .iter()
        .map(|s| shell_quote(s.fields.get(&Field::Path).map(|v| v.as_str()).unwrap_or("")))
        .collect();
    let rows: Vec<Vec<String>> = sessions
        .iter()
        .map(|s| {
            visible_fields
                .iter()
                .map(|f| sanitize_for_display(s.fields.get(f).map(|v| v.as_str()).unwrap_or("")))
                .collect()
        })
        .collect();

    let widths = compute_column_widths(&rows);
    let colors: Vec<&str> = visible_fields
        .iter()
        .map(|f| output::field_color(f))
        .collect();
    let mut input = String::new();
    for (i, key) in keys.iter().enumerate() {
        input.push_str(key);
        input.push('\t');
        let marker = if sessions[i]
            .fields
            .get(&Field::Running)
            .is_some_and(|v| v == "true")
        {
            "\x1b[32mR\x1b[0m "
        } else {
            "  "
        };
        input.push_str(marker);
        input.push_str(&format_columns(&rows[i], &widths, &colors));
        input.push('\n');
    }

    let mut selector_args: Vec<String> = vec![
        "--ansi".to_string(),
        "--no-sort".to_string(),
        "--delimiter=\t".to_string(),
        "--with-nth=2..".to_string(),
    ];

    if preview {
        let exe = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("ah"));
        let exe_quoted = shell_quote(&exe.to_string_lossy());
        selector_args.push(format!("--preview={} show --color {{r1}}", exe_quoted));
        selector_args.push("--preview-window=right:60%:wrap".to_string());
        push_preview_search_binds(&mut selector_args, &exe_quoted, false, "path", &selector);
    }

    let selected = match run_selector(&selector, &selector_args, &input)? {
        Some(s) => s,
        None => return Ok(()),
    };

    let first = selected.split('\t').next().unwrap_or("");
    let path_str = strip_shell_quote(first);
    if path_str.is_empty() {
        return Ok(());
    }

    if let Some(ref fields) = meta_fields {
        // Remote picks (tagged `remote:path` by `merge_into_sessions`) need
        // SSH forwarding; the local resolver can't read remote files.
        if let Some((remote_def, remote_path)) = remote::parse_remote_path(&path_str) {
            return remote::run_remote_show_meta(remote_def, remote_path, fields, filter);
        }
        let query = filter.query.clone().unwrap_or_default();
        return print_session_fields(&path_str, fields, &query, filter.search_mode());
    }

    let show_args = ShowArgs::with_session(args.head, Some(path_str), args.highlight.clone());
    crate::show::run(show_args, filter)
}

// ── Resume (interactive) ──

pub fn run_resume(
    args: &ResumeArgs,
    ia: &InteractiveArgs,
    filter: &FilterArgs,
) -> Result<(), String> {
    use crate::agents;
    use crate::resume;
    use std::fs;
    use std::time::SystemTime;

    let selector = resolve_selector(ia);
    let preview = use_preview(ia, &selector);
    let home = canonical_home();

    let display_fields = args.common.parse_fields()?.unwrap_or_else(|| {
        vec![
            Field::Agent,
            Field::Project,
            Field::ModifiedAt,
            Field::Title,
        ]
    });
    let mut resolve_fields = vec![Field::Path, Field::Id, Field::ResumeCmd, Field::ModifiedAt];
    for f in &display_fields {
        if !resolve_fields.contains(f) {
            resolve_fields.push(*f);
        }
    }

    let result = pipeline::run_pipeline(&pipeline::PipelineParams {
        resolve_fields: resolve_fields.clone(),
        resolve_opts: resolver::ResolveOpts::default_with_title_limit(30),
        filters: filter.to_filters(),
        since: filter.since_time()?,
        until: filter.until_time()?,
        query: filter.query.clone().unwrap_or_default(),
        search_mode: filter.search_mode(),
        sort_field: Field::ModifiedAt,
        sort_order: SortOrder::Desc,
        collect_limit: filter.limit,
        running: filter.running,
        require_resume_cmd: true,
    })?;
    let mut sessions = result.sessions;

    // Remote sessions get resume_cmd from remote ah, so require_resume_cmd
    // filtering is already done on the remote side.
    remote::merge_into_sessions(
        &mut sessions,
        filter,
        &resolve_fields,
        Field::ModifiedAt,
        SortOrder::Desc,
    )?;

    if sessions.is_empty() {
        return Err("No resumable sessions found.".to_string());
    }

    let visible_fields: Vec<&Field> = display_fields
        .iter()
        .filter(|f| **f != Field::Path)
        .collect();
    let keys: Vec<String> = sessions
        .iter()
        .map(|s| shell_quote(s.fields.get(&Field::Path).map(|v| v.as_str()).unwrap_or("")))
        .collect();
    let rows: Vec<Vec<String>> = sessions
        .iter()
        .map(|s| {
            visible_fields
                .iter()
                .map(|f| sanitize_for_display(s.fields.get(f).map(|v| v.as_str()).unwrap_or("")))
                .collect()
        })
        .collect();

    let ltsv = args.ltsv;

    let (input, with_nth) = if ltsv {
        let field_names: Vec<String> = visible_fields
            .iter()
            .map(|f| f.name().to_string())
            .collect();
        // Lossless encoder for the round-tripped `path:` key; simple
        // encoder for visible columns (otherwise fields like `title`
        // containing `C:\foo` would render with doubled backslashes in
        // the picker).
        let inp = build_ltsv_input(
            "path",
            &keys,
            &rows,
            &field_names,
            output::escape_tsv_lossless,
            output::escape_tsv,
        );
        let count = visible_fields.len();
        (inp, format!("--with-nth=2..{}", count + 1))
    } else {
        let widths = compute_column_widths(&rows);
        let colors: Vec<&str> = visible_fields
            .iter()
            .map(|f| output::field_color(f))
            .collect();
        let mut inp = String::new();
        for (i, key) in keys.iter().enumerate() {
            inp.push_str(key);
            inp.push('\t');
            let marker = if sessions[i]
                .fields
                .get(&Field::Running)
                .is_some_and(|v| v == "true")
            {
                "\x1b[32mR\x1b[0m "
            } else {
                "  "
            };
            inp.push_str(marker);
            inp.push_str(&format_columns(&rows[i], &widths, &colors));
            inp.push('\n');
        }
        (inp, "--with-nth=2..".to_string())
    };

    let mut selector_args: Vec<String> = vec![
        "--ansi".to_string(),
        "--no-sort".to_string(),
        "--delimiter=\t".to_string(),
        with_nth,
    ];

    if preview {
        let exe = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("ah"));
        let exe_quoted = shell_quote(&exe.to_string_lossy());
        if ltsv {
            selector_args.push(format!(
                "--preview=p={{r1}}; p=${{p#path:}}; p=$(printf '%b' \"$p\"); {} show --color \"$p\"",
                exe_quoted
            ));
        } else {
            selector_args.push(format!("--preview={} show --color {{r1}}", exe_quoted));
        }
        selector_args.push("--preview-window=right:60%:wrap".to_string());
        push_preview_search_binds(&mut selector_args, &exe_quoted, ltsv, "path", &selector);
    }

    let selected = match run_selector(&selector, &selector_args, &input)? {
        Some(s) => s,
        None => return Ok(()),
    };

    let first = selected.split('\t').next().unwrap_or("");
    let quoted = first.strip_prefix("path:").unwrap_or(first);
    // Symmetric to escape_tsv applied when building LTSV input above.
    let path_str = if ltsv {
        strip_shell_quote(&output::unescape_tsv(quoted))
    } else {
        strip_shell_quote(quoted)
    };
    if path_str.is_empty() {
        return Ok(());
    }

    if let Some((remote_def, remote_ref)) = remote::parse_remote_path(&path_str) {
        if args.print {
            println!(
                "{}",
                remote::format_remote_resume_command(remote_def, remote_ref, &args.extra_args,)
            );
            return Ok(());
        }
        remote::exec_remote_resume(remote_def, remote_ref, args);
    }

    let path = PathBuf::from(&path_str);
    let plugin = agents::find_plugin_for_path(&path);
    let mtime = fs::metadata(&path)
        .and_then(|m| m.modified())
        .unwrap_or(SystemTime::UNIX_EPOCH);
    let fields = resolver::resolve_fields(
        &path,
        plugin,
        mtime,
        &home,
        &[Field::ResumeCmd],
        &Default::default(),
    );

    let cmd = fields
        .get(&Field::ResumeCmd)
        .map(|v| v.as_str())
        .unwrap_or("");
    if cmd.is_empty() {
        return Err("No resume command available for this session.".to_string());
    }

    let full_cmd = if args.extra_args.is_empty() {
        cmd.to_string()
    } else {
        let extra = args
            .extra_args
            .iter()
            .map(|a| shell_quote(a))
            .collect::<Vec<_>>()
            .join(" ");
        format!("{} {}", cmd, extra)
    };

    if args.print {
        println!("{}", full_cmd);
        return Ok(());
    }

    resume::exec_resume(&full_cmd);
}

/// Push fzf --bind args for live preview highlight + ctrl-s toggle.
///
/// The preview command always passes `--highlight=$FZF_QUERY` to `ah show`,
/// so whatever the user has typed is highlighted in the preview pane.
/// `ah show` ignores --highlight when the pattern is empty.
///
/// On every query change we `refresh-preview` (so the highlight tracks the
/// current query even when the candidate doesn't change) and scroll the
/// preview to the first match.
///
/// ctrl-s toggles fzf's candidate-list filtering on/off via
/// `disable-search`/`enable-search`. Off lets the user keep typing to refine
/// highlight/scroll without the candidate list collapsing under them. The
/// state is read back via the `$FZF_INPUT_STATE` env var fzf exports.
fn push_preview_search_binds(
    selector_args: &mut Vec<String>,
    exe_quoted: &str,
    ltsv: bool,
    path_prefix: &str,
    selector: &str,
) {
    let selector_bin = selector.rsplit('/').next().unwrap_or(selector);
    if selector_bin != "fzf" {
        return;
    }
    // ctrl-s toggle reads $FZF_INPUT_STATE which was added in fzf 0.62.
    // On older fzf the variable is always unset, so the toggle would get
    // stuck always taking the "enabled" branch and could not flip state
    // back. Silently skip these binds so interactive mode still opens
    // cleanly without a half-broken toggle.
    let Some(version) = fzf_version(selector) else {
        return;
    };
    if version < (0, 62) {
        return;
    }
    let (prefix, path_ref) = if ltsv {
        // `printf '%b'` decodes the LTSV value's escape_tsv-style escapes
        // (`\\` / `\t` / `\n` / `\r`) so the preview/scroll commands receive
        // the actual path even for Windows-style cwds (`C:\...`) or paths
        // with embedded tabs/newlines.
        (
            format!(
                "p={{r1}}; p=${{p#{}:}}; p=$(printf '%b' \"$p\"); ",
                path_prefix
            ),
            "\"$p\"",
        )
    } else {
        (String::new(), "{r1}")
    };

    // Always highlight $FZF_QUERY in the preview. Empty query → ah show
    // ignores --highlight, so this is safe at startup too.
    if let Some(pos) = selector_args
        .iter()
        .position(|a| a.starts_with("--preview="))
    {
        selector_args[pos] = format!(
            "--preview={}{} show --color --highlight=\"$FZF_QUERY\" {}",
            prefix, exe_quoted, path_ref
        );
    }

    // Empty $FZF_QUERY is short-circuited to N=0: `grep -F ""` matches every
    // line, which would scroll to line 1 instead of resetting to the top
    // when the user clears the query.
    let scroll_transform = format!(
        "{}if [ -z \"$FZF_QUERY\" ]; then N=0; else N=`{} show {} | grep -Fni -m1 -- \"$FZF_QUERY\" | cut -d: -f1`; test -n \"$N\" || N=0; fi; echo \"change-preview-window(+$N)\"",
        prefix, exe_quoted, path_ref
    );
    // change: re-render preview (so highlight follows the query even when
    // the top candidate doesn't change) and scroll to the first match.
    // bg-transform runs the offset calculation in the background so typing
    // stays responsive even when `ah show | grep` is slow on large
    // transcripts, but it only exists since fzf 0.63 — on 0.62 fall back
    // to the synchronous transform (older fzf rejects unknown actions and
    // exits with status 2 instead of opening at all).
    let transform_action = if version >= (0, 63) {
        "bg-transform"
    } else {
        "transform"
    };
    selector_args.push(format!(
        "--bind=change:refresh-preview+{}({})",
        transform_action, scroll_transform
    ));

    // ctrl-s toggles candidate-list filtering. Off = user can keep typing
    // to refine the preview highlight/scroll without the list collapsing.
    // While filtering is off we append a yellow marker line to the
    // existing `$FZF_HEADER`; on re-enable we strip our marker line
    // (matched literally with `grep -Fv`) so any user-configured header
    // (e.g. via `FZF_DEFAULT_OPTS=--header=...`) is preserved instead of
    // being clobbered by `change-header`.
    selector_args.push(
        "--bind=ctrl-s:transform~if [ \"$FZF_INPUT_STATE\" = disabled ]; then echo 'enable-search+change-preview-window(+0)+transform-header(printf %s \"$FZF_HEADER\" | grep -Fv \"search off — ctrl-s to filter\")'; else echo 'disable-search+transform-header(if [ -n \"$FZF_HEADER\" ]; then printf %s\\n \"$FZF_HEADER\"; fi; printf \"\\033[33m[search off — ctrl-s to filter]\\033[0m\")'; fi~".to_string()
    );
}

/// Run the selector (fzf/sk/etc) with the given args and input, return selected line.
pub fn run_memory(
    args: &MemoryArgs,
    ia: &InteractiveArgs,
    filter: &FilterArgs,
) -> Result<(), String> {
    let selector = resolve_selector(ia);
    let preview = use_preview(ia, &selector);

    // Build resolved args with Path always included for key
    let resolved = MemoryResolvedArgs::from_args_interactive(args)?;

    // Remote memory not supported in interactive mode (path is not a local file)
    if !filter.remote.is_empty() {
        eprintln!(
            "Warning: --remote is ignored in interactive memory mode (use non-interactive listing)"
        );
    }

    let records = memory::build_memory_records(&resolved, filter)?;

    // Display fields = all except Path
    let display_fields: Vec<MemoryField> = resolved
        .fields
        .iter()
        .copied()
        .filter(|f| *f != MemoryField::Path)
        .collect();

    let home = canonical_home();
    let home_str = home.to_string_lossy();
    let keys: Vec<String> = records
        .iter()
        .map(|r| {
            let p = r.get(&MemoryField::Path).map(|s| s.as_str()).unwrap_or("");
            // Expand ~ back to absolute path for preview/cat
            if let Some(rest) = p.strip_prefix('~') {
                format!("{}{}", home_str, rest)
            } else {
                p.to_string()
            }
        })
        .collect();
    let rows: Vec<Vec<String>> = records
        .iter()
        .map(|r| {
            display_fields
                .iter()
                .map(|f| sanitize_for_display(r.get(f).map(|s| s.as_str()).unwrap_or("")))
                .collect()
        })
        .collect();

    let widths = compute_column_widths(&rows);
    let colors: Vec<&str> = display_fields
        .iter()
        .map(|f| output::memory_field_color(f))
        .collect();
    let mut input = String::new();
    for (i, key) in keys.iter().enumerate() {
        input.push_str(key);
        input.push('\t');
        input.push_str(&format_columns(&rows[i], &widths, &colors));
        input.push('\n');
    }

    let mut selector_args: Vec<String> = vec![
        "--ansi".to_string(),
        "--no-sort".to_string(),
        "--delimiter=\t".to_string(),
        "--with-nth=2..".to_string(),
    ];

    if preview {
        selector_args.push("--preview=cat {1}".to_string());
        selector_args.push("--preview-window=right:60%:wrap".to_string());
    }

    let selected = match run_selector(&selector, &selector_args, &input)? {
        Some(s) => s,
        None => return Ok(()),
    };

    let path = selected.split('\t').next().unwrap_or("");
    if path.is_empty() {
        return Ok(());
    }

    println!("{}", path);
    Ok(())
}

/// Run the selector and return the selected line.
/// Returns `None` if the user cancelled (exit 0 behavior).
fn run_selector(selector: &str, args: &[String], input: &str) -> Result<Option<String>, String> {
    let mut child = Command::new(selector)
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::inherit())
        .spawn()
        .map_err(|e| format!("{}: {}", selector, e))?;

    if let Some(ref mut stdin) = child.stdin {
        use std::io::Write;
        let _ = stdin.write_all(input.as_bytes());
    }
    drop(child.stdin.take());

    let result = child
        .wait_with_output()
        .map_err(|e| format!("{}: {}", selector, e))?;

    if !result.status.success() {
        // fzf: 1 = no match, 130 = cancelled (Ctrl-C). Treat as user cancellation.
        // Other non-zero codes indicate genuine errors.
        match result.status.code() {
            Some(1) | Some(130) => return Ok(None),
            Some(code) => return Err(format!("{} exited with status {}", selector, code)),
            None => return Err(format!("{} terminated by signal", selector)),
        }
    }

    let line = String::from_utf8_lossy(&result.stdout);
    let line = line.trim().to_string();
    if line.is_empty() {
        return Ok(None);
    }

    Ok(Some(line))
}

#[cfg(test)]
#[cfg(unix)]
mod tests {
    use super::*;
    use std::io::Write;
    use std::os::unix::fs::PermissionsExt;

    /// Write a fake `fzf` that only answers `--version` with the given
    /// banner, so the version-dependent bind selection can be exercised
    /// without a real fzf install.
    fn fake_fzf(dir: &std::path::Path, banner: &str, exit_code: i32) -> String {
        let path = dir.join("fzf");
        {
            let mut f = std::fs::File::create(&path).unwrap();
            writeln!(f, "#!/bin/sh\necho '{}'\nexit {}", banner, exit_code).unwrap();
        }
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
        // On Linux, a child forked by a concurrent test between create and
        // close above inherits the write fd until its own exec, so exec'ing
        // this script can transiently fail with ETXTBSY (checked per inode,
        // so writing elsewhere and renaming would not help). Retry until one
        // exec succeeds: success proves no write fd remains, and nothing
        // reopens the file for writing afterwards, so the spawns under test
        // cannot hit the race.
        let mut last_err = None;
        for _ in 0..100 {
            match std::process::Command::new(&path).arg("--version").output() {
                Ok(_) => {
                    last_err = None;
                    break;
                }
                Err(e) => {
                    last_err = Some(e);
                    std::thread::sleep(std::time::Duration::from_millis(5));
                }
            }
        }
        if let Some(e) = last_err {
            panic!("fake fzf never became executable: {e}");
        }
        path.to_string_lossy().into_owned()
    }

    fn binds_for(banner: &str) -> Vec<String> {
        binds_for_exit(banner, 0)
    }

    fn binds_for_exit(banner: &str, exit_code: i32) -> Vec<String> {
        let dir = tempfile::tempdir().unwrap();
        let selector = fake_fzf(dir.path(), banner, exit_code);
        let mut args = vec!["--preview='ah' show --color {r1}".to_string()];
        push_preview_search_binds(&mut args, "'ah'", false, "path", &selector);
        args
    }

    fn change_bind(args: &[String]) -> &String {
        args.iter()
            .find(|a| a.starts_with("--bind=change:"))
            .unwrap_or_else(|| panic!("no change bind in {args:?}"))
    }

    #[test]
    fn preview_search_uses_bg_transform_on_fzf_063_and_later() {
        let args = binds_for("0.63.0 (test)");
        assert!(
            change_bind(&args).contains("refresh-preview+bg-transform("),
            "{args:?}"
        );
    }

    #[test]
    fn preview_search_falls_back_to_transform_on_fzf_062() {
        let args = binds_for("0.62.0 (test)");
        let bind = change_bind(&args);
        assert!(bind.contains("refresh-preview+transform("), "{bind}");
        assert!(!bind.contains("bg-transform"), "{bind}");
    }

    #[test]
    fn preview_search_skipped_on_fzf_before_062() {
        let args = binds_for("0.61.3 (test)");
        assert!(!args.iter().any(|a| a.starts_with("--bind=")), "{args:?}");
    }

    #[test]
    fn preview_search_skipped_when_version_check_fails() {
        let args = binds_for_exit("0.70.0 (test)", 1);
        assert!(!args.iter().any(|a| a.starts_with("--bind=")), "{args:?}");
    }

    #[test]
    fn preview_search_parses_prefixed_version_banner() {
        let args = binds_for("fzf 0.64.0 (debian)");
        assert!(
            change_bind(&args).contains("refresh-preview+bg-transform("),
            "{args:?}"
        );
    }
}