dpc-tau-cli-term 0.2.1

A minimal Unix-first coding agent.
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
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
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
//! Command-mode and argument completion content + menu rendering.
//!
//! State and lifecycle live in [`tau_cli_term_raw`]; this module
//! supplies the *content* (which candidates exist for a given buffer)
//! and the *presentation* (how the menu block is laid out and styled).
//!
//! Public types:
//! - [`CommandCompletion`] — command completion entry
//! - [`CompletionItem`] / [`CompletionData`] — dynamic argument completions
//! - [`build_candidates`] — turns the current buffer into a `Vec<Candidate>`
//! - [`render_menu_block`] — turns a [`CompletionView`] into a [`StyledBlock`]

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::{collections as path_std_collections, fmt};

use tau_cli_term_raw::{
    Candidate, CompletionAcceptance, CompletionView, Span, StyledBlock, StyledText,
};
use tau_term_screen::{display_width, truncate_to_width};
use tau_themes::Theme;

use crate::resolve;

mod git_files;

/// One command-mode token, including its leading `:` (for example, `":model"`).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct CommandName(String);

impl CommandName {
    /// Creates a command name and asserts it follows the command-token grammar.
    ///
    /// # Panics
    ///
    /// Panics unless `name` is one colon followed by an ASCII alphanumeric
    /// character and then only ASCII alphanumeric, `_`, or `-` characters.
    pub fn new(name: impl Into<String>) -> Self {
        let s = name.into();
        assert!(
            is_valid_command_name(&s),
            "CommandName must be ':' followed by one command token"
        );
        Self(s)
    }

    /// Returns the command name as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for CommandName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// One command-mode completion entry with its display description.
#[derive(Clone, Debug)]
pub struct CommandCompletion {
    /// Command token typed by the user, including the leading `:`.
    pub name: CommandName,
    /// Human-readable description shown in the completion menu.
    pub description: String,
}

impl CommandCompletion {
    /// Creates a command-mode entry with a display description for completion
    /// menus.
    ///
    /// # Panics
    ///
    /// Panics when `name` does not satisfy [`CommandName::new`].
    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: CommandName::new(name),
            description: description.into(),
        }
    }
}

pub(crate) fn is_valid_command_name(name: &str) -> bool {
    let Some(token) = name.strip_prefix(':') else {
        return false;
    };
    let mut chars = token.chars();
    chars.next().is_some_and(|ch| ch.is_ascii_alphanumeric())
        && chars.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-'))
}

/// A single argument completion candidate.
#[derive(Clone, Debug)]
pub struct CompletionItem {
    /// Text inserted into the prompt when this completion is accepted.
    pub value: String,
    /// Human-readable description shown beside the value in the menu.
    pub description: String,
}

impl CompletionItem {
    /// Creates an argument completion with a menu description.
    pub fn new(value: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            description: description.into(),
        }
    }

    /// Creates an argument completion with no menu description.
    pub fn plain(value: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            description: String::new(),
        }
    }
}

/// Closure that produces argument completions for a command,
/// given the already-typed args (the last element is the partial arg
/// being completed; may be empty for "just typed a space").
///
/// The closure is responsible for filtering and ranking — callers do
/// no further processing. For the common flat-list case use
/// [`CompletionData::set_arg_completions`], which builds an appropriate
/// closure internally.
pub type ArgCompleter = Arc<dyn Fn(&[&str]) -> Vec<CompletionItem> + Send + Sync>;

/// Mutable completion state shared with background renderer updates.
#[derive(Default)]
struct CompletionInner {
    /// Description replacements for intrinsic command-root candidates.
    static_command_descriptions: HashMap<CommandName, String>,
    arg_completers: HashMap<CommandName, ArgCompleter>,
    dynamic_arg_completers: HashMap<CommandName, ArgCompleter>,
    dynamic_commands: Vec<CommandCompletion>,
    agent_mention_completer: Option<ArgCompleter>,
    session_completer: Option<ArgCompleter>,
}

/// Thread-safe storage for dynamic command and argument completions.
///
/// Clone this handle and pass it to background threads that need to
/// update available completions (e.g. when the harness sends a model
/// list or an extension publishes an action schema).
#[derive(Clone, Default)]
pub struct CompletionData {
    inner: Arc<Mutex<CompletionInner>>,
}

impl CompletionData {
    /// Creates empty, shareable dynamic completion storage.
    pub fn new() -> Self {
        Self::default()
    }

    /// Replaces extension-provided root commands shown alongside the
    /// static command registry.
    pub fn set_dynamic_commands(&self, commands: Vec<CommandCompletion>) {
        self.set_dynamic_commands_and_arg_completers(commands, Vec::new());
    }

    /// Replaces extension-provided root commands and their nested
    /// argument/subcommand completers as one atomic snapshot.
    pub fn set_dynamic_commands_and_arg_completers(
        &self,
        commands: Vec<CommandCompletion>,
        arg_completers: Vec<(CommandName, ArgCompleter)>,
    ) {
        let mut inner = self.inner.lock().expect("completion data lock");
        inner.dynamic_commands = commands;
        inner.dynamic_arg_completers = arg_completers.into_iter().collect();
    }

