aft-base 0.67.1

Shared foundation for Agent Foundational Toolkit
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
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::PathBuf;

use serde::{Deserialize, Serialize};

pub const DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS: u64 = 3_000;
/// `auto`: on the production lane (Bionic / Qwen3-Embedding-0.6B) the model-card
/// instruction on queries only left concept MRR and exact recall flat within noise,
/// raised real-query MRR 0.182 -> 0.189, and cut the dense lane's no-vocabulary
/// admission from 59% to 49% of top-10 rows (docs/investigations/query-instruction-ab-2026-09.md).
/// Document vectors are untouched, so flipping this never rebuilds an index.
pub const DEFAULT_SEMANTIC_QUERY_INSTRUCTION: &str = "auto";
/// Verbatim retrieval task recommended by the Qwen3-Embedding model card:
/// <https://huggingface.co/Qwen/Qwen3-Embedding-0.6B#usage-tips>
pub const QWEN3_EMBEDDING_MODEL_CARD_RETRIEVAL_TASK: &str =
    "Given a web search query, retrieve relevant passages that answer the query";
pub const QWEN3_EMBEDDING_CODE_SEARCH_TASK: &str =
    "Given a code search query, retrieve relevant source code, symbols, and documentation";
pub const MIN_SEMANTIC_QUERY_TIMEOUT_MS: u64 = 500;
pub const MAX_SEMANTIC_QUERY_TIMEOUT_MS: u64 = 30_000;
pub(crate) const DEFAULT_INSPECT_DIAGNOSTICS_TIMEOUT_MS: u64 = 120_000;
pub const MIN_INSPECT_DIAGNOSTICS_TIMEOUT_MS: u64 = 10_000;
pub const MAX_INSPECT_DIAGNOSTICS_TIMEOUT_MS: u64 = 600_000;
pub const DEFAULT_INSPECT_TIER2_PASS_TIMEOUT_MS: u64 = 600_000;
pub const DEFAULT_BASH_WATCH_SYNC_MAX_MS: u64 = 120_000;
pub const MIN_BASH_WATCH_SYNC_MAX_MS: u64 = 1_000;
pub const MAX_BASH_WATCH_SYNC_MAX_MS: u64 = 1_800_000;
/// How long a delegated worker's wait on one command blocks before control
/// returns to the worker (`bash.worker_wait_max_ms`): any `bash_watch` wait,
/// or a blocking `bash` call (`wait: true`, or every foreground call
/// when `bash.subagent_background` is false), which then moves to the
/// background instead of being killed. The worker then
/// decides whether to wait again or kill the command, so a stuck command can
/// never hold a worker for longer than this.
pub const DEFAULT_BASH_WORKER_WAIT_MAX_MS: u64 = 1_800_000;
pub const DEFAULT_LINUX_SCOPE_MAX_RUNTIME_SECS: u64 = 86_400;
/// Smallest accepted `bash.worker_wait_max_ms`. A shorter limit would make a
/// worker re-wait (and re-read its whole context) every few seconds; a value
/// below it is a config error rather than a silent clamp.
pub const MIN_BASH_WORKER_WAIT_MAX_MS: u64 = 60_000;

/// Unbound-root artifact eviction idle window, in minutes.
pub const DEFAULT_IDLE_ROOT_TTL_MINUTES: u32 = 30;
pub const MIN_IDLE_ROOT_TTL_MINUTES: u32 = 5;
pub const MAX_IDLE_ROOT_TTL_MINUTES: u32 = 30;
/// Hours without use after which a checkout's in-memory index state is
/// dropped (`idle.checkout_hours`).
pub const DEFAULT_IDLE_CHECKOUT_HOURS: u32 = 168;
pub const MIN_IDLE_CHECKOUT_HOURS: u32 = 1;
pub const MAX_IDLE_CHECKOUT_HOURS: u32 = 24 * 365;
/// Language-server idle window, in minutes. Independent of artifact eviction.
pub const DEFAULT_LSP_IDLE_MINUTES: u32 = 60;
pub const MIN_LSP_IDLE_MINUTES: u32 = 5;
pub const MAX_LSP_IDLE_MINUTES: u32 = 1440;

const fn default_semantic_query_timeout_ms() -> u64 {
    DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS
}

const fn default_inspect_diagnostics_timeout_ms() -> u64 {
    DEFAULT_INSPECT_DIAGNOSTICS_TIMEOUT_MS
}

const fn default_inspect_tier2_pass_timeout_ms() -> u64 {
    DEFAULT_INSPECT_TIER2_PASS_TIMEOUT_MS
}

const fn default_bash_detach_on_user_message() -> bool {
    true
}

pub(crate) const fn default_bash_watch_sync_max_ms() -> u64 {
    DEFAULT_BASH_WATCH_SYNC_MAX_MS
}

pub(crate) const fn default_bash_worker_wait_max_ms() -> u64 {
    DEFAULT_BASH_WORKER_WAIT_MAX_MS
}

use crate::harness::Harness;

/// Open a configuration file for reading.
///
/// On Windows a plain open asks for read access only, and the file then
/// refuses to be replaced while this handle lives: an editor that saves by
/// writing a temporary file and renaming it over this path, or an `aft write`
/// replacing it, gets ERROR_ACCESS_DENIED (os error 5). A handle that shares
/// delete lets the replacement land; it reaches the old file's bytes, which is
/// what a reader already under way should see. Config files are read and
/// released quickly, so this window is small either way.
///
/// Prefer this over `std::fs::read_to_string` for any file a user or tool may
/// rewrite while AFT runs: the user and project config files.
pub fn open_config_file(path: &std::path::Path) -> std::io::Result<std::fs::File> {
    let mut options = std::fs::OpenOptions::new();
    options.read(true);
    #[cfg(windows)]
    {
        use std::os::windows::fs::OpenOptionsExt;
        const FILE_SHARE_READ: u32 = 0x0000_0001;
        const FILE_SHARE_WRITE: u32 = 0x0000_0002;
        const FILE_SHARE_DELETE: u32 = 0x0000_0004;
        options.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE);
    }
    options.open(path)
}

