1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::path::PathBuf;
3
4use serde::{Deserialize, Serialize};
5
6pub const DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS: u64 = 3_000;
7pub const DEFAULT_SEMANTIC_QUERY_INSTRUCTION: &str = "auto";
13pub const QWEN3_EMBEDDING_MODEL_CARD_RETRIEVAL_TASK: &str =
16 "Given a web search query, retrieve relevant passages that answer the query";
17pub const QWEN3_EMBEDDING_CODE_SEARCH_TASK: &str =
18 "Given a code search query, retrieve relevant source code, symbols, and documentation";
19pub const MIN_SEMANTIC_QUERY_TIMEOUT_MS: u64 = 500;
20pub const MAX_SEMANTIC_QUERY_TIMEOUT_MS: u64 = 30_000;
21pub(crate) const DEFAULT_INSPECT_DIAGNOSTICS_TIMEOUT_MS: u64 = 120_000;
22pub const MIN_INSPECT_DIAGNOSTICS_TIMEOUT_MS: u64 = 10_000;
23pub const MAX_INSPECT_DIAGNOSTICS_TIMEOUT_MS: u64 = 600_000;
24pub const DEFAULT_INSPECT_TIER2_PASS_TIMEOUT_MS: u64 = 600_000;
25pub const DEFAULT_BASH_WATCH_SYNC_MAX_MS: u64 = 120_000;
26pub const MIN_BASH_WATCH_SYNC_MAX_MS: u64 = 1_000;
27pub const MAX_BASH_WATCH_SYNC_MAX_MS: u64 = 1_800_000;
28pub const DEFAULT_BASH_WORKER_WAIT_MAX_MS: u64 = 1_800_000;
36pub const DEFAULT_LINUX_SCOPE_MAX_RUNTIME_SECS: u64 = 86_400;
37pub const MIN_BASH_WORKER_WAIT_MAX_MS: u64 = 60_000;
41
42pub const DEFAULT_IDLE_ROOT_TTL_MINUTES: u32 = 30;
44pub const MIN_IDLE_ROOT_TTL_MINUTES: u32 = 5;
45pub const MAX_IDLE_ROOT_TTL_MINUTES: u32 = 30;
46pub const DEFAULT_IDLE_CHECKOUT_HOURS: u32 = 168;
49pub const MIN_IDLE_CHECKOUT_HOURS: u32 = 1;
50pub const MAX_IDLE_CHECKOUT_HOURS: u32 = 24 * 365;
51pub const DEFAULT_LSP_IDLE_MINUTES: u32 = 60;
53pub const MIN_LSP_IDLE_MINUTES: u32 = 5;
54pub const MAX_LSP_IDLE_MINUTES: u32 = 1440;
55
56const fn default_semantic_query_timeout_ms() -> u64 {
57 DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS
58}
59
60const fn default_inspect_diagnostics_timeout_ms() -> u64 {
61 DEFAULT_INSPECT_DIAGNOSTICS_TIMEOUT_MS
62}
63
64const fn default_inspect_tier2_pass_timeout_ms() -> u64 {
65 DEFAULT_INSPECT_TIER2_PASS_TIMEOUT_MS
66}
67
68const fn default_bash_detach_on_user_message() -> bool {
69 true
70}
71
72pub(crate) const fn default_bash_watch_sync_max_ms() -> u64 {
73 DEFAULT_BASH_WATCH_SYNC_MAX_MS
74}
75
76pub(crate) const fn default_bash_worker_wait_max_ms() -> u64 {
77 DEFAULT_BASH_WORKER_WAIT_MAX_MS
78}
79
80use crate::harness::Harness;
81
82pub fn open_config_file(path: &std::path::Path) -> std::io::Result<std::fs::File> {
95 let mut options = std::fs::OpenOptions::new();
96 options.read(true);
97 #[cfg(windows)]
98 {
99 use std::os::windows::fs::OpenOptionsExt;
100 const FILE_SHARE_READ: u32 = 0x0000_0001;
101 const FILE_SHARE_WRITE: u32 = 0x0000_0002;
102 const FILE_SHARE_DELETE: u32 = 0x0000_0004;
103 options.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE);
104 }
105 options.open(path)
106}
107
108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
115#[serde(default)]
116pub struct IdleConfig {
117 pub root_ttl_minutes: u32,
118 pub checkout_hours: u32,
119}
120
121impl Default for IdleConfig {
122 fn default() -> Self {
123 Self {
124 root_ttl_minutes: DEFAULT_IDLE_ROOT_TTL_MINUTES,
125 checkout_hours: DEFAULT_IDLE_CHECKOUT_HOURS,
126 }
127 }
128}
129
130impl IdleConfig {
131 pub fn root_ttl(&self) -> std::time::Duration {
132 std::time::Duration::from_secs(u64::from(self.root_ttl_minutes) * 60)
133 }
134}
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
138#[serde(rename_all = "snake_case")]
139pub enum IndexKind {
140 Search,
141 Semantic,
142 Callgraph,
143}
144
145impl IndexKind {
146 pub const ALL: [Self; 3] = [Self::Search, Self::Semantic, Self::Callgraph];
147
148 pub const fn as_str(self) -> &'static str {
149 match self {
150 Self::Search => "search",
151 Self::Semantic => "semantic",
152 Self::Callgraph => "callgraph",
153 }
154 }
155
156 pub fn from_name(name: &str) -> Option<Self> {
157 match name {
158 "search" => Some(Self::Search),
159 "semantic" => Some(Self::Semantic),
160 "callgraph" => Some(Self::Callgraph),
161 _ => None,
162 }
163 }
164}
165
166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
168pub struct IndexRootConfig {
169 pub path: String,
171 pub indexes: Vec<IndexKind>,
173}
174
175#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
177#[serde(default)]
178pub struct IndexConfig {
179 pub roots: Vec<IndexRootConfig>,
180}
181
182pub fn expand_index_root_path(
185 path: &str,
186 home: Option<&std::path::Path>,
187) -> Result<PathBuf, String> {
188 expand_configured_absolute_path("index.roots", path, home)
189}
190
191pub fn expand_cache_dir_path(
194 path: &str,
195 home: Option<&std::path::Path>,
196) -> Result<PathBuf, String> {
197 expand_configured_absolute_path("storage.cache_dir", path, home)
198}
199
200fn expand_configured_absolute_path(
204 key: &str,
205 path: &str,
206 home: Option<&std::path::Path>,
207) -> Result<PathBuf, String> {
208 let no_home = || format!("{key} path uses ~ but no home directory is available");
209 let expanded = if path == "~" {
210 home.ok_or_else(no_home)?.to_path_buf()
211 } else if let Some(remainder) = path.strip_prefix("~/").or_else(|| path.strip_prefix("~\\")) {
212 home.ok_or_else(no_home)?.join(remainder)
213 } else {
214 PathBuf::from(path)
215 };
216
217 if !expanded.is_absolute() {
218 return Err(format!(
219 "{key} path must be absolute after ~ expansion: {path:?}"
220 ));
221 }
222 Ok(expanded)
223}
224
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
227#[serde(rename_all = "snake_case")]
228pub enum SemanticBackend {
229 Fastembed,
230 #[serde(rename = "openai_compatible")]
231 OpenAiCompatible,
232 Ollama,
233 Synapse,
234}
235
236impl SemanticBackend {
237 pub const fn as_str(&self) -> &'static str {
238 match self {
239 Self::Fastembed => "fastembed",
240 Self::OpenAiCompatible => "openai_compatible",
241 Self::Ollama => "ollama",
242 Self::Synapse => "synapse",
243 }
244 }
245
246 pub fn from_name(name: &str) -> Option<Self> {
247 match name {
248 "fastembed" => Some(Self::Fastembed),
249 "openai_compatible" => Some(Self::OpenAiCompatible),
250 "ollama" => Some(Self::Ollama),
251 "synapse" => Some(Self::Synapse),
252 _ => None,
253 }
254 }
255}
256
257#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
258pub struct SemanticBackendConfig {
259 #[serde(skip)]
261 pub local_cache_dir: Option<PathBuf>,
262 pub backend: SemanticBackend,
263 pub model: String,
264 pub base_url: Option<String>,
265 pub api_key_env: Option<String>,
266 pub timeout_ms: u64,
270 #[serde(default = "default_semantic_query_timeout_ms")]
273 pub query_timeout_ms: u64,
274 #[serde(default = "default_semantic_query_instruction")]
277 pub query_instruction: String,
278 pub max_batch_size: usize,
279 #[serde(default, skip_serializing_if = "Option::is_none")]
282 pub max_input_tokens: Option<usize>,
283 pub max_files: usize,
287 #[serde(skip)]
289 pub subc_connection_file: Option<PathBuf>,
290 #[serde(skip)]
293 pub route_project_root: Option<PathBuf>,
294 #[serde(skip)]
295 pub route_harness: Option<String>,
296}
297
298#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
299pub struct UserServerDef {
300 pub id: String,
301 pub extensions: Vec<String>,
302 pub binary: String,
303 pub args: Vec<String>,
304 pub root_markers: Vec<String>,
305 pub env: HashMap<String, String>,
306 pub initialization_options: Option<serde_json::Value>,
307 pub disabled: bool,
308}
309
310fn default_semantic_query_instruction() -> String {
311 DEFAULT_SEMANTIC_QUERY_INSTRUCTION.to_string()
312}
313
314impl SemanticBackendConfig {
315 pub fn resolved_query_instruction(&self) -> Option<&str> {
316 if self.backend == SemanticBackend::Fastembed {
317 return None;
318 }
319 match self.query_instruction.as_str() {
320 "off" => None,
321 "auto" if self.model.to_ascii_lowercase().contains("qwen3-embedding") => {
322 Some(QWEN3_EMBEDDING_MODEL_CARD_RETRIEVAL_TASK)
323 }
324 "auto" => None,
325 literal => Some(literal),
326 }
327 }
328}
329
330impl Default for SemanticBackendConfig {
331 fn default() -> Self {
332 Self {
333 local_cache_dir: None,
334 backend: SemanticBackend::Fastembed,
335 model: DEFAULT_SEMANTIC_MODEL.to_string(),
336 base_url: None,
337 api_key_env: None,
338 timeout_ms: 25_000,
342 query_timeout_ms: DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS,
343 query_instruction: default_semantic_query_instruction(),
344 max_batch_size: 64,
345 max_input_tokens: None,
346 max_files: 20_000,
347 subc_connection_file: None,
348 route_project_root: None,
349 route_harness: None,
350 }
351 }
352}
353
354#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
355#[serde(default)]
356pub struct InspectConfig {
357 pub enabled: bool,
358 pub categories: InspectCategories,
359 #[serde(default = "default_inspect_diagnostics_timeout_ms")]
361 pub diagnostics_timeout_ms: u64,
362 #[serde(default = "default_inspect_tier2_pass_timeout_ms")]
364 pub tier2_pass_timeout_ms: u64,
365 pub duplicates: InspectDuplicatesConfig,
366}
367
368#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
369#[serde(default)]
370pub struct InspectDuplicatesConfig {
371 pub expected_mirrors: Vec<[String; 2]>,
372}
373
374#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
375#[serde(default, deny_unknown_fields)]
376pub struct InspectCategories {
377 pub diagnostics: bool,
378 pub todos: bool,
379 pub dead_code: bool,
380 pub unused_exports: bool,
381 pub duplicates: bool,
382 pub cycles: bool,
383 pub complexity: bool,
384}
385
386impl Default for InspectCategories {
387 fn default() -> Self {
388 Self {
389 diagnostics: true,
390 todos: true,
391 dead_code: true,
392 unused_exports: true,
393 duplicates: true,
394 cycles: true,
395 complexity: true,
396 }
397 }
398}
399
400impl InspectCategories {
401 pub const KEYS: [&'static str; 7] = [
402 "diagnostics",
403 "todos",
404 "dead_code",
405 "unused_exports",
406 "duplicates",
407 "cycles",
408 "complexity",
409 ];
410
411 pub fn enabled(&self, category: crate::inspect_category::InspectCategory) -> bool {
412 use crate::inspect_category::InspectCategory::*;
413 match category {
414 Diagnostics => self.diagnostics,
415 Todos => self.todos,
416 DeadCode => self.dead_code,
417 UnusedExports => self.unused_exports,
418 Duplicates => self.duplicates,
419 Cycles => self.cycles,
420 Complexity => self.complexity,
421 Metrics => true,
424 _ => false,
425 }
426 }
427}
428
429impl InspectConfig {
430 pub fn category_enabled(&self, category: crate::inspect_category::InspectCategory) -> bool {
431 self.enabled && self.categories.enabled(category)
432 }
433}
434
435impl Default for InspectConfig {
436 fn default() -> Self {
437 Self {
438 enabled: true,
439 categories: InspectCategories::default(),
440 diagnostics_timeout_ms: default_inspect_diagnostics_timeout_ms(),
441 tier2_pass_timeout_ms: default_inspect_tier2_pass_timeout_ms(),
442 duplicates: InspectDuplicatesConfig::default(),
443 }
444 }
445}
446
447#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
448#[serde(default)]
449pub struct BackupConfig {
450 pub enabled: Option<bool>,
451 pub max_depth: Option<usize>,
452 pub max_file_size: Option<u64>,
453}
454
455impl Default for BackupConfig {
456 fn default() -> Self {
457 Self {
458 enabled: Some(true),
459 max_depth: Some(DEFAULT_MAX_UNDO_DEPTH),
460 max_file_size: Some(DEFAULT_MAX_BACKUP_FILE_SIZE),
461 }
462 }
463}
464
465#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
468#[serde(default)]
469pub struct GhShimConfig {
470 pub binary_path: Option<PathBuf>,
473}
474
475#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
477#[serde(default)]
478pub struct GithubConfig {
479 pub shim: bool,
481 pub read: bool,
483 pub write: bool,
485}
486
487impl Default for GithubConfig {
488 fn default() -> Self {
489 Self {
490 shim: true,
491 read: false,
492 write: false,
493 }
494 }
495}
496
497#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
500#[serde(default)]
501pub struct IndexesConfig {
502 pub trigram: bool,
504 pub semantic: bool,
506 pub callgraph: bool,
508}
509
510impl Default for IndexesConfig {
511 fn default() -> Self {
512 Self {
513 trigram: true,
514 semantic: true,
515 callgraph: true,
516 }
517 }
518}
519
520#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
522#[serde(default)]
523pub struct GitConfig {
524 pub co_author: String,
526}
527
528impl Default for GitConfig {
529 fn default() -> Self {
530 Self {
531 co_author: "off".to_string(),
532 }
533 }
534}
535
536pub fn normalize_git_co_author(value: &str) -> Option<String> {
538 let value = value.trim();
539 if matches!(value, "off" | "auto") {
540 return Some(value.to_string());
541 }
542 if value.contains(['\n', '\r']) || !value.ends_with('>') {
543 return None;
544 }
545 let open = value.rfind('<')?;
546 if open == 0 || !value.as_bytes()[open - 1].is_ascii_whitespace() {
547 return None;
548 }
549 let name = value[..open].trim();
550 let email = value[open + 1..value.len() - 1].trim();
551 if name.is_empty()
552 || name.contains(['<', '>'])
553 || email.is_empty()
554 || !email.contains('@')
555 || email
556 .chars()
557 .any(|character| character.is_whitespace() || matches!(character, '<' | '>'))
558 {
559 return None;
560 }
561 Some(value.to_string())
562}
563
564pub const DEFAULT_SEMANTIC_MODEL: &str = "all-MiniLM-L6-v2";
565
566#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
568#[serde(rename_all = "snake_case")]
569pub enum RerankBackendKind {
570 Off,
571 Onnx,
572 Remote,
573 Synapse,
574}
575
576impl RerankBackendKind {
577 pub fn as_str(self) -> &'static str {
578 match self {
579 Self::Off => "off",
580 Self::Onnx => "onnx",
581 Self::Remote => "remote",
582 Self::Synapse => "synapse",
583 }
584 }
585}
586
587#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
592#[serde(default)]
593pub struct RerankConfig {
594 #[serde(skip_serializing_if = "Option::is_none")]
595 pub backend: Option<RerankBackendKind>,
596 #[serde(skip_serializing_if = "Option::is_none")]
597 pub model: Option<String>,
598 #[serde(skip_serializing_if = "Option::is_none")]
599 pub endpoint: Option<String>,
600 #[serde(skip_serializing_if = "Option::is_none")]
601 pub api_key_env: Option<String>,
602 #[serde(skip_serializing_if = "Option::is_none")]
603 pub top_n: Option<u64>,
604 #[serde(skip_serializing_if = "Option::is_none")]
605 pub timeout_ms: Option<u64>,
606}
607
608#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
610#[serde(default)]
611pub struct SearchConfig {
612 #[serde(skip_serializing_if = "Option::is_none")]
613 pub rerank: Option<RerankConfig>,
614}
615
616impl Config {
617 pub fn cache_storage_dir(&self) -> Option<PathBuf> {
619 (self.cache_dir.is_some() || self.storage_dir.is_some())
620 .then(|| crate::cache_location::cache_root(self))
621 }
622 pub fn semantic_backend_label(&self) -> &'static str {
623 self.semantic.backend.as_str()
624 }
625}
626
627#[derive(
629 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
630)]
631#[serde(rename_all = "lowercase")]
632pub enum SandboxMode {
633 Off,
634 Relaxed,
635 Strict,
636}
637
638impl Default for SandboxMode {
639 fn default() -> Self {
640 Self::Strict
641 }
642}
643
644impl std::fmt::Display for SandboxMode {
645 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
646 f.write_str(match self {
647 Self::Off => "off",
648 Self::Relaxed => "relaxed",
649 Self::Strict => "strict",
650 })
651 }
652}
653
654#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
655#[serde(default)]
656pub struct SandboxRoles {
657 pub worker: SandboxMode,
658 pub head: SandboxMode,
659}
660
661impl Default for SandboxRoles {
662 fn default() -> Self {
663 Self {
664 worker: SandboxMode::Relaxed,
665 head: SandboxMode::Off,
666 }
667 }
668}
669
670#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
671#[serde(default)]
672pub struct SandboxConfig {
673 pub profile: SandboxRoles,
676 pub write_allow: Vec<PathBuf>,
678 pub read_deny: Vec<PathBuf>,
680}
681
682impl SandboxConfig {
683 pub fn head_enabled(&self) -> bool {
684 self.profile.head != SandboxMode::Off
685 }
686}
687
688#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
691#[serde(default)]
692pub struct RemoteExecConfig {
693 pub enabled: bool,
697 pub default_demand: Option<String>,
700 pub project_off: bool,
703}
704
705#[derive(
706 Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
707)]
708#[serde(rename_all = "snake_case")]
709pub enum BashChangedFiles {
710 #[default]
711 Off,
712 List,
713 Diff,
714}
715
716#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
717#[serde(default)]
718pub struct BashConfig {
719 pub changed_files: BashChangedFiles,
721 #[serde(default = "default_bash_enabled")]
725 pub enabled: bool,
726 pub host_fallback: bool,
729 #[serde(default = "default_bash_detach_on_user_message")]
732 pub detach_on_user_message: bool,
733 #[serde(default = "default_bash_enabled")]
735 pub db_schema_hints: bool,
736 #[serde(default = "default_bash_watch_sync_max_ms")]
739 pub watch_sync_max_ms: u64,
740 #[serde(default = "default_bash_worker_wait_max_ms")]
746 pub worker_wait_max_ms: u64,
747 pub linux_scope: bool,
749 pub linux_scope_max_runtime_secs: u64,
751 pub memory_limit_mib: Option<u64>,
753 pub disclaim_privacy: bool,
756 pub powershell_tool: bool,
759 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
764 pub env: BTreeMap<String, String>,
765 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
770 pub project_env: BTreeMap<String, String>,
771 #[serde(default, skip_serializing_if = "Vec::is_empty")]
775 pub runon_env: Vec<String>,
776}
777
778#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
780#[serde(default, deny_unknown_fields)]
781pub struct ShellConfig {
782 #[serde(skip_serializing_if = "Option::is_none")]
783 #[schemars(
784 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."
785 )]
786 pub env_provider: Option<ShellEnvProvider>,
787}
788
789#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
790#[serde(rename_all = "lowercase")]
791pub enum ShellEnvProviderKind {
792 Mise,
793 Direnv,
794 Custom,
795}
796
797#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
798#[serde(deny_unknown_fields)]
799pub struct ShellEnvProvider {
800 pub kind: ShellEnvProviderKind,
801 #[serde(default, skip_serializing_if = "Option::is_none")]
802 #[schemars(
803 description = "Provider argv. Defaults to mise env --json or direnv export json; required for custom."
804 )]
805 pub command: Option<Vec<String>>,
806 #[serde(default = "default_env_provider_timeout_ms")]
807 pub timeout_ms: u64,
808 #[serde(default)]
809 #[schemars(
810 description = "Custom provider watch files, checked at every ancestor. A custom provider with no watches runs on every call."
811 )]
812 pub watch: Vec<String>,
813}
814
815fn default_env_provider_timeout_ms() -> u64 {
816 2000
817}
818
819impl ShellEnvProvider {
820 pub fn validate(&self) -> Result<(), String> {
821 if self.kind != ShellEnvProviderKind::Custom && !self.watch.is_empty() {
822 return Err("invalid_security_config:shell.env_provider.watch".into());
823 }
824 if !(100..=10000).contains(&self.timeout_ms) {
825 return Err("shell.env_provider.timeout_ms must be between 100 and 10000".into());
826 }
827 if self.kind == ShellEnvProviderKind::Custom && self.command.is_none() {
828 return Err("shell.env_provider.command is required for custom".into());
829 }
830 if self.command.as_ref().is_some_and(|command| {
831 command.is_empty()
832 || command[0].is_empty()
833 || command.iter().any(|arg| arg.contains('\0'))
834 }) {
835 return Err(
836 "shell.env_provider.command must be a nonempty argv without NUL bytes".into(),
837 );
838 }
839 if cfg!(windows) && self.kind == ShellEnvProviderKind::Direnv {
840 return Err(
841 "shell.env_provider: direnv is not supported on Windows; use mise or custom".into(),
842 );
843 }
844 Ok(())
845 }
846
847 pub fn argv(&self) -> Vec<String> {
848 self.command.clone().unwrap_or_else(|| match self.kind {
849 ShellEnvProviderKind::Mise => vec!["mise".into(), "env".into(), "--json".into()],
850 ShellEnvProviderKind::Direnv => vec!["direnv".into(), "export".into(), "json".into()],
851 ShellEnvProviderKind::Custom => unreachable!("custom command validated at config load"),
852 })
853 }
854}
855
856impl Default for BashConfig {
857 fn default() -> Self {
858 Self {
859 changed_files: BashChangedFiles::Off,
860 enabled: true,
861 host_fallback: false,
862 detach_on_user_message: default_bash_detach_on_user_message(),
863 db_schema_hints: true,
864 watch_sync_max_ms: default_bash_watch_sync_max_ms(),
865 worker_wait_max_ms: default_bash_worker_wait_max_ms(),
866 linux_scope: true,
867 linux_scope_max_runtime_secs: DEFAULT_LINUX_SCOPE_MAX_RUNTIME_SECS,
868 memory_limit_mib: None,
869 disclaim_privacy: false,
870 powershell_tool: false,
871 env: BTreeMap::new(),
872 project_env: BTreeMap::new(),
873 runon_env: Vec::new(),
874 }
875 }
876}
877
878#[derive(Debug, Clone, PartialEq, Eq)]
881pub struct ConfiguredCacheDir {
882 pub spelling: PathBuf,
883 pub resolved: PathBuf,
884}
885
886impl BashConfig {
887 pub fn configured_env(
896 &self,
897 project_trusted: bool,
898 ) -> Vec<crate::config_resolve::ConfiguredBashEnv> {
899 let mut applied = Vec::new();
900 if !self.env.is_empty() {
901 applied.push(crate::config_resolve::ConfiguredBashEnv {
902 names: self.env.clone(),
903 tier: crate::bash_env::BashEnvTier::User,
904 });
905 }
906 if project_trusted && !self.project_env.is_empty() {
907 applied.push(crate::config_resolve::ConfiguredBashEnv {
908 names: self.project_env.clone(),
909 tier: crate::bash_env::BashEnvTier::Project,
910 });
911 }
912 applied
913 }
914
915 pub fn shadowed_project_env(&self, project_trusted: bool) -> Vec<String> {
917 if !project_trusted {
918 return Vec::new();
919 }
920 self.project_env
921 .keys()
922 .filter(|name| self.env.contains_key(*name))
923 .cloned()
924 .collect()
925 }
926}
927
928#[derive(Debug, Clone, Default, Serialize, Deserialize)]
929#[serde(default)]
930pub struct DurabilityConfig {
931 pub macos_full_sync: bool,
933}
934
935#[derive(Debug, Clone, Serialize, Deserialize)]
936#[serde(default)]
937pub struct Config {
938 pub memory: Option<crate::memory_profile::MemoryMode>,
940 pub durability: DurabilityConfig,
942 #[serde(skip_deserializing)]
944 pub cache_dir: Option<PathBuf>,
945 #[serde(skip)]
950 pub cache_dir_configured: Option<ConfiguredCacheDir>,
951 #[serde(skip_deserializing)]
953 pub cache_unavailable: Option<String>,
954 #[serde(skip)]
956 pub cache_config_unknown: Option<String>,
957 #[serde(skip)]
960 pub cache_dir_opt_out: bool,
961 #[serde(skip_deserializing)]
963 pub cache_epoch: u64,
964 #[serde(skip)]
965 pub cache_lease: Option<std::sync::Arc<crate::cache_location::CacheLease>>,
966 #[serde(skip)]
968 pub storage_lease: Option<std::sync::Arc<crate::cache_location::ProcessStorageLease>>,
969 pub project_root: Option<PathBuf>,
971 pub validation_depth: u32,
973 pub checkpoint_ttl_hours: u32,
977 pub max_symbol_depth: u32,
979 pub formatter_timeout_secs: u32,
981 pub type_checker_timeout_secs: u32,
983 pub format_on_edit: bool,
985 pub revision_reads: bool,
989 pub hashline_enabled: bool,
992 pub validate_on_edit: Option<String>,
995 pub formatter: HashMap<String, String>,
998 pub checker: HashMap<String, String>,
1001 pub restrict_to_project_root: bool,
1004 pub indexes: IndexesConfig,
1006 pub index: IndexConfig,
1008 pub aft_search_registered: bool,
1013 pub experimental_bash_rewrite: bool,
1015 pub experimental_bash_compress: bool,
1017 pub experimental_bash_background: bool,
1019 pub max_background_bash_tasks: usize,
1028 pub bash_long_running_reminder_enabled: bool,
1030 pub bash_long_running_reminder_interval_ms: u64,
1032 #[serde(skip, default = "default_foreground_wait_window_ms")]
1034 pub foreground_wait_window_ms: u64,
1035 pub bash: BashConfig,
1037 pub shell: ShellConfig,
1038 pub bash_permissions: bool,
1040 pub sandbox: SandboxConfig,
1042 pub remote_exec: RemoteExecConfig,
1044 pub search_index_max_file_size: u64,
1046 pub semantic: SemanticBackendConfig,
1047 pub search: SearchConfig,
1049 pub inspect: InspectConfig,
1050 pub backup: BackupConfig,
1051 pub github: GithubConfig,
1053 pub gh_shim: GhShimConfig,
1055
1056 pub git: GitConfig,
1058 pub experimental_lsp_ty: bool,
1060 pub lsp_servers: Vec<UserServerDef>,
1062 #[serde(skip)]
1063 #[doc(hidden)]
1064 pub invalid_lsp_initialization_options: Vec<String>,
1065 pub disabled_lsp: HashSet<String>,
1067 #[serde(skip)]
1069 pub diagnostics_on_edit: bool,
1070 pub lsp_idle_minutes: u32,
1071 pub lsp_idle_shutdown: bool,
1072 pub lsp_max_servers: usize,
1074 #[serde(skip)]
1076 pub lsp_user_max_servers: Option<usize>,
1077 pub lsp_paths_extra: Vec<PathBuf>,
1085 pub lsp_auto_install_binaries: HashSet<String>,
1091 pub lsp_inflight_installs: HashSet<String>,
1097 pub storage_dir: Option<PathBuf>,
1101 pub url_fetch_allow_private: bool,
1104 pub disabled_tools: Vec<String>,
1108 #[serde(default)]
1110 pub harness: Option<Harness>,
1111 pub diagnostic_cache_size: usize,
1116 pub idle: IdleConfig,
1118}
1119
1120impl Default for Config {
1121 fn default() -> Self {
1122 Config {
1123 memory: None,
1124 durability: DurabilityConfig::default(),
1125 cache_dir: None,
1126 cache_dir_configured: None,
1127 cache_unavailable: None,
1128 cache_config_unknown: None,
1129 cache_dir_opt_out: false,
1130 cache_epoch: 0,
1131 cache_lease: None,
1132 storage_lease: None,
1133 project_root: None,
1134 validation_depth: 1,
1135 checkpoint_ttl_hours: 24,
1136 max_symbol_depth: 10,
1137 formatter_timeout_secs: 10,
1138 type_checker_timeout_secs: 30,
1139 format_on_edit: false,
1144 revision_reads: false,
1145 hashline_enabled: false,
1146 validate_on_edit: None,
1147 formatter: HashMap::new(),
1148 checker: HashMap::new(),
1149 restrict_to_project_root: false,
1152 indexes: IndexesConfig::default(),
1153 index: IndexConfig::default(),
1154 aft_search_registered: true,
1155 experimental_bash_rewrite: false,
1156 experimental_bash_compress: false,
1157 experimental_bash_background: false,
1158 max_background_bash_tasks: 8,
1159 bash_long_running_reminder_enabled: true,
1160 bash_long_running_reminder_interval_ms: 600_000,
1161 foreground_wait_window_ms: default_foreground_wait_window_ms(),
1162 bash: BashConfig::default(),
1163 shell: ShellConfig::default(),
1164 bash_permissions: false,
1165 sandbox: SandboxConfig::default(),
1166 remote_exec: RemoteExecConfig::default(),
1167 search_index_max_file_size: 1_048_576,
1168 semantic: SemanticBackendConfig::default(),
1169 search: SearchConfig::default(),
1170 inspect: InspectConfig::default(),
1171 backup: BackupConfig::default(),
1172 github: GithubConfig::default(),
1173 gh_shim: GhShimConfig::default(),
1174
1175 git: GitConfig::default(),
1176 experimental_lsp_ty: false,
1177 lsp_servers: Vec::new(),
1178 invalid_lsp_initialization_options: Vec::new(),
1179 disabled_lsp: HashSet::new(),
1180 diagnostics_on_edit: false,
1181 lsp_idle_minutes: DEFAULT_LSP_IDLE_MINUTES,
1182 lsp_idle_shutdown: true,
1183 lsp_max_servers: 8,
1184 lsp_user_max_servers: None,
1185 lsp_paths_extra: Vec::new(),
1186 lsp_auto_install_binaries: HashSet::new(),
1187 lsp_inflight_installs: HashSet::new(),
1188 storage_dir: None,
1189 url_fetch_allow_private: false,
1190 disabled_tools: crate::feature_config::DEFAULT_DISABLED_TOOLS
1191 .iter()
1192 .map(|name| (*name).to_string())
1193 .collect(),
1194 harness: None,
1195 diagnostic_cache_size: 5000,
1196 idle: IdleConfig::default(),
1197 }
1198 }
1199}
1200
1201impl Config {
1202 pub fn lsp_idle_ttl(&self) -> Option<std::time::Duration> {
1203 self.lsp_idle_shutdown
1204 .then(|| std::time::Duration::from_secs(u64::from(self.lsp_idle_minutes) * 60))
1205 }
1206
1207 pub fn read_slot_survives(&self) -> bool {
1216 !self.disabled_tools.iter().any(|name| name == "read")
1217 }
1218
1219 pub fn tool_registered(&self, name: &str) -> bool {
1221 !self.disabled_tools.iter().any(|disabled| disabled == name)
1222 }
1223}
1224
1225const fn default_bash_enabled() -> bool {
1226 true
1227}
1228
1229fn default_foreground_wait_window_ms() -> u64 {
1230 15_000
1231}
1232
1233#[cfg(test)]
1234mod tests {
1235 use super::*;
1236
1237 #[test]
1238 fn read_slot_survival_matches_the_plugin_registration_rule() {
1239 let base = Config::default();
1240 assert!(base.read_slot_survives());
1241
1242 let disabled = Config {
1243 disabled_tools: vec!["read".to_string()],
1244 ..Config::default()
1245 };
1246 assert!(!disabled.read_slot_survives());
1247
1248 let unrelated = Config {
1250 disabled_tools: vec!["aft_zoom".to_string()],
1251 ..Config::default()
1252 };
1253 assert!(unrelated.read_slot_survives());
1254 }
1255
1256 #[test]
1257 fn semantic_query_instruction_resolves_by_backend_model_and_override() {
1258 let mut config = SemanticBackendConfig::default();
1259 config.model = "QWEN/Qwen3-Embedding-0.6B".to_string();
1260 config.query_instruction = "auto".to_string();
1261 assert_eq!(config.resolved_query_instruction(), None);
1262
1263 config.backend = SemanticBackend::OpenAiCompatible;
1264 assert_eq!(
1265 config.resolved_query_instruction(),
1266 Some(QWEN3_EMBEDDING_MODEL_CARD_RETRIEVAL_TASK)
1267 );
1268
1269 config.model = "text-embedding-3-small".to_string();
1270 assert_eq!(config.resolved_query_instruction(), None);
1271
1272 config.query_instruction = "custom code retrieval task".to_string();
1273 assert_eq!(
1274 config.resolved_query_instruction(),
1275 Some("custom code retrieval task")
1276 );
1277
1278 config.query_instruction = "off".to_string();
1279 assert_eq!(config.resolved_query_instruction(), None);
1280 }
1281
1282 #[test]
1283 fn bash_watch_sync_max_defaults_to_two_minutes_when_deserialized() {
1284 let parsed: BashConfig = serde_json::from_str("{}").unwrap();
1285 assert_eq!(parsed.watch_sync_max_ms, DEFAULT_BASH_WATCH_SYNC_MAX_MS);
1286 assert_eq!(BashConfig::default().watch_sync_max_ms, 120_000);
1287 }
1288
1289 #[test]
1290 fn bash_worker_wait_max_defaults_to_thirty_minutes_when_deserialized() {
1291 let parsed: BashConfig = serde_json::from_str("{}").unwrap();
1292 assert_eq!(parsed.worker_wait_max_ms, DEFAULT_BASH_WORKER_WAIT_MAX_MS);
1293 assert_eq!(BashConfig::default().worker_wait_max_ms, 1_800_000);
1294 }
1295
1296 #[test]
1297 fn index_root_path_expands_tilde_before_absolute_validation() {
1298 let home = std::env::temp_dir().join("aft-home");
1299 assert_eq!(
1300 expand_index_root_path("~/workspace", Some(&home)).unwrap(),
1301 home.join("workspace")
1302 );
1303 assert!(expand_index_root_path("relative/root", Some(&home)).is_err());
1304 assert!(expand_index_root_path("~", None).is_err());
1305 }
1306
1307 #[test]
1308 fn relative_path_refusals_name_the_setting_that_holds_the_path() {
1309 let home = std::env::temp_dir().join("aft-home");
1310 let cache_error = expand_cache_dir_path("relative/cache", Some(&home)).unwrap_err();
1311 assert!(
1312 cache_error.starts_with("storage.cache_dir path must be absolute"),
1313 "{cache_error}"
1314 );
1315 assert!(!cache_error.contains("index.roots"), "{cache_error}");
1316 let no_home = expand_cache_dir_path("~/cache", None).unwrap_err();
1317 assert!(
1318 no_home.starts_with("storage.cache_dir path uses ~"),
1319 "{no_home}"
1320 );
1321
1322 assert_eq!(
1324 expand_index_root_path("relative/root", Some(&home)).unwrap_err(),
1325 "index.roots path must be absolute after ~ expansion: \"relative/root\""
1326 );
1327 }
1328}
1329
1330pub const DEFAULT_MAX_UNDO_DEPTH: usize = 20;
1331pub const DEFAULT_MAX_BACKUP_FILE_SIZE: u64 = 64 * 1024 * 1024;