    /// Replaces descriptions for existing intrinsic command-root candidates.
    ///
    /// This changes display text only: it cannot add a command or alter its
    /// insertion text.
    pub fn set_static_command_descriptions(
        &self,
        descriptions: impl IntoIterator<Item = (CommandName, String)>,
    ) {
        self.inner
            .lock()
            .expect("completion data lock")
            .static_command_descriptions = descriptions.into_iter().collect();
    }

    /// Sets a flat, single-arg completion list for a command.
    /// Items are ranked prefix-match-first, substring-match-second
    /// (case-insensitive). For commands that take more than one arg
    /// or need to react to prior args, use
    /// [`CompletionData::set_arg_completer`].
    pub fn set_arg_completions(&self, command: CommandName, items: Vec<CompletionItem>) {
        // Precompute lowercased haystacks once at insertion time so
        // the per-keystroke match loop doesn't reallocate.
        let indexed: Arc<Vec<(CompletionItem, String)>> = Arc::new(
            items
                .into_iter()
                .map(|item| {
                    let lower = item.value.to_lowercase();
                    (item, lower)
                })
                .collect(),
        );
        let completer: ArgCompleter = Arc::new(move |args: &[&str]| {
            // Single-arg completion only — multi-arg buffers fall
            // through to no candidates.
            if args.len() != 1 {
                return Vec::new();
            }
            let needle = args[0].to_lowercase();
            let mut prefix_matches = Vec::new();
            let mut substr_matches = Vec::new();
            for (item, value_lower) in indexed.iter() {
                if needle.is_empty() || value_lower.starts_with(&needle) {
                    prefix_matches.push(item.clone());
                } else if value_lower.contains(&needle) {
                    substr_matches.push(item.clone());
                }
            }
            prefix_matches.extend(substr_matches);
            prefix_matches
        });
        self.inner
            .lock()
            .expect("completion data lock")
            .arg_completers
            .insert(command, completer);
    }

    /// Registers a custom argument completer for a command.
    /// The closure receives the args typed so far (with the partial
    /// last element being completed) and returns ranked candidates.
    pub fn set_arg_completer(&self, command: CommandName, completer: ArgCompleter) {
        self.inner
            .lock()
            .expect("completion data lock")
            .arg_completers
            .insert(command, completer);
    }

    fn get_arg_completer(&self, command: &CommandName) -> Option<ArgCompleter> {
        let inner = self.inner.lock().expect("completion data lock");
        inner
            .arg_completers
            .get(command)
            .or_else(|| inner.dynamic_arg_completers.get(command))
            .cloned()
    }

    /// Registers prompt-text completion for active agent mentions typed as
    /// `@<partial-agent-id>`.
    pub fn set_agent_mention_completer(&self, completer: ArgCompleter) {
        self.inner
            .lock()
            .expect("completion data lock")
            .agent_mention_completer = Some(completer);
    }

    /// Registers prompt-text completion for running sessions typed as
    /// `&<partial-session-id>`.
    pub fn set_session_completer(&self, completer: ArgCompleter) {
        self.inner
            .lock()
            .expect("completion data lock")
            .session_completer = Some(completer);
    }

    fn get_agent_mention_completer(&self) -> Option<ArgCompleter> {
        self.inner
            .lock()
            .expect("completion data lock")
            .agent_mention_completer
            .clone()
    }

    fn get_session_completer(&self) -> Option<ArgCompleter> {
        self.inner
            .lock()
            .expect("completion data lock")
            .session_completer
            .clone()
    }

    fn root_commands(&self) -> (HashMap<CommandName, String>, Vec<CommandCompletion>) {
        let inner = self.inner.lock().expect("completion data lock");
        (
            inner.static_command_descriptions.clone(),
            inner.dynamic_commands.clone(),
        )
    }

    fn dynamic_commands(&self) -> Vec<CommandCompletion> {
        self.inner
            .lock()
            .expect("completion data lock")
            .dynamic_commands
            .clone()
    }
}

/// Named completion behavior selected by prompt completion config.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CompletionRuleKind {
    /// Complete active agent mentions from harness-provided agent data.
    Agents,
    /// Complete running session identifiers from application-provided data.
    Sessions,
    /// Complete filesystem paths by reading the matching directory.
    Path,
    /// Complete filesystem paths, preferring fuzzy git-tracked file matches for
    /// `./<partial>` inside a repository.
    PathFuzzy,
    /// Complete action/command names.
    Actions,
    /// Run an external command when the trigger token is typed exactly.
    Command(Vec<String>),
}

/// A single prompt completion rule keyed by the word prefix that activates it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CompletionRule {
    /// Word prefix that activates this completion rule.
    pub prefix: String,
    /// Completion behavior selected for the prefix.
    pub kind: CompletionRuleKind,
}