/// Idle reclamation windows.
///
/// `root_ttl_minutes` controls when an unbound root's indexes are evicted.
/// Reclaimed indexes rebuild on the next request. `checkout_hours` controls
/// when a checkout that has not been used for that long counts as idle and
/// drops its in-memory index state; it replaces `views.idle_checkout_hours`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct IdleConfig {
    pub root_ttl_minutes: u32,
    pub checkout_hours: u32,
}

impl Default for IdleConfig {
    fn default() -> Self {
        Self {
            root_ttl_minutes: DEFAULT_IDLE_ROOT_TTL_MINUTES,
            checkout_hours: DEFAULT_IDLE_CHECKOUT_HOURS,
        }
    }
}

impl IdleConfig {
    pub fn root_ttl(&self) -> std::time::Duration {
        std::time::Duration::from_secs(u64::from(self.root_ttl_minutes) * 60)
    }
}

/// The durable index families that a standing root may maintain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IndexKind {
    Search,
    Semantic,
    Callgraph,
}

impl IndexKind {
    pub const ALL: [Self; 3] = [Self::Search, Self::Semantic, Self::Callgraph];

    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Search => "search",
            Self::Semantic => "semantic",
            Self::Callgraph => "callgraph",
        }
    }

    pub fn from_name(name: &str) -> Option<Self> {
        match name {
            "search" => Some(Self::Search),
            "semantic" => Some(Self::Semantic),
            "callgraph" => Some(Self::Callgraph),
            _ => None,
        }
    }
}

/// One user-configured root whose literal path spelling is its durable identity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IndexRootConfig {
    /// The unmodified Unicode spelling supplied in `index.roots[].path`.
    pub path: String,
    /// Normalized selected index families, in fixed [`IndexKind::ALL`] order.
    pub indexes: Vec<IndexKind>,
}

/// User-tier standing-index configuration.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct IndexConfig {
    pub roots: Vec<IndexRootConfig>,
}

/// Expand the supported `~` forms before validating that a configured root is
/// absolute. The literal string is retained separately for durable identity.
pub fn expand_index_root_path(
    path: &str,
    home: Option<&std::path::Path>,
) -> Result<PathBuf, String> {
    expand_configured_absolute_path("index.roots", path, home)
}

/// Expand the supported `~` forms in `storage.cache_dir` and require the
/// result to be absolute.
pub fn expand_cache_dir_path(
    path: &str,
    home: Option<&std::path::Path>,
) -> Result<PathBuf, String> {
    expand_configured_absolute_path("storage.cache_dir", path, home)
}

/// Shared `~` expansion and absolute-path check for user-configured paths.
/// `key` is the setting's name as the user writes it, so a refusal names the
/// setting that actually holds the bad value.
fn expand_configured_absolute_path(
    key: &str,
    path: &str,
    home: Option<&std::path::Path>,
) -> Result<PathBuf, String> {
    let no_home = || format!("{key} path uses ~ but no home directory is available");
    let expanded = if path == "~" {
        home.ok_or_else(no_home)?.to_path_buf()
    } else if let Some(remainder) = path.strip_prefix("~/").or_else(|| path.strip_prefix("~\\")) {
        home.ok_or_else(no_home)?.join(remainder)
    } else {
        PathBuf::from(path)
    };

    if !expanded.is_absolute() {
        return Err(format!(
            "{key} path must be absolute after ~ expansion: {path:?}"
        ));
    }
    Ok(expanded)
}

/// Semantic backend selected by the currently resolved runtime configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum SemanticBackend {
    Fastembed,
    #[serde(rename = "openai_compatible")]
    OpenAiCompatible,
    Ollama,
    Synapse,
}

