agentmux 0.2.0

Multi-agent coordination runtime with inter-agent messaging across CLI, MCP, tmux, and ACP.
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
//! Bundle configuration loading and sender-association helpers.

use std::{
    collections::{HashMap, HashSet},
    error::Error,
    fmt::{Display, Formatter},
    fs, io,
    path::{Path, PathBuf},
};

use regex::Regex;
use serde::{Deserialize, Serialize};

const FORMAT_VERSION: u32 = 1;
const CODERS_FILE: &str = "coders.toml";
const BUNDLES_DIRECTORY: &str = "bundles";
const BUNDLE_EXTENSION: &str = "toml";
const TUI_FILE: &str = "tui.toml";
const POLICIES_FILE: &str = "policies.toml";
const SESSION_ID_LENGTH_MAX: usize = 31;
pub const RESERVED_GROUP_ALL: &str = "ALL";

/// One configured bundle member.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct BundleMember {
    /// Canonical routing identity from `[[sessions]].id`.
    pub id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional human-facing recipient label from `[[sessions]].name`.
    pub name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub working_directory: Option<PathBuf>,
    pub target: TargetConfiguration,
    /// Optional persistent agent session handle sourced from
    /// `[[sessions]].coder-session-id` (not from `[[coders]]`).
    /// ACP delivery uses this to select `session/load` vs `session/new`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub coder_session_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policy_id: Option<String>,
}

/// Optional prompt-readiness template for one bundle member.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct PromptReadinessTemplate {
    pub prompt_regex: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub inspect_lines: Option<usize>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub input_idle_cursor_column: Option<usize>,
}

/// Validated runtime target configuration for one bundle member.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case", tag = "transport", content = "config")]
pub enum TargetConfiguration {
    Tmux(TmuxTargetConfiguration),
    Acp(AcpTargetConfiguration),
}

/// Tmux transport configuration for one bundle member.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct TmuxTargetConfiguration {
    pub start_command: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prompt_readiness: Option<PromptReadinessTemplate>,
}

/// ACP transport configuration for one bundle member.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct AcpTargetConfiguration {
    pub channel: AcpChannel,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub turn_timeout_ms: Option<u64>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub headers: Vec<NameValueEntry>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub environment: Vec<NameValueEntry>,
}

/// Configuration for one named bundle.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct BundleConfiguration {
    pub schema_version: String,
    pub bundle_name: String,
    pub autostart: bool,
    pub groups: Vec<String>,
    pub members: Vec<BundleMember>,
}

/// Group membership metadata for one bundle.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BundleGroupMembership {
    pub bundle_name: String,
    pub autostart: bool,
    pub groups: Vec<String>,
}

/// One global TUI session entry from `tui.toml`.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct TuiSession {
    /// Selector identity used by CLI (`--as-session`).
    pub id: String,
    /// Optional operator-facing label.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Policy preset reference.
    pub policy_id: String,
}

/// Global TUI configuration loaded from `tui.toml`.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct TuiConfiguration {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_bundle: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_session: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub sessions: Vec<TuiSession>,
}