/// Private nonempty argv retained for one configured completion command.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct CompletionCommand {
    /// Executable name passed as argv element zero.
    program: String,
    /// Remaining argv elements passed to the executable unchanged and in order.
    args: Vec<String>,
}

impl CompletionCommand {
    /// Converts a public command argv into its private nonempty runtime form.
    fn from_argv(argv: Vec<String>) -> Option<Self> {
        let mut argv = argv.into_iter();
        Some(Self {
            program: argv.next()?,
            args: argv.collect(),
        })
    }

    /// Returns the executable name selected by the public command argv.
    pub(super) fn program(&self) -> &str {
        &self.program
    }

    /// Returns the executable arguments after the program name.
    pub(super) fn args(&self) -> &[String] {
        &self.args
    }
}

/// Exact command-completion match selected from the private runtime rules.
pub(super) enum CommandCompletionMatch<'a> {
    /// A public command argv with a program, ready for execution.
    Command(&'a CompletionCommand),
    /// A publicly constructed empty command argv, retained for the established
    /// runtime fallback diagnostic.
    EmptyCommand,
}

/// One completion rule retained by the private command-completion runtime.
#[derive(Clone, Debug)]
struct RuntimeCompletionRule {
    /// Word prefix that activates this rule.
    prefix: String,
    /// Runtime behavior selected from the public rule kind.
    kind: RuntimeCompletionRuleKind,
}

impl From<&CompletionRule> for RuntimeCompletionRule {
    fn from(rule: &CompletionRule) -> Self {
        Self {
            prefix: rule.prefix.clone(),
            kind: (&rule.kind).into(),
        }
    }
}

/// Runtime completion behavior with command argv made nonempty before storage.
#[derive(Clone, Debug)]
enum RuntimeCompletionRuleKind {
    /// Complete active agent mentions from harness-provided agent data.
    Agents,
    /// Complete running session identifiers from application-provided data.
    Sessions,
    /// Complete filesystem paths by reading the matching directory.
    Path,
    /// Complete filesystem paths, preferring fuzzy git-tracked file matches.
    PathFuzzy,
    /// Complete action/command names.
    Actions,
    /// Run a configured command, or retain the public empty-argv fallback.
    Command(Option<CompletionCommand>),
}

impl From<&CompletionRuleKind> for RuntimeCompletionRuleKind {
    fn from(kind: &CompletionRuleKind) -> Self {
        match kind {
            CompletionRuleKind::Agents => Self::Agents,
            CompletionRuleKind::Sessions => Self::Sessions,
            CompletionRuleKind::Path => Self::Path,
            CompletionRuleKind::PathFuzzy => Self::PathFuzzy,
            CompletionRuleKind::Actions => Self::Actions,
            CompletionRuleKind::Command(argv) => {
                Self::Command(CompletionCommand::from_argv(argv.clone()))
            }
        }
    }
}

impl CompletionRule {
    /// Parses a `cli.yaml` completion entry such as `complete_path` or
    /// `complete_with_command fzf --filter foo`.
    pub fn parse(prefix: impl Into<String>, spec: &str) -> Option<Self> {
        let prefix = prefix.into();
        let mut parts = spec.split_whitespace();
        let name = parts.next()?;
        let kind = match name {
            "complete_agents" => CompletionRuleKind::Agents,
            "complete_sessions" => CompletionRuleKind::Sessions,
            "complete_path" => CompletionRuleKind::Path,
            "complete_path_fuzzy" => CompletionRuleKind::PathFuzzy,
            "complete_actions" => CompletionRuleKind::Actions,
            "complete_with_command" => {
                let args = parts.map(ToOwned::to_owned).collect::<Vec<_>>();
                if args.is_empty() {
                    return None;
                }
                CompletionRuleKind::Command(args)
            }
            _ => return None,
        };
        Some(Self { prefix, kind })
    }
}

/// Prompt completion rules. If multiple rules match, the longest prefix wins.
#[derive(Clone, Debug)]
pub struct CompletionRules {
    /// Public/config rules retained for the public accessor and completion
    /// menu.
    rules: Vec<CompletionRule>,
    /// Private command runtime derived at the public-rule construction
    /// boundary.
    command_rules: CompletionCommandRules,
}

impl CompletionRules {
    /// Creates rules sorted so the longest matching prefix wins.
    pub fn new(mut rules: Vec<CompletionRule>) -> Self {
        rules.sort_by(|a, b| {
            b.prefix
                .len()
                .cmp(&a.prefix.len())
                .then(a.prefix.cmp(&b.prefix))
        });
        let command_rules = CompletionCommandRules::from_public_rules(&rules);
        Self {
            rules,
            command_rules,
        }
    }