impl SemanticBackend {
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Fastembed => "fastembed",
            Self::OpenAiCompatible => "openai_compatible",
            Self::Ollama => "ollama",
            Self::Synapse => "synapse",
        }
    }

    pub fn from_name(name: &str) -> Option<Self> {
        match name {
            "fastembed" => Some(Self::Fastembed),
            "openai_compatible" => Some(Self::OpenAiCompatible),
            "ollama" => Some(Self::Ollama),
            "synapse" => Some(Self::Synapse),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SemanticBackendConfig {
    /// Runtime-only local model location selected with the artifact root.
    #[serde(skip)]
    pub local_cache_dir: Option<PathBuf>,
    pub backend: SemanticBackend,
    pub model: String,
    pub base_url: Option<String>,
    pub api_key_env: Option<String>,
    /// Per-request floor for background index builds. HTTP batches scale this
    /// deadline from a successful per-item latency EMA; interactive queries use
    /// `query_timeout_ms` instead.
    pub timeout_ms: u64,
    /// Deadline for one interactive query embedding request. Unlike `timeout_ms`,
    /// this budget never controls background index builds.
    #[serde(default = "default_semantic_query_timeout_ms")]
    pub query_timeout_ms: u64,
    /// Query-only task instruction. `auto` selects a model-family recipe, `off`
    /// sends bare queries, and any other value is used as literal task text.
    #[serde(default = "default_semantic_query_instruction")]
    pub query_instruction: String,
    pub max_batch_size: usize,
    /// Optional whole-row input budget for remote embedding backends. When absent,
    /// chunk construction retains the legacy MiniLM-era limits.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_input_tokens: Option<usize>,
    /// Maximum number of project files to semantically index. Guards local
    /// fastembed memory (model + embeddings + batch buffers) on huge project
    /// roots; remote backends that embed server-side can raise it freely.
    pub max_files: usize,
    /// User-tier SubC connection file used only by the Synapse embedding backend.
    #[serde(skip)]
    pub subc_connection_file: Option<PathBuf>,
    /// Project-root and harness identity used to route Synapse management calls
    /// to the correct project and execution environment.
    #[serde(skip)]
    pub route_project_root: Option<PathBuf>,
    #[serde(skip)]
    pub route_harness: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct UserServerDef {
    pub id: String,
    pub extensions: Vec<String>,
    pub binary: String,
    pub args: Vec<String>,
    pub root_markers: Vec<String>,
    pub env: HashMap<String, String>,
    pub initialization_options: Option<serde_json::Value>,
    pub disabled: bool,
}

fn default_semantic_query_instruction() -> String {
    DEFAULT_SEMANTIC_QUERY_INSTRUCTION.to_string()
}

impl SemanticBackendConfig {
    pub fn resolved_query_instruction(&self) -> Option<&str> {
        if self.backend == SemanticBackend::Fastembed {
            return None;
        }
        match self.query_instruction.as_str() {
            "off" => None,
            "auto" if self.model.to_ascii_lowercase().contains("qwen3-embedding") => {
                Some(QWEN3_EMBEDDING_MODEL_CARD_RETRIEVAL_TASK)
            }
            "auto" => None,
            literal => Some(literal),
        }
    }
}

impl Default for SemanticBackendConfig {
    fn default() -> Self {
        Self {
            local_cache_dir: None,
            backend: SemanticBackend::Fastembed,
            model: DEFAULT_SEMANTIC_MODEL.to_string(),
            base_url: None,
            api_key_env: None,
            // Background HTTP batches treat this as a per-request floor and
            // scale it with measured per-item latency. Query requests have their
            // own short deadline below.
            timeout_ms: 25_000,
            query_timeout_ms: DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS,
            query_instruction: default_semantic_query_instruction(),
            max_batch_size: 64,
            max_input_tokens: None,
            max_files: 20_000,
            subc_connection_file: None,
            route_project_root: None,
            route_harness: None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct InspectConfig {
    pub enabled: bool,
    pub categories: InspectCategories,
    /// Deadline for the blocking LSP diagnostics phase of `aft_inspect`.
    #[serde(default = "default_inspect_diagnostics_timeout_ms")]
    pub diagnostics_timeout_ms: u64,
    /// Hard deadline for one Tier-2 pass, including projection and scanning.
    #[serde(default = "default_inspect_tier2_pass_timeout_ms")]
    pub tier2_pass_timeout_ms: u64,
    pub duplicates: InspectDuplicatesConfig,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct InspectDuplicatesConfig {
    pub expected_mirrors: Vec<[String; 2]>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct InspectCategories {
    pub diagnostics: bool,
    pub todos: bool,
    pub dead_code: bool,
    pub unused_exports: bool,
    pub duplicates: bool,
    pub cycles: bool,
    pub complexity: bool,
}

impl Default for InspectCategories {
    fn default() -> Self {
        Self {
            diagnostics: true,
            todos: true,
            dead_code: true,
            unused_exports: true,
            duplicates: true,
            cycles: true,
            complexity: true,
        }
    }
}

impl InspectCategories {
    pub const KEYS: [&'static str; 7] = [
        "diagnostics",
        "todos",
        "dead_code",
        "unused_exports",
        "duplicates",
        "cycles",
        "complexity",
    ];

    pub fn enabled(&self, category: crate::inspect_category::InspectCategory) -> bool {
        use crate::inspect_category::InspectCategory::*;
        match category {
            Diagnostics => self.diagnostics,
            Todos => self.todos,
            DeadCode => self.dead_code,
            UnusedExports => self.unused_exports,
            Duplicates => self.duplicates,
            Cycles => self.cycles,
            Complexity => self.complexity,
            // Metrics is internal, not a rendered category. Scoped file counts
            // need its scanner even when all user-facing categories are off.
            Metrics => true,
            _ => false,
        }
    }
}

impl InspectConfig {
    pub fn category_enabled(&self, category: crate::inspect_category::InspectCategory) -> bool {
        self.enabled && self.categories.enabled(category)
    }
}

impl Default for InspectConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            categories: InspectCategories::default(),
            diagnostics_timeout_ms: default_inspect_diagnostics_timeout_ms(),
            tier2_pass_timeout_ms: default_inspect_tier2_pass_timeout_ms(),
            duplicates: InspectDuplicatesConfig::default(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct BackupConfig {
    pub enabled: Option<bool>,
    pub max_depth: Option<usize>,
    pub max_file_size: Option<u64>,
}

impl Default for BackupConfig {
    fn default() -> Self {
        Self {
            enabled: Some(true),
            max_depth: Some(DEFAULT_MAX_UNDO_DEPTH),
            max_file_size: Some(DEFAULT_MAX_BACKUP_FILE_SIZE),
        }
    }
}

/// Binary configuration for the managed `gh` shim. Whether the shim is
/// interposed at all is `github.shim`; this block carries no enable state.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct GhShimConfig {
    /// Optional deployed or development AFT image used by managed shim entries.
    /// The running executable is used when this user-tier field is absent.
    pub binary_path: Option<PathBuf>,
}

/// GitHub integration gates resolved from the user-only `github` block.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct GithubConfig {
    /// Whether AFT interposes the governed `gh` shim in agent child PATHs.
    pub shim: bool,
    /// Whether structured `issue://` and `pr://` reads are enabled.
    pub read: bool,
    /// Whether issue and pull-request comment writes are enabled.
    pub write: bool,
}

impl Default for GithubConfig {
    fn default() -> Self {
        Self {
            shim: true,
            read: false,
            write: false,
        }
    }
}

/// Which background indexes are switched on. Each defaults on and builds
/// independently of which tools are registered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct IndexesConfig {
    /// Trigram index used by indexed grep/glob and the lexical search lane.
    pub trigram: bool,
    /// Semantic (embedding) index used by the semantic search lane.
    pub semantic: bool,
    /// Persisted call-graph store used by callgraph queries and enrichment.
    pub callgraph: bool,
}

impl Default for IndexesConfig {
    fn default() -> Self {
        Self {
            trigram: true,
            semantic: true,
            callgraph: true,
        }
    }
}

/// Git behavior applied only to AFT-spawned agent children.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct GitConfig {
    /// `off` (default), `auto`, or one explicit `Name <email>` identity.
    pub co_author: String,
}

impl Default for GitConfig {
    fn default() -> Self {
        Self {
            co_author: "off".to_string(),
        }
    }
}

/// Normalize configuration values into `off`, `auto`, or `Name <email>`.
pub fn normalize_git_co_author(value: &str) -> Option<String> {
    let value = value.trim();
    if matches!(value, "off" | "auto") {
        return Some(value.to_string());
    }
    if value.contains(['\n', '\r']) || !value.ends_with('>') {
        return None;
    }
    let open = value.rfind('<')?;
    if open == 0 || !value.as_bytes()[open - 1].is_ascii_whitespace() {
        return None;
    }
    let name = value[..open].trim();
    let email = value[open + 1..value.len() - 1].trim();
    if name.is_empty()
        || name.contains(['<', '>'])
        || email.is_empty()
        || !email.contains('@')
        || email
            .chars()
            .any(|character| character.is_whitespace() || matches!(character, '<' | '>'))
    {
        return None;
    }
    Some(value.to_string())
}

pub const DEFAULT_SEMANTIC_MODEL: &str = "all-MiniLM-L6-v2";

/// Which reranker, if any, reorders the head of `aft_search` results.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RerankBackendKind {
    Off,
    Onnx,
    Remote,
    Synapse,
}

impl RerankBackendKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Off => "off",
            Self::Onnx => "onnx",
            Self::Remote => "remote",
            Self::Synapse => "synapse",
        }
    }
}

/// The `search.rerank` block exactly as the tiers supplied it. Only parsing
/// and the user/project trust boundary happen in config resolution; defaults,
/// clamps and the reranked depth are decided by the search engine, so a change
/// to them is a ranking change measured by the search-quality gate.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct RerankConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub backend: Option<RerankBackendKind>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub endpoint: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub api_key_env: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_n: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
}