impl TuiConfiguration {
    #[must_use]
    pub fn session_by_id(&self, selector: &str) -> Option<&TuiSession> {
        self.sessions.iter().find(|session| session.id == selector)
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
struct RawCodersFile {
    format_version: u32,
    #[serde(default)]
    coders: Vec<RawCoder>,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
struct RawCoder {
    id: String,
    #[serde(default)]
    tmux: Option<RawTmuxTarget>,
    #[serde(default)]
    acp: Option<RawAcpTarget>,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
struct RawTmuxTarget {
    initial_command: String,
    resume_command: String,
    #[serde(default)]
    prompt_regex: Option<String>,
    #[serde(default)]
    prompt_inspect_lines: Option<usize>,
    #[serde(default)]
    prompt_idle_column: Option<usize>,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
struct RawAcpTarget {
    channel: AcpChannel,
    #[serde(default)]
    command: Option<String>,
    #[serde(default)]
    url: Option<String>,
    #[serde(default)]
    turn_timeout_ms: Option<u64>,
    #[serde(default)]
    headers: Vec<NameValueEntry>,
    #[serde(default)]
    environment: Vec<NameValueEntry>,
}

#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct NameValueEntry {
    pub name: String,
    pub value: String,
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum AcpChannel {
    Stdio,
    Http,
}

#[derive(Clone, Debug)]
struct Coder {
    target: CoderTarget,
}

#[derive(Clone, Debug)]
enum CoderTarget {
    Tmux(TmuxTarget),
    Acp(AcpTarget),
}

#[derive(Clone, Debug)]
struct TmuxTarget {
    initial_command: String,
    resume_command: String,
    prompt_regex: Option<String>,
    prompt_inspect_lines: Option<usize>,
    prompt_idle_column: Option<usize>,
}

#[derive(Clone, Debug)]
struct AcpTarget {
    channel: AcpChannel,
    command: Option<String>,
    url: Option<String>,
    turn_timeout_ms: Option<u64>,
    headers: Vec<NameValueEntry>,
    environment: Vec<NameValueEntry>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
struct RawBundleFile {
    format_version: u32,
    #[serde(default)]
    autostart: bool,
    #[serde(default)]
    groups: Vec<String>,
    #[serde(default)]
    sessions: Vec<RawSession>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
struct RawTuiFile {
    #[serde(default)]
    default_bundle: Option<String>,
    #[serde(default)]
    default_session: Option<String>,
    #[serde(default)]
    sessions: Vec<RawTuiSession>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
struct RawTuiSession {
    id: String,
    #[serde(default)]
    name: Option<String>,
    policy: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
struct RawPoliciesFile {
    format_version: u32,
    #[serde(default, rename = "default")]
    _default: Option<String>,
    #[serde(default)]
    policies: Vec<RawPolicyPreset>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
struct RawPolicyPreset {
    id: String,
    #[serde(default, rename = "description")]
    _description: Option<String>,
    #[serde(default, rename = "controls")]
    _controls: Option<toml::Value>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
struct RawSession {
    id: String,
    #[serde(default)]
    name: Option<String>,
    directory: PathBuf,
    coder: String,
    #[serde(default)]
    coder_session_id: Option<String>,
    #[serde(default)]
    policy: Option<String>,
}

/// Configuration load/validation failures.
#[derive(Debug)]
pub enum ConfigurationError {
    UnknownBundle {
        bundle_name: String,
        path: PathBuf,
    },
    AmbiguousSender {
        working_directory: PathBuf,
        matches: Vec<String>,
    },
    InvalidConfiguration {
        path: PathBuf,
        message: String,
    },
    InvalidGroupName {
        path: PathBuf,
        group_name: String,
    },
    ReservedGroupName {
        path: PathBuf,
        group_name: String,
    },
    Io {
        context: String,
        source: io::Error,
    },
}

impl ConfigurationError {
    fn io(context: impl Into<String>, source: io::Error) -> Self {
        Self::Io {
            context: context.into(),
            source,
        }
    }
}

impl Display for ConfigurationError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::UnknownBundle { bundle_name, path } => write!(
                formatter,
                "bundle '{}' is not configured at {}",
                bundle_name,
                path.display()
            ),
            Self::AmbiguousSender {
                working_directory,
                matches,
            } => write!(
                formatter,
                "ambiguous sender for {} matched sessions: {}",
                working_directory.display(),
                matches.join(", ")
            ),
            Self::InvalidConfiguration { path, message } => {
                write!(
                    formatter,
                    "invalid bundle configuration {}: {}",
                    path.display(),
                    message
                )
            }
            Self::InvalidGroupName { path, group_name } => write!(
                formatter,
                "invalid group name '{}' in {}",
                group_name,
                path.display()
            ),
            Self::ReservedGroupName { path, group_name } => write!(
                formatter,
                "group name '{}' is reserved in {}",
                group_name,
                path.display()
            ),
            Self::Io { context, source } => write!(formatter, "{context}: {source}"),
        }
    }
}

impl Error for ConfigurationError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            _ => None,
        }
    }
}

/// Resolves path to shared coder definitions.
pub fn coders_configuration_path(configuration_root: &Path) -> PathBuf {
    configuration_root.join(CODERS_FILE)
}

/// Resolves path to one bundle definition file.
pub fn bundle_configuration_path(configuration_root: &Path, bundle_name: &str) -> PathBuf {
    configuration_root
        .join(BUNDLES_DIRECTORY)
        .join(format!("{bundle_name}.{BUNDLE_EXTENSION}"))
}

/// Resolves path to global TUI configuration file.
pub fn tui_configuration_path(configuration_root: &Path) -> PathBuf {
    configuration_root.join(TUI_FILE)
}

/// Resolves path to authorization policy presets file.
pub fn policies_configuration_path(configuration_root: &Path) -> PathBuf {
    configuration_root.join(POLICIES_FILE)
}

/// Loads bundle-group membership metadata for configured bundles.
///
/// # Errors
///
/// Returns `ConfigurationError` for malformed bundle files and I/O failures.
pub fn load_bundle_group_memberships(
    configuration_root: &Path,
) -> Result<Vec<BundleGroupMembership>, ConfigurationError> {
    let bundles_directory = configuration_root.join(BUNDLES_DIRECTORY);
    if !bundles_directory.exists() {
        return Ok(Vec::new());
    }
    let mut bundle_names = fs::read_dir(&bundles_directory)
        .map_err(|source| {
            ConfigurationError::io(
                format!("read bundle directory {}", bundles_directory.display()),
                source,
            )
        })?
        .filter_map(|entry| entry.ok())
        .filter_map(|entry| entry.path().file_name().map(ToOwned::to_owned))
        .filter_map(|name| name.to_str().map(ToOwned::to_owned))
        .filter(|name| name.ends_with(".toml"))
        .filter_map(|name| name.strip_suffix(".toml").map(ToOwned::to_owned))
        .collect::<Vec<_>>();
    bundle_names.sort_unstable();

    let mut memberships = Vec::with_capacity(bundle_names.len());
    for bundle_name in bundle_names {
        let bundle_path = bundle_configuration_path(configuration_root, &bundle_name);
        let bundle_raw = fs::read_to_string(&bundle_path).map_err(|source| {
            ConfigurationError::io(format!("read {}", bundle_path.display()), source)
        })?;
        let bundle_file = toml::from_str::<RawBundleFile>(&bundle_raw).map_err(|source| {
            ConfigurationError::InvalidConfiguration {
                path: bundle_path.clone(),
                message: source.to_string(),
            }
        })?;
        validate_format_version(bundle_file.format_version, &bundle_path)?;
        if bundle_file.sessions.is_empty() {
            continue;
        }
        let groups = validate_bundle_groups(&bundle_file.groups, &bundle_path)?;
        memberships.push(BundleGroupMembership {
            bundle_name,
            autostart: bundle_file.autostart,
            groups,
        });
    }
    Ok(memberships)
}

/// Loads one bundle configuration and applies schema validation.
///
/// # Errors
///
/// Returns `ConfigurationError` for unknown bundles, invalid schema, and I/O.
pub fn load_bundle_configuration(
    configuration_root: &Path,
    bundle_name: &str,
) -> Result<BundleConfiguration, ConfigurationError> {
    let coders_path = coders_configuration_path(configuration_root);
    let bundle_path = bundle_configuration_path(configuration_root, bundle_name);

    if !bundle_path.exists() {
        return Err(ConfigurationError::UnknownBundle {
            bundle_name: bundle_name.to_string(),
            path: bundle_path,
        });
    }

    let coders_raw = fs::read_to_string(&coders_path).map_err(|source| {
        ConfigurationError::io(format!("read {}", coders_path.display()), source)
    })?;
    let bundle_raw = fs::read_to_string(&bundle_path).map_err(|source| {
        ConfigurationError::io(format!("read {}", bundle_path.display()), source)
    })?;

    let coders_file = toml::from_str::<RawCodersFile>(&coders_raw).map_err(|source| {
        ConfigurationError::InvalidConfiguration {
            path: coders_path.clone(),
            message: source.to_string(),
        }
    })?;
    let bundle_file = toml::from_str::<RawBundleFile>(&bundle_raw).map_err(|source| {
        ConfigurationError::InvalidConfiguration {
            path: bundle_path.clone(),
            message: source.to_string(),
        }
    })?;

    validate_loaded_configuration(
        bundle_name,
        coders_file,
        &coders_path,
        bundle_file,
        &bundle_path,
    )
}

/// Loads global TUI configuration from `<config-root>/tui.toml`.
///
/// # Errors
///
/// Returns `ConfigurationError` when the file exists but is malformed.
pub fn load_tui_configuration(
    configuration_root: &Path,
) -> Result<Option<TuiConfiguration>, ConfigurationError> {
    load_tui_configuration_file(&tui_configuration_path(configuration_root))
}

/// Loads global TUI configuration from an explicit file path.
///
/// # Errors
///
/// Returns `ConfigurationError` when the file exists but is malformed.
pub fn load_tui_configuration_file(
    path: &Path,
) -> Result<Option<TuiConfiguration>, ConfigurationError> {
    if !path.exists() {
        return Ok(None);
    }
    let raw = fs::read_to_string(path)
        .map_err(|source| ConfigurationError::io(format!("read {}", path.display()), source))?;
    let parsed = toml::from_str::<RawTuiFile>(&raw).map_err(|source| {
        ConfigurationError::InvalidConfiguration {
            path: path.to_path_buf(),
            message: source.to_string(),
        }
    })?;

    let default_bundle = parsed
        .default_bundle
        .as_deref()
        .map(normalize_field)
        .filter(|value| !value.is_empty())
        .map(ToString::to_string);
    let default_session = parsed
        .default_session
        .as_deref()
        .map(normalize_field)
        .filter(|value| !value.is_empty())
        .map(ToString::to_string);
    let sessions = validate_tui_sessions(parsed.sessions, path)?;

    Ok(Some(TuiConfiguration {
        default_bundle,
        default_session,
        sessions,
    }))
}

/// Loads known policy preset identifiers from `<config-root>/policies.toml`.
///
/// # Errors
///
/// Returns `ConfigurationError` when the artifact is missing or malformed.
pub fn load_policy_ids(configuration_root: &Path) -> Result<HashSet<String>, ConfigurationError> {
    let path = policies_configuration_path(configuration_root);
    let raw = fs::read_to_string(&path)
        .map_err(|source| ConfigurationError::io(format!("read {}", path.display()), source))?;
    let parsed = toml::from_str::<RawPoliciesFile>(&raw).map_err(|source| {
        ConfigurationError::InvalidConfiguration {
            path: path.clone(),
            message: source.to_string(),
        }
    })?;
    validate_format_version(parsed.format_version, &path)?;

    let mut unique = HashSet::<String>::new();
    for policy in parsed.policies {
        let policy_id = normalize_field(policy.id.as_str());
        if policy_id.is_empty() {
            return Err(ConfigurationError::InvalidConfiguration {
                path: path.clone(),
                message: "policy id must be non-empty".to_string(),
            });
        }
        if !unique.insert(policy_id.to_string()) {
            return Err(ConfigurationError::InvalidConfiguration {
                path: path.clone(),
                message: format!("duplicate policy id '{policy_id}'"),
            });
        }
    }
    Ok(unique)
}

/// Infers sender session from bundle member working-directory matches.
///
/// # Errors
///
/// Returns `ConfigurationError::AmbiguousSender` when more than one member
/// matches the same directory.
pub fn infer_sender_from_working_directory(
    bundle: &BundleConfiguration,
    working_directory: &Path,
) -> Result<Option<String>, ConfigurationError> {
    let target = canonicalize_best_effort(working_directory);
    let mut matches = Vec::new();

    for member in &bundle.members {
        let Some(member_directory) = member.working_directory.as_ref() else {
            continue;
        };
        if canonicalize_best_effort(member_directory) == target {
            matches.push(member.id.clone());
        }
    }

    match matches.len() {
        0 => Ok(None),
        1 => Ok(matches.pop()),
        _ => Err(ConfigurationError::AmbiguousSender {
            working_directory: target,
            matches,
        }),
    }
}

fn validate_loaded_configuration(
    expected_bundle_name: &str,
    coders_file: RawCodersFile,
    coders_path: &Path,
    bundle_file: RawBundleFile,
    bundle_path: &Path,
) -> Result<BundleConfiguration, ConfigurationError> {
    validate_format_version(coders_file.format_version, coders_path)?;
    validate_format_version(bundle_file.format_version, bundle_path)?;

    let coders = validate_coders(coders_file.coders, coders_path)?;

    let groups = validate_bundle_groups(&bundle_file.groups, bundle_path)?;

    if bundle_file.sessions.is_empty() {
        return Err(ConfigurationError::InvalidConfiguration {
            path: bundle_path.to_path_buf(),
            message: "sessions must contain at least one session".to_string(),
        });
    }

    let mut session_ids = HashSet::new();
    let mut session_names = HashSet::new();
    let mut members = Vec::with_capacity(bundle_file.sessions.len());

    for session in &bundle_file.sessions {
        let session_id = normalize_field(session.id.as_str());
        if session_id.is_empty() {
            return Err(ConfigurationError::InvalidConfiguration {
                path: bundle_path.to_path_buf(),
                message: "session id must be non-empty".to_string(),
            });
        }
        validate_session_id(bundle_path, session_id)?;
        if !session_ids.insert(session_id.to_string()) {
            return Err(ConfigurationError::InvalidConfiguration {
                path: bundle_path.to_path_buf(),
                message: format!("duplicate session id '{session_id}'"),
            });
        }

        let session_name = session
            .name
            .as_deref()
            .map(normalize_field)
            .filter(|value| !value.is_empty());
        if let Some(session_name) = session_name
            && !session_names.insert(session_name.to_string())
        {
            return Err(ConfigurationError::InvalidConfiguration {
                path: bundle_path.to_path_buf(),
                message: format!("duplicate session name '{session_name}'"),
            });
        }

        let coder_id = normalize_field(session.coder.as_str());
        let Some(coder) = coders.get(coder_id) else {
            return Err(ConfigurationError::InvalidConfiguration {
                path: bundle_path.to_path_buf(),
                message: format!(
                    "session '{}' references unknown coder '{}'",
                    session_id, coder_id
                ),
            });
        };

        if session.directory.as_os_str().is_empty() {
            return Err(ConfigurationError::InvalidConfiguration {
                path: bundle_path.to_path_buf(),
                message: format!("session '{}' directory must be non-empty", session_id),
            });
        }

        let coder_session_id = session
            .coder_session_id
            .as_deref()
            .map(normalize_field)
            .filter(|value| !value.is_empty());
        let policy_id = session
            .policy
            .as_deref()
            .map(normalize_field)
            .filter(|value| !value.is_empty())
            .map(ToString::to_string);
        let target = match &coder.target {
            CoderTarget::Tmux(target) => {
                let command_template = if coder_session_id.is_some() {
                    target.resume_command.as_str()
                } else {
                    target.initial_command.as_str()
                };
                let start_command = render_command_template(
                    command_template,
                    coder_session_id,
                    bundle_path,
                    session_id,
                )?;
                let prompt_readiness =
                    prompt_readiness_from_tmux_target(target, coders_path, session_id)?;
                TargetConfiguration::Tmux(TmuxTargetConfiguration {
                    start_command,
                    prompt_readiness,
                })
            }
            CoderTarget::Acp(target) => TargetConfiguration::Acp(AcpTargetConfiguration {
                channel: target.channel,
                command: target.command.clone(),
                url: target.url.clone(),
                turn_timeout_ms: target.turn_timeout_ms,
                headers: target.headers.clone(),
                environment: target.environment.clone(),
            }),
        };

        members.push(BundleMember {
            id: session_id.to_string(),
            name: session_name.map(ToString::to_string),
            working_directory: Some(session.directory.clone()),
            target,
            coder_session_id: coder_session_id.map(ToString::to_string),
            policy_id,
        });
    }

    Ok(BundleConfiguration {
        schema_version: FORMAT_VERSION.to_string(),
        bundle_name: expected_bundle_name.to_string(),
        autostart: bundle_file.autostart,
        groups,
        members,
    })
}

fn validate_tui_sessions(
    sessions: Vec<RawTuiSession>,
    path: &Path,
) -> Result<Vec<TuiSession>, ConfigurationError> {
    let mut unique = HashSet::<String>::new();
    let mut validated = Vec::<TuiSession>::with_capacity(sessions.len());
    for session in sessions {
        let selector_id = normalize_field(session.id.as_str());
        if selector_id.is_empty() {
            return Err(ConfigurationError::InvalidConfiguration {
                path: path.to_path_buf(),
                message: "tui session id must be non-empty".to_string(),
            });
        }
        validate_session_id(path, selector_id)?;
        if !unique.insert(selector_id.to_string()) {
            return Err(ConfigurationError::InvalidConfiguration {
                path: path.to_path_buf(),
                message: format!("duplicate tui session id '{selector_id}'"),
            });
        }

        let policy_id = normalize_field(session.policy.as_str());
        if policy_id.is_empty() {
            return Err(ConfigurationError::InvalidConfiguration {
                path: path.to_path_buf(),
                message: format!("tui session '{}' policy must be non-empty", selector_id),
            });
        }
        let name = session
            .name
            .as_deref()
            .map(normalize_field)
            .filter(|value| !value.is_empty())
            .map(ToString::to_string);

        validated.push(TuiSession {
            id: selector_id.to_string(),
            name,
            policy_id: policy_id.to_string(),
        });
    }
    Ok(validated)
}

fn validate_coders(
    coders: Vec<RawCoder>,
    coders_path: &Path,
) -> Result<HashMap<String, Coder>, ConfigurationError> {
    if coders.is_empty() {
        return Err(ConfigurationError::InvalidConfiguration {
            path: coders_path.to_path_buf(),
            message: "coders must contain at least one coder".to_string(),
        });
    }

    let mut unique = HashMap::new();
    for coder in coders {
        let coder_id = normalize_field(coder.id.as_str());
        if coder_id.is_empty() {
            return Err(ConfigurationError::InvalidConfiguration {
                path: coders_path.to_path_buf(),
                message: "coder id must be non-empty".to_string(),
            });
        }
        if unique.contains_key(coder_id) {
            return Err(ConfigurationError::InvalidConfiguration {
                path: coders_path.to_path_buf(),
                message: format!("duplicate coder id '{coder_id}'"),
            });
        }

        let target = match (coder.tmux, coder.acp) {
            (Some(tmux), None) => {
                CoderTarget::Tmux(validate_tmux_target(tmux, coders_path, coder_id)?)
            }
            (None, Some(acp)) => CoderTarget::Acp(validate_acp_target(acp, coders_path, coder_id)?),
            (None, None) => {
                return Err(ConfigurationError::InvalidConfiguration {
                    path: coders_path.to_path_buf(),
                    message: format!(
                        "coder '{}' must define exactly one target table ([coders.tmux] or [coders.acp])",
                        coder_id
                    ),
                });
            }
            (Some(_), Some(_)) => {
                return Err(ConfigurationError::InvalidConfiguration {
                    path: coders_path.to_path_buf(),
                    message: format!(
                        "coder '{}' defines multiple target tables; expected exactly one",
                        coder_id
                    ),
                });
            }
        };

        unique.insert(coder_id.to_string(), Coder { target });
    }

    Ok(unique)
}

fn validate_bundle_groups(
    groups: &[String],
    bundle_path: &Path,
) -> Result<Vec<String>, ConfigurationError> {
    let mut validated = Vec::<String>::with_capacity(groups.len());
    let mut seen = HashSet::<String>::new();
    for raw_group in groups {
        let group = normalize_field(raw_group.as_str());
        if group.is_empty() {
            return Err(ConfigurationError::InvalidGroupName {
                path: bundle_path.to_path_buf(),
                group_name: raw_group.clone(),
            });
        }
        if group == RESERVED_GROUP_ALL {
            return Err(ConfigurationError::ReservedGroupName {
                path: bundle_path.to_path_buf(),
                group_name: group.to_string(),
            });
        }
        if is_reserved_group_name(group) || !is_custom_group_name(group) {
            return Err(ConfigurationError::InvalidGroupName {
                path: bundle_path.to_path_buf(),
                group_name: group.to_string(),
            });
        }
        if seen.insert(group.to_string()) {
            validated.push(group.to_string());
        }
    }
    Ok(validated)
}

fn is_reserved_group_name(group: &str) -> bool {
    group.chars().all(|character| {
        character.is_ascii_uppercase() || character.is_ascii_digit() || character == '_'
    })
}

fn is_custom_group_name(group: &str) -> bool {
    group.chars().all(|character| {
        character.is_ascii_lowercase()
            || character.is_ascii_digit()
            || character == '_'
            || character == '-'
    })
}

fn validate_format_version(version: u32, path: &Path) -> Result<(), ConfigurationError> {
    if version == FORMAT_VERSION {
        return Ok(());
    }
    Err(ConfigurationError::InvalidConfiguration {
        path: path.to_path_buf(),
        message: format!("unsupported format-version '{version}'"),
    })
}

fn render_command_template(
    template: &str,
    coder_session_id: Option<&str>,
    path: &Path,
    session_id: &str,
) -> Result<String, ConfigurationError> {
    let mut rendered = template.to_string();

    if rendered.contains("{coder-session-id}") {
        let Some(coder_session_id) = coder_session_id else {
            return Err(ConfigurationError::InvalidConfiguration {
                path: path.to_path_buf(),
                message: format!(
                    "session '{}' requires coder-session-id for template",
                    session_id
                ),
            });
        };
        rendered = rendered.replace("{coder-session-id}", coder_session_id);
    }

    let placeholder_regex = Regex::new(r"\{[a-z][a-z0-9-]*\}").map_err(|source| {
        ConfigurationError::InvalidConfiguration {
            path: path.to_path_buf(),
            message: format!("internal placeholder regex failure: {source}"),
        }
    })?;
    if let Some(found) = placeholder_regex.find(rendered.as_str()) {
        return Err(ConfigurationError::InvalidConfiguration {
            path: path.to_path_buf(),
            message: format!(
                "session '{}' template has unknown placeholder '{}'",
                session_id,
                found.as_str()
            ),
        });
    }

    if normalize_field(rendered.as_str()).is_empty() {
        return Err(ConfigurationError::InvalidConfiguration {
            path: path.to_path_buf(),
            message: format!("session '{}' resolved command is empty", session_id),
        });
    }
    Ok(rendered)
}

fn validate_tmux_target(
    target: RawTmuxTarget,
    coders_path: &Path,
    coder_id: &str,
) -> Result<TmuxTarget, ConfigurationError> {
    if normalize_field(target.initial_command.as_str()).is_empty() {
        return Err(ConfigurationError::InvalidConfiguration {
            path: coders_path.to_path_buf(),
            message: format!(
                "coder '{}' tmux initial-command must be non-empty",
                coder_id
            ),
        });
    }
    if normalize_field(target.resume_command.as_str()).is_empty() {
        return Err(ConfigurationError::InvalidConfiguration {
            path: coders_path.to_path_buf(),
            message: format!("coder '{}' tmux resume-command must be non-empty", coder_id),
        });
    }

    if let Some(prompt_regex) = target.prompt_regex.as_deref() {
        if normalize_field(prompt_regex).is_empty() {
            return Err(ConfigurationError::InvalidConfiguration {
                path: coders_path.to_path_buf(),
                message: format!(
                    "coder '{}' tmux prompt-regex must be non-empty when set",
                    coder_id
                ),
            });
        }
        compile_prompt_regex(prompt_regex, coders_path, coder_id, "tmux prompt-regex")?;
    }

    if matches!(target.prompt_inspect_lines, Some(0)) {
        return Err(ConfigurationError::InvalidConfiguration {
            path: coders_path.to_path_buf(),
            message: format!(
                "coder '{}' tmux prompt-inspect-lines must be greater than zero",
                coder_id
            ),
        });
    }

    Ok(TmuxTarget {
        initial_command: target.initial_command,
        resume_command: target.resume_command,
        prompt_regex: target.prompt_regex,
        prompt_inspect_lines: target.prompt_inspect_lines,
        prompt_idle_column: target.prompt_idle_column,
    })
}

fn validate_acp_target(
    target: RawAcpTarget,
    coders_path: &Path,
    coder_id: &str,
) -> Result<AcpTarget, ConfigurationError> {
    if matches!(target.turn_timeout_ms, Some(0)) {
        return Err(ConfigurationError::InvalidConfiguration {
            path: coders_path.to_path_buf(),
            message: format!(
                "coder '{}' ACP turn-timeout-ms must be greater than zero",
                coder_id
            ),
        });
    }

    match target.channel {
        AcpChannel::Stdio => {
            let Some(command) = target.command.as_deref() else {
                return Err(ConfigurationError::InvalidConfiguration {
                    path: coders_path.to_path_buf(),
                    message: format!(
                        "coder '{}' ACP stdio target requires non-empty command",
                        coder_id
                    ),
                });
            };
            if normalize_field(command).is_empty() {
                return Err(ConfigurationError::InvalidConfiguration {
                    path: coders_path.to_path_buf(),
                    message: format!(
                        "coder '{}' ACP stdio target requires non-empty command",
                        coder_id
                    ),
                });
            }
            if target.url.is_some() {
                return Err(ConfigurationError::InvalidConfiguration {
                    path: coders_path.to_path_buf(),
                    message: format!("coder '{}' ACP stdio target must not set url", coder_id),
                });
            }
            if !target.headers.is_empty() {
                return Err(ConfigurationError::InvalidConfiguration {
                    path: coders_path.to_path_buf(),
                    message: format!("coder '{}' ACP stdio target must not set headers", coder_id),
                });
            }
        }
        AcpChannel::Http => {
            let Some(url) = target.url.as_deref() else {
                return Err(ConfigurationError::InvalidConfiguration {
                    path: coders_path.to_path_buf(),
                    message: format!(
                        "coder '{}' ACP http target requires non-empty url",
                        coder_id
                    ),
                });
            };
            if normalize_field(url).is_empty() {
                return Err(ConfigurationError::InvalidConfiguration {
                    path: coders_path.to_path_buf(),
                    message: format!(
                        "coder '{}' ACP http target requires non-empty url",
                        coder_id
                    ),
                });
            }
            if target.command.is_some() {
                return Err(ConfigurationError::InvalidConfiguration {
                    path: coders_path.to_path_buf(),
                    message: format!(
                        "coder '{}' ACP http target must not set stdio-only fields",
                        coder_id
                    ),
                });
            }
            validate_name_value_entries(&target.headers, coders_path, coder_id, "headers")?;
        }
    }

    validate_name_value_entries(&target.environment, coders_path, coder_id, "environment")?;

    Ok(AcpTarget {
        channel: target.channel,
        command: target.command,
        url: target.url,
        turn_timeout_ms: target.turn_timeout_ms,
        headers: target.headers,
        environment: target.environment,
    })
}

fn validate_name_value_entries(
    entries: &[NameValueEntry],
    path: &Path,
    coder_id: &str,
    field_name: &str,
) -> Result<(), ConfigurationError> {
    for (index, entry) in entries.iter().enumerate() {
        if normalize_field(entry.name.as_str()).is_empty() {
            return Err(ConfigurationError::InvalidConfiguration {
                path: path.to_path_buf(),
                message: format!(
                    "coder '{}' {} entry {} has empty name",
                    coder_id, field_name, index
                ),
            });
        }
        if normalize_field(entry.value.as_str()).is_empty() {
            return Err(ConfigurationError::InvalidConfiguration {
                path: path.to_path_buf(),
                message: format!(
                    "coder '{}' {} entry {} has empty value",
                    coder_id, field_name, index
                ),
            });
        }
    }
    Ok(())
}

fn prompt_readiness_from_tmux_target(
    target: &TmuxTarget,
    path: &Path,
    session_id: &str,
) -> Result<Option<PromptReadinessTemplate>, ConfigurationError> {
    let Some(prompt_regex) = target.prompt_regex.as_deref() else {
        return Ok(None);
    };
    compile_prompt_regex(prompt_regex, path, session_id, "prompt-regex")?;
    Ok(Some(PromptReadinessTemplate {
        prompt_regex: prompt_regex.to_string(),
        inspect_lines: target.prompt_inspect_lines,
        input_idle_cursor_column: target.prompt_idle_column,
    }))
}

fn compile_prompt_regex(
    pattern: &str,
    path: &Path,
    session_id: &str,
    field_name: &str,
) -> Result<(), ConfigurationError> {
    Regex::new(pattern)
        .map(|_| ())
        .map_err(|source| ConfigurationError::InvalidConfiguration {
            path: path.to_path_buf(),
            message: format!("invalid {field_name} for session/coder '{session_id}': {source}"),
        })
}

fn normalize_field(value: &str) -> &str {
    value.trim()
}

fn validate_session_id(path: &Path, session_id: &str) -> Result<(), ConfigurationError> {
    let mut characters = session_id.chars();
    let Some(first) = characters.next() else {
        return Err(ConfigurationError::InvalidConfiguration {
            path: path.to_path_buf(),
            message: "session id must be non-empty".to_string(),
        });
    };
    if !first.is_ascii_alphabetic() {
        return Err(ConfigurationError::InvalidConfiguration {
            path: path.to_path_buf(),
            message: format!(
                "session id '{}' must start with an ASCII alphabetic character",
                session_id
            ),
        });
    }
    if !characters
        .all(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'))
    {
        return Err(ConfigurationError::InvalidConfiguration {
            path: path.to_path_buf(),
            message: format!(
                "session id '{}' may only contain ASCII alphanumeric characters, '-' or '_'",
                session_id
            ),
        });
    }
    if session_id.len() > SESSION_ID_LENGTH_MAX {
        return Err(ConfigurationError::InvalidConfiguration {
            path: path.to_path_buf(),
            message: format!(
                "session id '{}' exceeds max length {}",
                session_id, SESSION_ID_LENGTH_MAX
            ),
        });
    }
    Ok(())
}

fn canonicalize_best_effort(path: &Path) -> PathBuf {
    if let Ok(value) = fs::canonicalize(path) {
        return value;
    }
    if path.is_absolute() {
        return path.to_path_buf();
    }
    if let Ok(current_directory) = std::env::current_dir() {
        return current_directory.join(path);
    }
    path.to_path_buf()
}