    /// Built-in prompt completion defaults used when no config is supplied.
    pub fn built_in() -> Self {
        Self::new(vec![
            CompletionRule::parse("@", "complete_agents").expect("valid built-in completion"),
            CompletionRule::parse("&", "complete_sessions").expect("valid built-in completion"),
            CompletionRule::parse("./", "complete_path").expect("valid built-in completion"),
            CompletionRule::parse("../", "complete_path").expect("valid built-in completion"),
            CompletionRule::parse("/", "complete_path").expect("valid built-in completion"),
            CompletionRule::parse("~", "complete_path").expect("valid built-in completion"),
            CompletionRule::parse("~/", "complete_path").expect("valid built-in completion"),
        ])
    }

    fn matching_rule(&self, token_prefix: &str) -> Option<&CompletionRule> {
        self.rules
            .iter()
            .find(|rule| token_prefix.starts_with(&rule.prefix))
    }

    /// Returns the argv and replacement surroundings for an exact command
    /// trigger token at the cursor.
    pub fn command_for_exact_token<'a>(
        &'a self,
        buffer: &'a str,
        cursor: usize,
    ) -> Option<(&'a [String], &'a str, &'a str)> {
        let token = exact_command_token(buffer, cursor)?;
        let rule = self.rules.iter().find(|rule| rule.prefix == token.prefix)?;
        match &rule.kind {
            CompletionRuleKind::Command(command) => Some((command, token.before, token.after)),
            _ => None,
        }
    }

    /// Returns the private command runtime derived with these public rules.
    pub(super) fn command_rules(&self) -> &CompletionCommandRules {
        &self.command_rules
    }
}

/// Private command rules converted from the public completion-rule boundary.
#[derive(Clone, Debug)]
pub(super) struct CompletionCommandRules {
    /// All rules in public rule order so duplicate-prefix behavior remains
    /// exact.
    rules: Vec<RuntimeCompletionRule>,
}

impl CompletionCommandRules {
    /// Converts public completion rules at their construction boundary.
    fn from_public_rules(rules: &[CompletionRule]) -> Self {
        Self {
            rules: rules.iter().map(RuntimeCompletionRule::from).collect(),
        }
    }

    /// Returns the private command and replacement surroundings for one exact
    /// command trigger token.
    pub(super) fn command_for_exact_token<'a>(
        &'a self,
        buffer: &'a str,
        cursor: usize,
    ) -> Option<(CommandCompletionMatch<'a>, &'a str, &'a str)> {
        let token = exact_command_token(buffer, cursor)?;
        let rule = self.rules.iter().find(|rule| rule.prefix == token.prefix)?;
        match &rule.kind {
            RuntimeCompletionRuleKind::Command(Some(command)) => Some((
                CommandCompletionMatch::Command(command),
                token.before,
                token.after,
            )),
            RuntimeCompletionRuleKind::Command(None) => Some((
                CommandCompletionMatch::EmptyCommand,
                token.before,
                token.after,
            )),
            _ => None,
        }
    }
}

/// Finds a configured command trigger only when it occupies the complete token
/// at the cursor outside intrinsic command mode.
fn exact_command_token(buffer: &str, cursor: usize) -> Option<PathToken<'_>> {
    if first_non_whitespace_starts_command(buffer) {
        return None;
    }
    let token = word_token(buffer, cursor)?;
    if buffer
        .get(cursor..)?
        .chars()
        .next()
        .is_some_and(|ch| !ch.is_whitespace())
    {
        return None;
    }
    Some(token)
}

impl Default for CompletionRules {
    fn default() -> Self {
        Self::built_in()
    }
}

/// Builds the candidate list for the given buffer/cursor.
pub fn build_candidates(
    commands: &[CommandCompletion],
    data: &CompletionData,
    buffer: &str,
    cursor: usize,
) -> Vec<Candidate> {
    build_candidates_with_rules(commands, data, &CompletionRules::default(), buffer, cursor)
}

/// Builds candidates using explicit prompt completion rules.
pub fn build_candidates_with_rules(
    commands: &[CommandCompletion],
    data: &CompletionData,
    rules: &CompletionRules,
    buffer: &str,
    cursor: usize,
) -> Vec<Candidate> {
    build_candidates_with_home_and_rules(
        commands,
        data,
        rules,
        buffer,
        cursor,
        home_dir().as_deref(),
    )
}

#[cfg(test)]
pub(crate) fn build_candidates_with_home(
    commands: &[CommandCompletion],
    data: &CompletionData,
    buffer: &str,
    cursor: usize,
    home_dir: Option<&Path>,
) -> Vec<Candidate> {
    build_candidates_with_home_and_rules(
        commands,
        data,
        &CompletionRules::default(),
        buffer,
        cursor,
        home_dir,
    )
}

pub(crate) fn build_candidates_with_home_and_rules(
    commands: &[CommandCompletion],
    data: &CompletionData,
    rules: &CompletionRules,
    buffer: &str,
    cursor: usize,
    home_dir: Option<&Path>,
) -> Vec<Candidate> {
    build_candidates_with_home_and_rules_at_cwd(
        commands, data, rules, buffer, cursor, home_dir, None,
    )
}