/// Search settings outside the semantic embedding backend.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct SearchConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rerank: Option<RerankConfig>,
}

impl Config {
    /// Optional artifact location for APIs that keep disk persistence opt-in.
    pub fn cache_storage_dir(&self) -> Option<PathBuf> {
        (self.cache_dir.is_some() || self.storage_dir.is_some())
            .then(|| crate::cache_location::cache_root(self))
    }
    pub fn semantic_backend_label(&self) -> &'static str {
        self.semantic.backend.as_str()
    }
}

/// Ordered from least to most restrictive for project-tier hardening.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "lowercase")]
pub enum SandboxMode {
    Off,
    Relaxed,
    Strict,
}

impl Default for SandboxMode {
    fn default() -> Self {
        Self::Strict
    }
}

impl std::fmt::Display for SandboxMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Off => "off",
            Self::Relaxed => "relaxed",
            Self::Strict => "strict",
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct SandboxRoles {
    pub worker: SandboxMode,
    pub head: SandboxMode,
}

impl Default for SandboxRoles {
    fn default() -> Self {
        Self {
            worker: SandboxMode::Relaxed,
            head: SandboxMode::Off,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct SandboxConfig {
    /// An authenticated Alfonso worker stamp selects worker; heads, standalone
    /// commands and unstamped first-party routes select head.
    pub profile: SandboxRoles,
    /// User-approved writable roots in addition to projects, task artifacts, and caches.
    pub write_allow: Vec<PathBuf>,
    /// Extra paths that native backends should deny reading.
    pub read_deny: Vec<PathBuf>,
}

impl SandboxConfig {
    pub fn head_enabled(&self) -> bool {
        self.profile.head != SandboxMode::Off
    }
}

/// Whether bash calls may ask to run on the remote build server (`runon`).
/// The user config turns it on; a project config may only turn it off.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct RemoteExecConfig {
    /// Offer `runon` to heads and accept their calls that set it. True only
    /// when the user config enables it and the project config does not turn
    /// it off.
    pub enabled: bool,
    /// The runner demand a `runon` call without specifics runs under. User
    /// configuration only; it never makes a call remote by itself.
    pub default_demand: Option<String>,
    /// The project config turned remote runs off, so a `runon` call in this
    /// project is refused with that reason rather than run anywhere.
    pub project_off: bool,
}

#[derive(
    Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum BashChangedFiles {
    #[default]
    Off,
    List,
    Diff,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct BashConfig {
    /// Optional watcher-based reporting after shell commands. Disabled by default.
    pub changed_files: BashChangedFiles,
    /// Runtime gate for every bash-execution operation, including the
    /// background companions. When false those operations report
    /// `bash_disabled`; registration is decided by `disabled_tools` alone.
    #[serde(default = "default_bash_enabled")]
    pub enabled: bool,
    /// Permit plugin-side break-glass execution when its AFT transport is unavailable.
    /// Rust accepts this for cross-language config parity but never acts on it.
    pub host_fallback: bool,
    /// Whether the hosting plugin detaches wait:true bash calls on user messages.
    /// Rust accepts this for cross-language config parity but never acts on it.
    #[serde(default = "default_bash_detach_on_user_message")]
    pub detach_on_user_message: bool,
    /// Append read-only database CLI schema hints after missing-schema errors.
    #[serde(default = "default_bash_enabled")]
    pub db_schema_hints: bool,
    /// Maximum synchronous `bash_watch` wait accepted by the hosting plugin.
    /// Rust accepts this for cross-language config parity but never acts on it.
    #[serde(default = "default_bash_watch_sync_max_ms")]
    pub watch_sync_max_ms: u64,
    /// Longest a delegated worker's wait on one command blocks before control
    /// returns to it; see [`DEFAULT_BASH_WORKER_WAIT_MAX_MS`]. The engine caps
    /// a worker's blocking bash call with it, and each wait a worker makes on a
    /// task without its own timeout pushes that task's default hard kill to at
    /// least this long after the wait.
    #[serde(default = "default_bash_worker_wait_max_ms")]
    pub worker_wait_max_ms: u64,
    /// Put Linux tool shells in transient user scopes when systemd is available.
    pub linux_scope: bool,
    /// User-only ceiling for daemon scopes, in seconds. Default: 86_400.
    pub linux_scope_max_runtime_secs: u64,
    /// Aggregate local-command memory ceiling in MiB; absent means unlimited.
    pub memory_limit_mib: Option<u64>,
    /// On macOS, agent commands become responsible for their own privacy permissions.
    /// Other platforms accept the setting but do not change process creation.
    pub disclaim_privacy: bool,
    /// Pi-only fallback gate for its optional PowerShell default tool. The Rust
    /// executor accepts this solely to keep shared config parsing in parity.
    pub powershell_tool: bool,
    /// Fixed environment entries merged into each local bash request. User
    /// configuration supplies these, and a trusted project's `bash.env` adds
    /// more in [`BashConfig::project_env`]; replies disclose names, never
    /// values.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub env: BTreeMap<String, String>,
    /// Validated project-tier `bash.env` values. The resolver never applies
    /// them: `commands/bash.rs` merges them only while the project root is on
    /// the filter trust list at the time of the call, and a name the user tier
    /// already sets keeps the user value.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub project_env: BTreeMap<String, String>,
    /// User-only names whose `bash.env` value is also sent to a `runon` build
    /// job. Every other configured name stays on this machine, and a project
    /// value is never sent.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub runon_env: Vec<String>,
}

/// User-only project environment selection, separate from shell tool switches.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct ShellConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[schemars(
        description = "Opt-in per-project environment export, run in the command workdir under its sandbox. Omit to preserve AFT's default environment. direnv is unsupported on Windows."
    )]
    pub env_provider: Option<ShellEnvProvider>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum ShellEnvProviderKind {
    Mise,
    Direnv,
    Custom,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ShellEnvProvider {
    pub kind: ShellEnvProviderKind,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(
        description = "Provider argv. Defaults to mise env --json or direnv export json; required for custom."
    )]
    pub command: Option<Vec<String>>,
    #[serde(default = "default_env_provider_timeout_ms")]
    pub timeout_ms: u64,
    #[serde(default)]
    #[schemars(
        description = "Custom provider watch files, checked at every ancestor. A custom provider with no watches runs on every call."
    )]
    pub watch: Vec<String>,
}