/// Builds candidates against an injected current directory for hermetic tests.
#[cfg(test)]
pub(crate) fn build_candidates_with_home_and_cwd(
    commands: &[CommandCompletion],
    data: &CompletionData,
    buffer: &str,
    cursor: usize,
    home_dir: Option<&Path>,
    cwd: &Path,
) -> Vec<Candidate> {
    build_candidates_with_home_and_rules_at_cwd(
        commands,
        data,
        &CompletionRules::default(),
        buffer,
        cursor,
        home_dir,
        Some(cwd),
    )
}

fn build_candidates_with_home_and_rules_at_cwd(
    commands: &[CommandCompletion],
    data: &CompletionData,
    rules: &CompletionRules,
    buffer: &str,
    cursor: usize,
    home_dir: Option<&Path>,
    working_dir: Option<&Path>,
) -> Vec<Candidate> {
    if first_non_whitespace_starts_command(buffer) {
        let leading_len = buffer.len() - buffer.trim_start().len();
        let view = &buffer[leading_len..];
        if cursor < leading_len {
            return Vec::new();
        }
        let view_cursor = clamp_to_char_boundary(view, cursor.saturating_sub(leading_len));
        if view_cursor == 0 {
            return Vec::new();
        }
        let command_token_end = first_whitespace(view)
            .map(|(index, _)| index)
            .unwrap_or(view.len());
        if view_cursor <= command_token_end {
            let prefix = &view[..view_cursor];
            let suffix = &view[command_token_end..];
            let (static_descriptions, dynamic_commands) = data.root_commands();
            let candidates =
                build_cmd_candidates(commands, &dynamic_commands, &static_descriptions, prefix);
            return replace_token_candidates(&buffer[..leading_len], suffix, candidates);
        }

        if let Some((space_pos, space_ch)) = first_whitespace(view) {
            let cmd = &view[..space_pos];
            if cmd.is_empty() {
                return Vec::new();
            }
            let rest_start = space_pos + space_ch.len_utf8();
            let rest = &view[rest_start..];
            let rest_cursor = view_cursor.saturating_sub(rest_start).min(rest.len());
            let candidates = build_arg_candidates(data, cmd, rest, rest_cursor);
            return prepend_to_replacements(&buffer[..leading_len], candidates);
        }
    }

    let Some(token) = word_token(buffer, cursor) else {
        return Vec::new();
    };
    let Some(rule) = rules.matching_rule(token.prefix) else {
        return Vec::new();
    };

    match &rule.kind {
        CompletionRuleKind::Agents => build_agent_mention_candidates(data, &token, &rule.prefix),
        CompletionRuleKind::Sessions => build_session_candidates(data, &token, &rule.prefix),
        CompletionRuleKind::Path => {
            build_filesystem_candidates_with_home(&token, home_dir, false, working_dir)
        }
        CompletionRuleKind::PathFuzzy => {
            build_filesystem_candidates_with_home(&token, home_dir, true, working_dir)
        }
        CompletionRuleKind::Actions => {
            build_action_token_candidates(commands, &data.dynamic_commands(), &token, &rule.prefix)
        }
        CompletionRuleKind::Command(_) => Vec::new(),
    }
}

fn build_cmd_candidates(
    static_commands: &[CommandCompletion],
    dynamic_commands: &[CommandCompletion],
    static_descriptions: &HashMap<CommandName, String>,
    prefix: &str,
) -> Vec<Candidate> {
    let mut seen = path_std_collections::HashSet::new();
    static_commands
        .iter()
        .chain(dynamic_commands)
        .filter(|cmd| seen.insert(cmd.name.to_string()))
        .filter(|cmd| cmd.name.as_str().starts_with(prefix))
        .map(|cmd| Candidate {
            label: cmd.name.to_string(),
            description: static_descriptions
                .get(&cmd.name)
                .cloned()
                .unwrap_or_else(|| cmd.description.clone()),
            replacement: cmd.name.to_string(),
            cursor: cmd.name.as_str().len(),
            acceptance: None,
        })
        .collect()
}
fn prepend_to_replacements(prefix: &str, candidates: Vec<Candidate>) -> Vec<Candidate> {
    candidates
        .into_iter()
        .map(|candidate| Candidate {
            replacement: format!("{prefix}{}", candidate.replacement),
            cursor: prefix.len() + candidate.cursor,
            ..candidate
        })
        .collect()
}

fn replace_token_candidates(
    before: &str,
    after: &str,
    candidates: Vec<Candidate>,
) -> Vec<Candidate> {
    candidates
        .into_iter()
        .map(|candidate| {
            let accepted = candidate.replacement.clone();
            replace_candidate(candidate, before, &accepted, after)
        })
        .collect()
}

fn replace_candidate(candidate: Candidate, before: &str, accepted: &str, after: &str) -> Candidate {
    Candidate {
        replacement: format!("{before}{accepted}{after}"),
        cursor: before.len() + accepted.len(),
        ..candidate
    }
}