fn default_env_provider_timeout_ms() -> u64 {
    2000
}

impl ShellEnvProvider {
    pub fn validate(&self) -> Result<(), String> {
        if self.kind != ShellEnvProviderKind::Custom && !self.watch.is_empty() {
            return Err("invalid_security_config:shell.env_provider.watch".into());
        }
        if !(100..=10000).contains(&self.timeout_ms) {
            return Err("shell.env_provider.timeout_ms must be between 100 and 10000".into());
        }
        if self.kind == ShellEnvProviderKind::Custom && self.command.is_none() {
            return Err("shell.env_provider.command is required for custom".into());
        }
        if self.command.as_ref().is_some_and(|command| {
            command.is_empty()
                || command[0].is_empty()
                || command.iter().any(|arg| arg.contains('\0'))
        }) {
            return Err(
                "shell.env_provider.command must be a nonempty argv without NUL bytes".into(),
            );
        }
        if cfg!(windows) && self.kind == ShellEnvProviderKind::Direnv {
            return Err(
                "shell.env_provider: direnv is not supported on Windows; use mise or custom".into(),
            );
        }
        Ok(())
    }

    pub fn argv(&self) -> Vec<String> {
        self.command.clone().unwrap_or_else(|| match self.kind {
            ShellEnvProviderKind::Mise => vec!["mise".into(), "env".into(), "--json".into()],
            ShellEnvProviderKind::Direnv => vec!["direnv".into(), "export".into(), "json".into()],
            ShellEnvProviderKind::Custom => unreachable!("custom command validated at config load"),
        })
    }
}

impl Default for BashConfig {
    fn default() -> Self {
        Self {
            changed_files: BashChangedFiles::Off,
            enabled: true,
            host_fallback: false,
            detach_on_user_message: default_bash_detach_on_user_message(),
            db_schema_hints: true,
            watch_sync_max_ms: default_bash_watch_sync_max_ms(),
            worker_wait_max_ms: default_bash_worker_wait_max_ms(),
            linux_scope: true,
            linux_scope_max_runtime_secs: DEFAULT_LINUX_SCOPE_MAX_RUNTIME_SECS,
            memory_limit_mib: None,
            disclaim_privacy: false,
            powershell_tool: false,
            env: BTreeMap::new(),
            project_env: BTreeMap::new(),
            runon_env: Vec::new(),
        }
    }
}

/// `storage.cache_dir` as configured and the directory it named when the cache
/// root was prepared.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfiguredCacheDir {
    pub spelling: PathBuf,
    pub resolved: PathBuf,
}

impl BashConfig {
    /// The `bash.env` values a local command should start with, lowest tier
    /// first, tagged with the tier that supplied them.
    ///
    /// `project_trusted` is the caller's per-command trust decision; an
    /// untrusted project's map is not included at all. A name both tiers set
    /// keeps the user value: user names are often protective
    /// (`GIT_TERMINAL_PROMPT=0`), and a repository should add names rather
    /// than undo the user's.
    pub fn configured_env(
        &self,
        project_trusted: bool,
    ) -> Vec<crate::config_resolve::ConfiguredBashEnv> {
        let mut applied = Vec::new();
        if !self.env.is_empty() {
            applied.push(crate::config_resolve::ConfiguredBashEnv {
                names: self.env.clone(),
                tier: crate::bash_env::BashEnvTier::User,
            });
        }
        if project_trusted && !self.project_env.is_empty() {
            applied.push(crate::config_resolve::ConfiguredBashEnv {
                names: self.project_env.clone(),
                tier: crate::bash_env::BashEnvTier::Project,
            });
        }
        applied
    }

    /// Project names that a user value already covers, and so do not apply.
    pub fn shadowed_project_env(&self, project_trusted: bool) -> Vec<String> {
        if !project_trusted {
            return Vec::new();
        }
        self.project_env
            .keys()
            .filter(|name| self.env.contains_key(*name))
            .cloned()
            .collect()
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct DurabilityConfig {
    /// Flush the drive's volatile cache on macOS; plain fsync is the default.
    pub macos_full_sync: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
    /// Machine-local resource profile; only the user config base may select it.
    pub memory: Option<crate::memory_profile::MemoryMode>,
    /// User-selected file flush policy; only macOS has a full drive-flush option.
    pub durability: DurabilityConfig,
    /// Existing cache parent; AFT owns only its `aft` namespace. None preserves the storage-root layout.
    #[serde(skip_deserializing)]
    pub cache_dir: Option<PathBuf>,
    /// The spelling of `cache_dir` the user configured, kept once preparation
    /// replaces `cache_dir` with the directory it resolved to. A symlink in
    /// that spelling may later be repointed; every recheck resolves the
    /// configured spelling again so the change is noticed.
    #[serde(skip)]
    pub cache_dir_configured: Option<ConfiguredCacheDir>,
    /// Runtime validation failure; a configured unavailable root never falls back.
    #[serde(skip_deserializing)]
    pub cache_unavailable: Option<String>,
    /// The user document could not establish whether a cache volume was selected.
    #[serde(skip)]
    pub cache_config_unknown: Option<String>,
    /// The user config selects `storage.cache_dir.kind: main_disk`: caches deliberately
    /// return to the storage root even if it earlier used a cache directory.
    #[serde(skip)]
    pub cache_dir_opt_out: bool,
    /// Runtime cache-volume transition identity, used to retire old handles.
    #[serde(skip_deserializing)]
    pub cache_epoch: u64,
    #[serde(skip)]
    pub cache_lease: Option<std::sync::Arc<crate::cache_location::CacheLease>>,
    /// A trusted process lease, never accepted from configuration or tool input.
    #[serde(skip)]
    pub storage_lease: Option<std::sync::Arc<crate::cache_location::ProcessStorageLease>>,
    /// Root directory of the project being analyzed. `None` if not scoped.
    pub project_root: Option<PathBuf>,
    /// Legacy serialized setting (default: 1); validation does not consume it.
    pub validation_depth: u32,
    /// Hours before legacy backup-session maintenance may collect inactive history
    /// (default: 24). Named checkpoint retention is intentionally fixed at fourteen
    /// days and is not controlled by configuration.
    pub checkpoint_ttl_hours: u32,
    /// Legacy serialized setting (default: 10); symbol resolution does not consume it.
    pub max_symbol_depth: u32,
    /// Seconds before killing a formatter subprocess (default: 10).
    pub formatter_timeout_secs: u32,
    /// Seconds before killing a type-checker subprocess (default: 30).
    pub type_checker_timeout_secs: u32,
    /// Whether to auto-format files after edits (default: false).
    pub format_on_edit: bool,
    /// Whether `read`, `outline` and `zoom` accept a `ref` argument that reads
    /// a file as it is at a git revision (default: false). While it is off,
    /// the argument is neither advertised nor accepted.
    pub revision_reads: bool,
    /// Whether the hashline edit/read surface is enabled for eligible sessions.
    /// Resolved from the public `edit_mode` enum in aft.jsonc.
    pub hashline_enabled: bool,
    /// Optional automatic validation mode after edits (default: None, disabled).
    /// When "syntax", only tree-sitter parse check. When "full", runs type checker.
    pub validate_on_edit: Option<String>,
    /// Per-language formatter overrides. Keys: "typescript", "python", "rust", "go".
    /// Values: "biome", "oxfmt", "prettier", "deno", "ruff", "black", "rustfmt", "goimports", "gofmt", "none".
    pub formatter: HashMap<String, String>,
    /// Per-language type checker overrides. Keys: "typescript", "python", "rust", "go".
    /// Values: "tsc", "tsgo", "biome", "pyright", "ruff", "cargo", "go", "staticcheck", "none".
    pub checker: HashMap<String, String>,
    /// Whether to restrict file operations to within `project_root` (default: false).
    /// When true, write-capable commands reject paths outside the project root.
    pub restrict_to_project_root: bool,
    /// Background index switches (all default on).
    pub indexes: IndexesConfig,
    /// User-tier standing roots. Empty by default, so normal session indexing is unchanged.
    pub index: IndexConfig,
    /// Whether `aft_search` is registered, which is exactly "`aft_search` is not
    /// in `disabled_tools`". It is derived from the resolved disabled list and
    /// says nothing about index state or backend presence. Used only to pick
    /// the grep-rewrite footer. Not a capability gate.
    pub aft_search_registered: bool,
    /// Enable experimental bash command rewriting (default: false).
    pub experimental_bash_rewrite: bool,
    /// Enable experimental bash command compression (default: false).
    pub experimental_bash_compress: bool,
    /// Enable experimental bash background execution (default: false).
    pub experimental_bash_background: bool,
    /// Maximum number of background bash tasks allowed to run at once in one
    /// project root, shared by all its sessions (default: 8). Only background
    /// tasks count, whether local or remote: `background: true` and PTY launches, and foreground
    /// commands once promoted to the background. A background launch at the
    /// limit is refused with a list of the caller's own tasks holding slots
    /// (other sessions' are only counted); a foreground command always starts,
    /// and one promoted at the limit keeps
    /// running, so the count can briefly exceed the limit.
    pub max_background_bash_tasks: usize,
    /// Emit reminders for long-running bash tasks (default: true).
    pub bash_long_running_reminder_enabled: bool,
    /// Milliseconds between long-running bash reminders (default: 10 minutes).
    pub bash_long_running_reminder_interval_ms: u64,
    /// Milliseconds to wait before a foreground bash task is promoted to background handling.
    #[serde(skip, default = "default_foreground_wait_window_ms")]
    pub foreground_wait_window_ms: u64,
    /// Plugin-owned bash settings accepted by configure but inert in the engine.
    pub bash: BashConfig,
    pub shell: ShellConfig,
    /// Enable OpenCode-style bash permission prompts (default: false).
    pub bash_permissions: bool,
    /// Native sandbox policy for first-party bash and PTY processes.
    pub sandbox: SandboxConfig,
    /// Remote runs requested per bash call with `runon`. Off by default.
    pub remote_exec: RemoteExecConfig,
    /// Maximum file size to fully index in bytes (default: 1MB).
    pub search_index_max_file_size: u64,
    pub semantic: SemanticBackendConfig,
    /// `search.*` settings; today only the optional reranker.
    pub search: SearchConfig,
    pub inspect: InspectConfig,
    pub backup: BackupConfig,
    /// Resolved GitHub integration gates. User configuration only.
    pub github: GithubConfig,
    /// Binary configuration for the managed `gh` shim (no enable state).
    pub gh_shim: GhShimConfig,

    /// Git attribution for AFT-spawned agent children. Default off.
    pub git: GitConfig,
    /// Enable Astral ty as an experimental Python LSP server (default: false).
    pub experimental_lsp_ty: bool,
    /// User-defined LSP servers registered by the OpenCode plugin.
    pub lsp_servers: Vec<UserServerDef>,
    #[serde(skip)]
    #[doc(hidden)]
    pub invalid_lsp_initialization_options: Vec<String>,
    /// Lowercase LSP server IDs disabled by user config.
    pub disabled_lsp: HashSet<String>,
    /// Whether the system should request inline diagnostics after a tool call edits or writes a file.
    #[serde(skip)]
    pub diagnostics_on_edit: bool,
    pub lsp_idle_minutes: u32,
    pub lsp_idle_shutdown: bool,
    /// Maximum live language servers, including reserved starts.
    pub lsp_max_servers: usize,
    /// Trusted user ceiling before project tightening; not a configure input.
    #[serde(skip)]
    pub lsp_user_max_servers: Option<usize>,
    /// Extra directories to search when resolving LSP binaries.
    /// The plugin populates these from its own auto-install cache (e.g.
    /// `~/.cache/aft/lsp-packages/<pkg>/node_modules/.bin/`) so an LSP binary
    /// installed by AFT is discoverable without needing it on PATH.
    /// Resolution order: `<project_root>/node_modules/.bin/<bin>` →
    /// `lsp_paths_extra/<bin>` (in order) → PATH via `which`. Python-family
    /// servers additionally probe the selected workspace's `.venv`/`venv` first.
    pub lsp_paths_extra: Vec<PathBuf>,
    /// Binary names the hosting plugin knows how to auto-install.
    ///
    /// Built-in LSPs discovered from files only emit missing-binary warnings
    /// when their binary is in this set. User-configured `lsp_servers` keep
    /// warning unconditionally.
    pub lsp_auto_install_binaries: HashSet<String>,
    /// Binary names with plugin-managed auto-installs currently in flight.
    ///
    /// Missing-binary warnings are suppressed while the install is actively
    /// running; install failure reporting is handled by the plugin after the
    /// background work settles.
    pub lsp_inflight_installs: HashSet<String>,
    /// Persistent storage directory for indexes (trigram, semantic).
    /// Set by the plugin to the XDG-compliant path (e.g. ~/.local/share/opencode/storage/plugin/aft/).
    /// Falls back to ~/.cache/aft/ if not set.
    pub storage_dir: Option<PathBuf>,
    /// Allow URL-fetch commands to access private network hosts.
    /// Default false; hosting plugins only forward this from user-level config.
    pub url_fetch_allow_private: bool,
    /// Resolved agent-visible tool names that are not registered, sorted. A
    /// tool is registered exactly when its canonical name is absent from this
    /// list; the resolver always produces it explicitly (even when empty).
    pub disabled_tools: Vec<String>,
    /// Hosting harness identity supplied by configure.
    #[serde(default)]
    pub harness: Option<Harness>,
    /// Maximum number of (server, file) entries kept in the in-memory
    /// diagnostic cache. Older entries are evicted in LRU order when the
    /// cap is exceeded. Set to 0 to disable the cap entirely.
    /// Default: 5000 (covers very large monorepos with bounded memory).
    pub diagnostic_cache_size: usize,
    /// Idle reclamation windows for unbound-root artifacts and language servers.
    pub idle: IdleConfig,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            memory: None,
            durability: DurabilityConfig::default(),
            cache_dir: None,
            cache_dir_configured: None,
            cache_unavailable: None,
            cache_config_unknown: None,
            cache_dir_opt_out: false,
            cache_epoch: 0,
            cache_lease: None,
            storage_lease: None,
            project_root: None,
            validation_depth: 1,
            checkpoint_ttl_hours: 24,
            max_symbol_depth: 10,
            formatter_timeout_secs: 10,
            type_checker_timeout_secs: 30,
            // Default OFF: formatting after an edit can silently reflow the file
            // under the agent (a formatter splitting/joining lines), staling the
            // context for the next edit/patch. Agents that want formatting opt in
            // via `format_on_edit: true`.
            format_on_edit: false,
            revision_reads: false,
            hashline_enabled: false,
            validate_on_edit: None,
            formatter: HashMap::new(),
            checker: HashMap::new(),
            // Default to false to match OpenCode's existing permission-based model.
            // The plugin opts into root restriction explicitly when desired.
            restrict_to_project_root: false,
            indexes: IndexesConfig::default(),
            index: IndexConfig::default(),
            aft_search_registered: true,
            experimental_bash_rewrite: false,
            experimental_bash_compress: false,
            experimental_bash_background: false,
            max_background_bash_tasks: 8,
            bash_long_running_reminder_enabled: true,
            bash_long_running_reminder_interval_ms: 600_000,
            foreground_wait_window_ms: default_foreground_wait_window_ms(),
            bash: BashConfig::default(),
            shell: ShellConfig::default(),
            bash_permissions: false,
            sandbox: SandboxConfig::default(),
            remote_exec: RemoteExecConfig::default(),
            search_index_max_file_size: 1_048_576,
            semantic: SemanticBackendConfig::default(),
            search: SearchConfig::default(),
            inspect: InspectConfig::default(),
            backup: BackupConfig::default(),
            github: GithubConfig::default(),
            gh_shim: GhShimConfig::default(),

            git: GitConfig::default(),
            experimental_lsp_ty: false,
            lsp_servers: Vec::new(),
            invalid_lsp_initialization_options: Vec::new(),
            disabled_lsp: HashSet::new(),
            diagnostics_on_edit: false,
            lsp_idle_minutes: DEFAULT_LSP_IDLE_MINUTES,
            lsp_idle_shutdown: true,
            lsp_max_servers: 8,
            lsp_user_max_servers: None,
            lsp_paths_extra: Vec::new(),
            lsp_auto_install_binaries: HashSet::new(),
            lsp_inflight_installs: HashSet::new(),
            storage_dir: None,
            url_fetch_allow_private: false,
            disabled_tools: crate::feature_config::DEFAULT_DISABLED_TOOLS
                .iter()
                .map(|name| (*name).to_string())
                .collect(),
            harness: None,
            diagnostic_cache_size: 5000,
            idle: IdleConfig::default(),
        }
    }
}