fn build_action_token_candidates(
    static_commands: &[CommandCompletion],
    dynamic_commands: &[CommandCompletion],
    token: &PathToken<'_>,
    trigger_prefix: &str,
) -> Vec<Candidate> {
    let partial = token
        .prefix
        .strip_prefix(trigger_prefix)
        .unwrap_or(token.prefix);
    let lookup_prefix = if trigger_prefix == ":" {
        token.prefix.to_owned()
    } else {
        format!(":{partial}")
    };
    build_cmd_candidates(
        static_commands,
        dynamic_commands,
        &HashMap::new(),
        &lookup_prefix,
    )
    .into_iter()
    .map(|candidate| {
        let replacement = if trigger_prefix == ":" {
            candidate.replacement.clone()
        } else {
            format!(
                "{trigger_prefix}{}",
                candidate.replacement.trim_start_matches(':')
            )
        };
        replace_candidate(candidate, token.before, &replacement, token.after)
    })
    .collect()
}
struct PathToken<'a> {
    prefix: &'a str,
    /// Bytes in the current token after the cursor.
    suffix: &'a str,
    before: &'a str,
    after: &'a str,
}

fn first_non_whitespace_starts_command(buffer: &str) -> bool {
    let trimmed = buffer.trim_start();
    trimmed.starts_with(':') && !trimmed.starts_with("::")
}

fn word_token(buffer: &str, cursor: usize) -> Option<PathToken<'_>> {
    let before_cursor = buffer.get(..cursor)?;
    let after_cursor = buffer.get(cursor..)?;
    let token_start = before_cursor
        .char_indices()
        .rev()
        .find_map(|(idx, ch)| ch.is_whitespace().then_some(idx + ch.len_utf8()))
        .unwrap_or(0);
    let token_end = after_cursor
        .char_indices()
        .find_map(|(idx, ch)| ch.is_whitespace().then_some(cursor + idx))
        .unwrap_or(buffer.len());
    Some(PathToken {
        prefix: &buffer[token_start..cursor],
        suffix: &buffer[cursor..token_end],
        before: &buffer[..token_start],
        after: &buffer[token_end..],
    })
}

fn build_session_candidates(
    data: &CompletionData,
    token: &PathToken<'_>,
    trigger_prefix: &str,
) -> Vec<Candidate> {
    if token.prefix.contains('/') || token.suffix.contains('/') {
        return Vec::new();
    }
    let Some(completer) = data.get_session_completer() else {
        return Vec::new();
    };
    let partial = token
        .prefix
        .strip_prefix(trigger_prefix)
        .unwrap_or(token.prefix);
    completer(&[partial])
        .into_iter()
        .map(|item| {
            let accepted = format!("{trigger_prefix}{}", item.value);
            replace_candidate(
                Candidate {
                    label: item.value,
                    description: item.description,
                    replacement: String::new(),
                    cursor: 0,
                    acceptance: None,
                },
                token.before,
                &accepted,
                token.after,
            )
        })
        .collect()
}
fn build_agent_mention_candidates(
    data: &CompletionData,
    token: &PathToken<'_>,
    trigger_prefix: &str,
) -> Vec<Candidate> {
    let Some(completer) = data.get_agent_mention_completer() else {
        return Vec::new();
    };
    let partial = token
        .prefix
        .strip_prefix(trigger_prefix)
        .unwrap_or(token.prefix);
    completer(&[partial])
        .into_iter()
        .map(|item| {
            let accepted = format!("{trigger_prefix}{}", item.value);
            replace_candidate(
                Candidate {
                    label: item.value,
                    description: item.description,
                    replacement: String::new(),
                    cursor: 0,
                    acceptance: None,
                },
                token.before,
                &accepted,
                token.after,
            )
        })
        .collect()
}

fn cwd() -> PathBuf {
    std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
}

fn home_dir() -> Option<PathBuf> {
    let home = std::env::var_os("HOME")?;
    if home.as_os_str().is_empty() {
        None
    } else {
        Some(PathBuf::from(home))
    }
}
fn home_expanded_path(prefix: &str, home_dir: Option<&Path>) -> Option<PathBuf> {
    if prefix == "~" {
        Some(home_dir?.to_path_buf())
    } else if let Some(rest) = prefix.strip_prefix("~/") {
        Some(home_dir?.join(rest))
    } else {
        Some(PathBuf::from(prefix))
    }
}

fn build_filesystem_candidates_with_home(
    path_token: &PathToken<'_>,
    home_dir: Option<&Path>,
    fuzzy_git_files: bool,
    working_dir: Option<&Path>,
) -> Vec<Candidate> {
    let prefix = path_token.prefix;
    let Some(lookup_path) = home_expanded_path(prefix, home_dir) else {
        return Vec::new();
    };
    let display_path = Path::new(prefix);
    let (lookup_dir, display_dir, partial) = if prefix == "~" {
        (lookup_path, PathBuf::from("~"), "")
    } else if prefix.ends_with('/') {
        (lookup_path, display_path.to_path_buf(), "")
    } else {
        let Some(lookup_parent) = lookup_path.parent() else {
            return Vec::new();
        };
        let Some(display_parent) = display_path.parent() else {
            return Vec::new();
        };
        let partial = display_path
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or("");
        let lookup_dir = if lookup_parent.as_os_str().is_empty() {
            PathBuf::from(".")
        } else {
            lookup_parent.to_path_buf()
        };
        let display_dir = if display_parent.as_os_str().is_empty() {
            PathBuf::from(".")
        } else {
            display_parent.to_path_buf()
        };
        (lookup_dir, display_dir, partial)
    };

    if fuzzy_git_files && prefix.starts_with("./") && !partial.is_empty() {
        let cwd = working_dir.map(Path::to_path_buf).unwrap_or_else(cwd);
        if let Some((repo_root, files)) = git_files::git_repo_files(&cwd) {
            let matches = git_files::fuzzy_match_git_files(partial, &files);
            if !matches.is_empty() {
                return matches
                    .into_iter()
                    .map(|path| {
                        let display = git_files::dotslash_display_path(path, &repo_root, &cwd);
                        replace_candidate(
                            Candidate {
                                label: display.clone(),
                                description: "git file".to_owned(),
                                replacement: String::new(),
                                cursor: 0,
                                acceptance: None,
                            },
                            path_token.before,
                            &display,
                            path_token.after,
                        )
                    })
                    .collect();
            }
        }
    }

    let lookup_dir = working_dir
        .filter(|_| lookup_dir.is_relative())
        .map_or(lookup_dir.clone(), |cwd| cwd.join(lookup_dir));
    let Ok(entries) = std::fs::read_dir(lookup_dir) else {
        return Vec::new();
    };

    let mut candidates = Vec::new();
    for entry in entries.flatten() {
        let name = entry.file_name();
        let Some(name) = name.to_str() else {
            continue;
        };
        if !name.starts_with(partial) {
            continue;
        }
        if !partial.starts_with('.') && name.starts_with('.') {
            continue;
        }

        let is_dir = entry.file_type().map(|ty| ty.is_dir()).unwrap_or(false);
        let mut replacement = display_dir.join(name).to_string_lossy().into_owned();
        if is_dir && !replacement.ends_with('/') {
            replacement.push('/');
        }
        let acceptance = home_completion_acceptance(
            path_token,
            home_dir,
            &replacement,
            path_token.before,
            path_token.after,
        );
        candidates.push(replace_candidate(
            Candidate {
                label: replacement.clone(),
                description: if is_dir { "directory" } else { "file" }.to_owned(),
                replacement: String::new(),
                cursor: 0,
                acceptance,
            },
            path_token.before,
            &replacement,
            path_token.after,
        ));
    }

    candidates.sort_by(|a, b| a.label.cmp(&b.label));
    candidates
}

fn clamp_to_char_boundary(text: &str, cursor: usize) -> usize {
    let mut cursor = cursor.min(text.len());
    while 0 < cursor && !text.is_char_boundary(cursor) {
        cursor -= 1;
    }
    cursor
}

fn first_whitespace(text: &str) -> Option<(usize, char)> {
    text.char_indices().find(|(_, ch)| ch.is_whitespace())
}

fn build_arg_candidates(
    data: &CompletionData,
    cmd: &str,
    rest: &str,
    rest_cursor: usize,
) -> Vec<Candidate> {
    let cmd_name = CommandName::new(cmd);
    let Some(completer) = data.get_arg_completer(&cmd_name) else {
        return Vec::new();
    };

    let rest_cursor = clamp_to_char_boundary(rest, rest_cursor);
    let token_start = rest[..rest_cursor]
        .char_indices()
        .rev()
        .find_map(|(pos, ch)| ch.is_whitespace().then_some(pos + ch.len_utf8()))
        .unwrap_or(0);
    let token_end = rest[rest_cursor..]
        .find(char::is_whitespace)
        .map(|pos| rest_cursor + pos)
        .unwrap_or(rest.len());

    let mut args: Vec<&str> = rest[..token_start].split_whitespace().collect();
    args.push(&rest[token_start..rest_cursor]);

    let replacement_prefix = format!("{cmd} {}", &rest[..token_start]);
    let replacement_suffix = &rest[token_end..];

    completer(&args)
        .into_iter()
        .map(|item| {
            let accepted = item.value.clone();
            replace_candidate(
                Candidate {
                    label: item.value,
                    description: item.description,
                    replacement: String::new(),
                    cursor: 0,
                    acceptance: None,
                },
                &replacement_prefix,
                &accepted,
                replacement_suffix,
            )
        })
        .collect()
}