impl Config {
    pub fn lsp_idle_ttl(&self) -> Option<std::time::Duration> {
        self.lsp_idle_shutdown
            .then(|| std::time::Duration::from_secs(u64::from(self.lsp_idle_minutes) * 60))
    }

    /// Whether the host's tagged `read` slot is registered, i.e. `read` is not
    /// in the resolved disabled list.
    ///
    /// Only a tagged read mints the `[path#TAG]` snapshots a hashline patch can
    /// address, so a session that lost the read slot must not be offered the
    /// hashline edit arm. The predicate is deliberately spelled the same way as
    /// the plugins' registration check so both sides of the boundary classify a
    /// given config identically.
    pub fn read_slot_survives(&self) -> bool {
        !self.disabled_tools.iter().any(|name| name == "read")
    }

    /// Whether a canonical tool name is registered under the resolved list.
    pub fn tool_registered(&self, name: &str) -> bool {
        !self.disabled_tools.iter().any(|disabled| disabled == name)
    }
}

const fn default_bash_enabled() -> bool {
    true
}

fn default_foreground_wait_window_ms() -> u64 {
    15_000
}

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

    #[test]
    fn read_slot_survival_matches_the_plugin_registration_rule() {
        let base = Config::default();
        assert!(base.read_slot_survives());

        let disabled = Config {
            disabled_tools: vec!["read".to_string()],
            ..Config::default()
        };
        assert!(!disabled.read_slot_survives());

        // An unrelated disabled tool leaves the read slot alone.
        let unrelated = Config {
            disabled_tools: vec!["aft_zoom".to_string()],
            ..Config::default()
        };
        assert!(unrelated.read_slot_survives());
    }

    #[test]
    fn semantic_query_instruction_resolves_by_backend_model_and_override() {
        let mut config = SemanticBackendConfig::default();
        config.model = "QWEN/Qwen3-Embedding-0.6B".to_string();
        config.query_instruction = "auto".to_string();
        assert_eq!(config.resolved_query_instruction(), None);

        config.backend = SemanticBackend::OpenAiCompatible;
        assert_eq!(
            config.resolved_query_instruction(),
            Some(QWEN3_EMBEDDING_MODEL_CARD_RETRIEVAL_TASK)
        );

        config.model = "text-embedding-3-small".to_string();
        assert_eq!(config.resolved_query_instruction(), None);

        config.query_instruction = "custom code retrieval task".to_string();
        assert_eq!(
            config.resolved_query_instruction(),
            Some("custom code retrieval task")
        );

        config.query_instruction = "off".to_string();
        assert_eq!(config.resolved_query_instruction(), None);
    }

    #[test]
    fn bash_watch_sync_max_defaults_to_two_minutes_when_deserialized() {
        let parsed: BashConfig = serde_json::from_str("{}").unwrap();
        assert_eq!(parsed.watch_sync_max_ms, DEFAULT_BASH_WATCH_SYNC_MAX_MS);
        assert_eq!(BashConfig::default().watch_sync_max_ms, 120_000);
    }

    #[test]
    fn bash_worker_wait_max_defaults_to_thirty_minutes_when_deserialized() {
        let parsed: BashConfig = serde_json::from_str("{}").unwrap();
        assert_eq!(parsed.worker_wait_max_ms, DEFAULT_BASH_WORKER_WAIT_MAX_MS);
        assert_eq!(BashConfig::default().worker_wait_max_ms, 1_800_000);
    }

    #[test]
    fn index_root_path_expands_tilde_before_absolute_validation() {
        let home = std::env::temp_dir().join("aft-home");
        assert_eq!(
            expand_index_root_path("~/workspace", Some(&home)).unwrap(),
            home.join("workspace")
        );
        assert!(expand_index_root_path("relative/root", Some(&home)).is_err());
        assert!(expand_index_root_path("~", None).is_err());
    }

    #[test]
    fn relative_path_refusals_name_the_setting_that_holds_the_path() {
        let home = std::env::temp_dir().join("aft-home");
        let cache_error = expand_cache_dir_path("relative/cache", Some(&home)).unwrap_err();
        assert!(
            cache_error.starts_with("storage.cache_dir path must be absolute"),
            "{cache_error}"
        );
        assert!(!cache_error.contains("index.roots"), "{cache_error}");
        let no_home = expand_cache_dir_path("~/cache", None).unwrap_err();
        assert!(
            no_home.starts_with("storage.cache_dir path uses ~"),
            "{no_home}"
        );

        // The index.roots refusal keeps its own key name and exact text.
        assert_eq!(
            expand_index_root_path("relative/root", Some(&home)).unwrap_err(),
            "index.roots path must be absolute after ~ expansion: \"relative/root\""
        );
    }
}

pub const DEFAULT_MAX_UNDO_DEPTH: usize = 20;
/// Default upper bound for one automatic undo snapshot (64 MiB).
pub const DEFAULT_MAX_BACKUP_FILE_SIZE: u64 = 64 * 1024 * 1024;