/// Builds the absolute prompt replacement used only after accepting a `~/`
/// filesystem candidate.
fn home_completion_acceptance(
    path_token: &PathToken<'_>,
    home_dir: Option<&Path>,
    display_replacement: &str,
    before: &str,
    after: &str,
) -> Option<CompletionAcceptance> {
    path_token.prefix.strip_prefix("~/")?;
    let home_dir = home_dir?;
    let completed = display_replacement.strip_prefix("~/")?;
    let mut absolute = home_dir.join(completed).to_string_lossy().into_owned();
    if display_replacement.ends_with('/') && !absolute.ends_with('/') {
        absolute.push('/');
    }
    Some(CompletionAcceptance {
        cursor: before.len() + absolute.len(),
        replacement: format!("{before}{absolute}{after}"),
    })
}

const COMPLETION_MENU_MAX_HEIGHT_PERCENT: usize = 30;

/// Renders the completion menu as a [`StyledBlock`]: each candidate
/// on its own line, with the selected entry highlighted.
pub fn render_menu_block(
    view: &CompletionView,
    theme: &Theme,
    terminal_width: usize,
    terminal_height: usize,
) -> StyledBlock {
    render_menu_block_with_max_rows(
        view,
        theme,
        terminal_width,
        completion_menu_max_rows(terminal_height),
    )
}

fn completion_menu_max_rows(terminal_height: usize) -> usize {
    (terminal_height * COMPLETION_MENU_MAX_HEIGHT_PERCENT / 100).max(1)
}

fn visible_candidate_range(view: &CompletionView, max_rows: usize) -> std::ops::Range<usize> {
    let total = view.candidates.len();
    let max_rows = max_rows.max(1).min(total.max(1));
    if total <= max_rows {
        return 0..total;
    }

    let selected = view.selected.unwrap_or(0).min(total - 1);
    let half = max_rows / 2;
    let start = selected.saturating_sub(half).min(total - max_rows);
    start..start + max_rows
}

struct MenuLineParts {
    label: String,
    padding: usize,
    description: String,
}

fn menu_line_parts(
    candidate: &Candidate,
    max_label_width: usize,
    terminal_width: usize,
) -> MenuLineParts {
    let inner_width = if terminal_width < 4 {
        terminal_width.max(1)
    } else {
        terminal_width.max(1).saturating_sub(4)
    };
    let label_budget = max_label_width.min(inner_width);
    let label = truncate_to_width(&candidate.label, label_budget);
    let label_width = display_width(label.as_str());
    let remaining = inner_width.saturating_sub(label_width);

    let mut padding = 0;
    let mut description = String::new();
    if !candidate.description.is_empty() && 0 < remaining {
        padding = (max_label_width.saturating_sub(label_width) + 2).min(remaining);
        let desc_budget = remaining.saturating_sub(padding);
        if 0 < desc_budget {
            description = truncate_to_width(&candidate.description, desc_budget);
        }
    }

    MenuLineParts {
        label,
        padding,
        description,
    }
}

fn render_menu_block_with_max_rows(
    view: &CompletionView,
    theme: &Theme,
    terminal_width: usize,
    max_rows: usize,
) -> StyledBlock {
    let selected_style = resolve::resolve(theme, tau_themes::names::COMPLETION_SELECTED);
    let label_style = resolve::resolve(theme, tau_themes::names::COMPLETION_LABEL);
    let desc_style = resolve::resolve(theme, tau_themes::names::COMPLETION_DESC);

    let visible = visible_candidate_range(view, max_rows);
    let max_label_width = view.candidates[visible.clone()]
        .iter()
        .map(|c| display_width(c.label.as_str()))
        .max()
        .unwrap_or(0);

    let mut spans: Vec<Span> = Vec::new();
    for (row, i) in visible.enumerate() {
        let candidate = &view.candidates[i];
        if 0 < row {
            spans.push(Span::plain("\n"));
        }

        let is_selected = view.selected == Some(i);
        let parts = menu_line_parts(candidate, max_label_width, terminal_width);

        let line_text = if terminal_width < 4 {
            truncate_to_width(&parts.label, terminal_width)
        } else if parts.description.is_empty() {
            format!("  {}  ", parts.label)
        } else {
            format!(
                "  {}{:padding$}{}  ",
                parts.label,
                "",
                parts.description,
                padding = parts.padding,
            )
        };

        if terminal_width < 4 {
            spans.push(Span::plain(line_text));
        } else if is_selected {
            spans.push(Span::new(line_text, selected_style));
        } else {
            spans.push(Span::plain("  "));
            spans.push(Span::new(parts.label, label_style));
            if !parts.description.is_empty() {
                spans.push(Span::plain(format!(
                    "{:padding$}",
                    "",
                    padding = parts.padding
                )));
                spans.push(Span::new(parts.description, desc_style));
            }
            spans.push(Span::plain("  "));
        }
    }

    StyledBlock::new(StyledText::from(spans))
}

#[cfg(test)]
#[path = "completion_rule_tests.rs"]
mod completion_rule_tests;
#[cfg(test)]
mod render_tests;