Skip to main content

aft_base/
config.rs

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;
7/// `auto`: on the production lane (Bionic / Qwen3-Embedding-0.6B) the model-card
8/// instruction on queries only left concept MRR and exact recall flat within noise,
9/// raised real-query MRR 0.182 -> 0.189, and cut the dense lane's no-vocabulary
10/// admission from 59% to 49% of top-10 rows (docs/investigations/query-instruction-ab-2026-09.md).
11/// Document vectors are untouched, so flipping this never rebuilds an index.
12pub const DEFAULT_SEMANTIC_QUERY_INSTRUCTION: &str = "auto";
13/// Verbatim retrieval task recommended by the Qwen3-Embedding model card:
14/// <https://huggingface.co/Qwen/Qwen3-Embedding-0.6B#usage-tips>
15pub 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;
28/// How long a delegated worker's wait on one command blocks before control
29/// returns to the worker (`bash.worker_wait_max_ms`): any `bash_watch` wait,
30/// or a blocking `bash` call (`wait: true`, or every foreground call
31/// when `bash.subagent_background` is false), which then moves to the
32/// background instead of being killed. The worker then
33/// decides whether to wait again or kill the command, so a stuck command can
34/// never hold a worker for longer than this.
35pub const DEFAULT_BASH_WORKER_WAIT_MAX_MS: u64 = 1_800_000;
36pub const DEFAULT_LINUX_SCOPE_MAX_RUNTIME_SECS: u64 = 86_400;
37/// Smallest accepted `bash.worker_wait_max_ms`. A shorter limit would make a
38/// worker re-wait (and re-read its whole context) every few seconds; a value
39/// below it is a config error rather than a silent clamp.
40pub const MIN_BASH_WORKER_WAIT_MAX_MS: u64 = 60_000;
41
42/// Unbound-root artifact eviction idle window, in minutes.
43pub 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;
46/// Hours without use after which a checkout's in-memory index state is
47/// dropped (`idle.checkout_hours`).
48pub const DEFAULT_IDLE_CHECKOUT_HOURS: u32 = 168;
49pub const MIN_IDLE_CHECKOUT_HOURS: u32 = 1;
50pub const MAX_IDLE_CHECKOUT_HOURS: u32 = 24 * 365;
51/// Language-server idle window, in minutes. Independent of artifact eviction.
52pub 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
82/// Open a configuration file for reading.
83///
84/// On Windows a plain open asks for read access only, and the file then
85/// refuses to be replaced while this handle lives: an editor that saves by
86/// writing a temporary file and renaming it over this path, or an `aft write`
87/// replacing it, gets ERROR_ACCESS_DENIED (os error 5). A handle that shares
88/// delete lets the replacement land; it reaches the old file's bytes, which is
89/// what a reader already under way should see. Config files are read and
90/// released quickly, so this window is small either way.
91///
92/// Prefer this over `std::fs::read_to_string` for any file a user or tool may
93/// rewrite while AFT runs: the user and project config files.
94pub 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/// Idle reclamation windows.
109///
110/// `root_ttl_minutes` controls when an unbound root's indexes are evicted.
111/// Reclaimed indexes rebuild on the next request. `checkout_hours` controls
112/// when a checkout that has not been used for that long counts as idle and
113/// drops its in-memory index state; it replaces `views.idle_checkout_hours`.
114#[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/// The durable index families that a standing root may maintain.
137#[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/// One user-configured root whose literal path spelling is its durable identity.
167#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
168pub struct IndexRootConfig {
169    /// The unmodified Unicode spelling supplied in `index.roots[].path`.
170    pub path: String,
171    /// Normalized selected index families, in fixed [`IndexKind::ALL`] order.
172    pub indexes: Vec<IndexKind>,
173}
174
175/// User-tier standing-index configuration.
176#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
177#[serde(default)]
178pub struct IndexConfig {
179    pub roots: Vec<IndexRootConfig>,
180}
181
182/// Expand the supported `~` forms before validating that a configured root is
183/// absolute. The literal string is retained separately for durable identity.
184pub 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
191/// Expand the supported `~` forms in `storage.cache_dir` and require the
192/// result to be absolute.
193pub 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
200/// Shared `~` expansion and absolute-path check for user-configured paths.
201/// `key` is the setting's name as the user writes it, so a refusal names the
202/// setting that actually holds the bad value.
203fn 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/// Semantic backend selected by the currently resolved runtime configuration.
226#[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    /// Runtime-only local model location selected with the artifact root.
260    #[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    /// Per-request floor for background index builds. HTTP batches scale this
267    /// deadline from a successful per-item latency EMA; interactive queries use
268    /// `query_timeout_ms` instead.
269    pub timeout_ms: u64,
270    /// Deadline for one interactive query embedding request. Unlike `timeout_ms`,
271    /// this budget never controls background index builds.
272    #[serde(default = "default_semantic_query_timeout_ms")]
273    pub query_timeout_ms: u64,
274    /// Query-only task instruction. `auto` selects a model-family recipe, `off`
275    /// sends bare queries, and any other value is used as literal task text.
276    #[serde(default = "default_semantic_query_instruction")]
277    pub query_instruction: String,
278    pub max_batch_size: usize,
279    /// Optional whole-row input budget for remote embedding backends. When absent,
280    /// chunk construction retains the legacy MiniLM-era limits.
281    #[serde(default, skip_serializing_if = "Option::is_none")]
282    pub max_input_tokens: Option<usize>,
283    /// Maximum number of project files to semantically index. Guards local
284    /// fastembed memory (model + embeddings + batch buffers) on huge project
285    /// roots; remote backends that embed server-side can raise it freely.
286    pub max_files: usize,
287    /// User-tier SubC connection file used only by the Synapse embedding backend.
288    #[serde(skip)]
289    pub subc_connection_file: Option<PathBuf>,
290    /// Project-root and harness identity used to route Synapse management calls
291    /// to the correct project and execution environment.
292    #[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            // Background HTTP batches treat this as a per-request floor and
339            // scale it with measured per-item latency. Query requests have their
340            // own short deadline below.
341            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    /// Deadline for the blocking LSP diagnostics phase of `aft_inspect`.
360    #[serde(default = "default_inspect_diagnostics_timeout_ms")]
361    pub diagnostics_timeout_ms: u64,
362    /// Hard deadline for one Tier-2 pass, including projection and scanning.
363    #[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 is internal, not a rendered category. Scoped file counts
422            // need its scanner even when all user-facing categories are off.
423            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/// Binary configuration for the managed `gh` shim. Whether the shim is
466/// interposed at all is `github.shim`; this block carries no enable state.
467#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
468#[serde(default)]
469pub struct GhShimConfig {
470    /// Optional deployed or development AFT image used by managed shim entries.
471    /// The running executable is used when this user-tier field is absent.
472    pub binary_path: Option<PathBuf>,
473}
474
475/// GitHub integration gates resolved from the user-only `github` block.
476#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
477#[serde(default)]
478pub struct GithubConfig {
479    /// Whether AFT interposes the governed `gh` shim in agent child PATHs.
480    pub shim: bool,
481    /// Whether structured `issue://` and `pr://` reads are enabled.
482    pub read: bool,
483    /// Whether issue and pull-request comment writes are enabled.
484    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/// Which background indexes are switched on. Each defaults on and builds
498/// independently of which tools are registered.
499#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
500#[serde(default)]
501pub struct IndexesConfig {
502    /// Trigram index used by indexed grep/glob and the lexical search lane.
503    pub trigram: bool,
504    /// Semantic (embedding) index used by the semantic search lane.
505    pub semantic: bool,
506    /// Persisted call-graph store used by callgraph queries and enrichment.
507    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/// Git behavior applied only to AFT-spawned agent children.
521#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
522#[serde(default)]
523pub struct GitConfig {
524    /// `off` (default), `auto`, or one explicit `Name <email>` identity.
525    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
536/// Normalize configuration values into `off`, `auto`, or `Name <email>`.
537pub 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/// Which reranker, if any, reorders the head of `aft_search` results.
567#[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/// The `search.rerank` block exactly as the tiers supplied it. Only parsing
588/// and the user/project trust boundary happen in config resolution; defaults,
589/// clamps and the reranked depth are decided by the search engine, so a change
590/// to them is a ranking change measured by the search-quality gate.
591#[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/// Search settings outside the semantic embedding backend.
609#[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    /// Optional artifact location for APIs that keep disk persistence opt-in.
618    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/// Ordered from least to most restrictive for project-tier hardening.
628#[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    /// An authenticated Alfonso worker stamp selects worker; heads, standalone
674    /// commands and unstamped first-party routes select head.
675    pub profile: SandboxRoles,
676    /// User-approved writable roots in addition to projects, task artifacts, and caches.
677    pub write_allow: Vec<PathBuf>,
678    /// Extra paths that native backends should deny reading.
679    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/// Whether bash calls may ask to run on the remote build server (`runon`).
689/// The user config turns it on; a project config may only turn it off.
690#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
691#[serde(default)]
692pub struct RemoteExecConfig {
693    /// Offer `runon` to heads and accept their calls that set it. True only
694    /// when the user config enables it and the project config does not turn
695    /// it off.
696    pub enabled: bool,
697    /// The runner demand a `runon` call without specifics runs under. User
698    /// configuration only; it never makes a call remote by itself.
699    pub default_demand: Option<String>,
700    /// The project config turned remote runs off, so a `runon` call in this
701    /// project is refused with that reason rather than run anywhere.
702    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    /// Optional watcher-based reporting after shell commands. Disabled by default.
720    pub changed_files: BashChangedFiles,
721    /// Runtime gate for every bash-execution operation, including the
722    /// background companions. When false those operations report
723    /// `bash_disabled`; registration is decided by `disabled_tools` alone.
724    #[serde(default = "default_bash_enabled")]
725    pub enabled: bool,
726    /// Permit plugin-side break-glass execution when its AFT transport is unavailable.
727    /// Rust accepts this for cross-language config parity but never acts on it.
728    pub host_fallback: bool,
729    /// Whether the hosting plugin detaches wait:true bash calls on user messages.
730    /// Rust accepts this for cross-language config parity but never acts on it.
731    #[serde(default = "default_bash_detach_on_user_message")]
732    pub detach_on_user_message: bool,
733    /// Append read-only database CLI schema hints after missing-schema errors.
734    #[serde(default = "default_bash_enabled")]
735    pub db_schema_hints: bool,
736    /// Maximum synchronous `bash_watch` wait accepted by the hosting plugin.
737    /// Rust accepts this for cross-language config parity but never acts on it.
738    #[serde(default = "default_bash_watch_sync_max_ms")]
739    pub watch_sync_max_ms: u64,
740    /// Longest a delegated worker's wait on one command blocks before control
741    /// returns to it; see [`DEFAULT_BASH_WORKER_WAIT_MAX_MS`]. The engine caps
742    /// a worker's blocking bash call with it, and each wait a worker makes on a
743    /// task without its own timeout pushes that task's default hard kill to at
744    /// least this long after the wait.
745    #[serde(default = "default_bash_worker_wait_max_ms")]
746    pub worker_wait_max_ms: u64,
747    /// Put Linux tool shells in transient user scopes when systemd is available.
748    pub linux_scope: bool,
749    /// User-only ceiling for daemon scopes, in seconds. Default: 86_400.
750    pub linux_scope_max_runtime_secs: u64,
751    /// Aggregate local-command memory ceiling in MiB; absent means unlimited.
752    pub memory_limit_mib: Option<u64>,
753    /// On macOS, agent commands become responsible for their own privacy permissions.
754    /// Other platforms accept the setting but do not change process creation.
755    pub disclaim_privacy: bool,
756    /// Pi-only fallback gate for its optional PowerShell default tool. The Rust
757    /// executor accepts this solely to keep shared config parsing in parity.
758    pub powershell_tool: bool,
759    /// Fixed environment entries merged into each local bash request. User
760    /// configuration supplies these, and a trusted project's `bash.env` adds
761    /// more in [`BashConfig::project_env`]; replies disclose names, never
762    /// values.
763    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
764    pub env: BTreeMap<String, String>,
765    /// Validated project-tier `bash.env` values. The resolver never applies
766    /// them: `commands/bash.rs` merges them only while the project root is on
767    /// the filter trust list at the time of the call, and a name the user tier
768    /// already sets keeps the user value.
769    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
770    pub project_env: BTreeMap<String, String>,
771    /// User-only names whose `bash.env` value is also sent to a `runon` build
772    /// job. Every other configured name stays on this machine, and a project
773    /// value is never sent.
774    #[serde(default, skip_serializing_if = "Vec::is_empty")]
775    pub runon_env: Vec<String>,
776}
777
778/// User-only project environment selection, separate from shell tool switches.
779#[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/// `storage.cache_dir` as configured and the directory it named when the cache
879/// root was prepared.
880#[derive(Debug, Clone, PartialEq, Eq)]
881pub struct ConfiguredCacheDir {
882    pub spelling: PathBuf,
883    pub resolved: PathBuf,
884}
885
886impl BashConfig {
887    /// The `bash.env` values a local command should start with, lowest tier
888    /// first, tagged with the tier that supplied them.
889    ///
890    /// `project_trusted` is the caller's per-command trust decision; an
891    /// untrusted project's map is not included at all. A name both tiers set
892    /// keeps the user value: user names are often protective
893    /// (`GIT_TERMINAL_PROMPT=0`), and a repository should add names rather
894    /// than undo the user's.
895    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    /// Project names that a user value already covers, and so do not apply.
916    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    /// Flush the drive's volatile cache on macOS; plain fsync is the default.
932    pub macos_full_sync: bool,
933}
934
935#[derive(Debug, Clone, Serialize, Deserialize)]
936#[serde(default)]
937pub struct Config {
938    /// Machine-local resource profile; only the user config base may select it.
939    pub memory: Option<crate::memory_profile::MemoryMode>,
940    /// User-selected file flush policy; only macOS has a full drive-flush option.
941    pub durability: DurabilityConfig,
942    /// Existing cache parent; AFT owns only its `aft` namespace. None preserves the storage-root layout.
943    #[serde(skip_deserializing)]
944    pub cache_dir: Option<PathBuf>,
945    /// The spelling of `cache_dir` the user configured, kept once preparation
946    /// replaces `cache_dir` with the directory it resolved to. A symlink in
947    /// that spelling may later be repointed; every recheck resolves the
948    /// configured spelling again so the change is noticed.
949    #[serde(skip)]
950    pub cache_dir_configured: Option<ConfiguredCacheDir>,
951    /// Runtime validation failure; a configured unavailable root never falls back.
952    #[serde(skip_deserializing)]
953    pub cache_unavailable: Option<String>,
954    /// The user document could not establish whether a cache volume was selected.
955    #[serde(skip)]
956    pub cache_config_unknown: Option<String>,
957    /// The user config selects `storage.cache_dir.kind: main_disk`: caches deliberately
958    /// return to the storage root even if it earlier used a cache directory.
959    #[serde(skip)]
960    pub cache_dir_opt_out: bool,
961    /// Runtime cache-volume transition identity, used to retire old handles.
962    #[serde(skip_deserializing)]
963    pub cache_epoch: u64,
964    #[serde(skip)]
965    pub cache_lease: Option<std::sync::Arc<crate::cache_location::CacheLease>>,
966    /// A trusted process lease, never accepted from configuration or tool input.
967    #[serde(skip)]
968    pub storage_lease: Option<std::sync::Arc<crate::cache_location::ProcessStorageLease>>,
969    /// Root directory of the project being analyzed. `None` if not scoped.
970    pub project_root: Option<PathBuf>,
971    /// Legacy serialized setting (default: 1); validation does not consume it.
972    pub validation_depth: u32,
973    /// Hours before legacy backup-session maintenance may collect inactive history
974    /// (default: 24). Named checkpoint retention is intentionally fixed at fourteen
975    /// days and is not controlled by configuration.
976    pub checkpoint_ttl_hours: u32,
977    /// Legacy serialized setting (default: 10); symbol resolution does not consume it.
978    pub max_symbol_depth: u32,
979    /// Seconds before killing a formatter subprocess (default: 10).
980    pub formatter_timeout_secs: u32,
981    /// Seconds before killing a type-checker subprocess (default: 30).
982    pub type_checker_timeout_secs: u32,
983    /// Whether to auto-format files after edits (default: false).
984    pub format_on_edit: bool,
985    /// Whether `read`, `outline` and `zoom` accept a `ref` argument that reads
986    /// a file as it is at a git revision (default: false). While it is off,
987    /// the argument is neither advertised nor accepted.
988    pub revision_reads: bool,
989    /// Whether the hashline edit/read surface is enabled for eligible sessions.
990    /// Resolved from the public `edit_mode` enum in aft.jsonc.
991    pub hashline_enabled: bool,
992    /// Optional automatic validation mode after edits (default: None, disabled).
993    /// When "syntax", only tree-sitter parse check. When "full", runs type checker.
994    pub validate_on_edit: Option<String>,
995    /// Per-language formatter overrides. Keys: "typescript", "python", "rust", "go".
996    /// Values: "biome", "oxfmt", "prettier", "deno", "ruff", "black", "rustfmt", "goimports", "gofmt", "none".
997    pub formatter: HashMap<String, String>,
998    /// Per-language type checker overrides. Keys: "typescript", "python", "rust", "go".
999    /// Values: "tsc", "tsgo", "biome", "pyright", "ruff", "cargo", "go", "staticcheck", "none".
1000    pub checker: HashMap<String, String>,
1001    /// Whether to restrict file operations to within `project_root` (default: false).
1002    /// When true, write-capable commands reject paths outside the project root.
1003    pub restrict_to_project_root: bool,
1004    /// Background index switches (all default on).
1005    pub indexes: IndexesConfig,
1006    /// User-tier standing roots. Empty by default, so normal session indexing is unchanged.
1007    pub index: IndexConfig,
1008    /// Whether `aft_search` is registered, which is exactly "`aft_search` is not
1009    /// in `disabled_tools`". It is derived from the resolved disabled list and
1010    /// says nothing about index state or backend presence. Used only to pick
1011    /// the grep-rewrite footer. Not a capability gate.
1012    pub aft_search_registered: bool,
1013    /// Enable experimental bash command rewriting (default: false).
1014    pub experimental_bash_rewrite: bool,
1015    /// Enable experimental bash command compression (default: false).
1016    pub experimental_bash_compress: bool,
1017    /// Enable experimental bash background execution (default: false).
1018    pub experimental_bash_background: bool,
1019    /// Maximum number of background bash tasks allowed to run at once in one
1020    /// project root, shared by all its sessions (default: 8). Only background
1021    /// tasks count, whether local or remote: `background: true` and PTY launches, and foreground
1022    /// commands once promoted to the background. A background launch at the
1023    /// limit is refused with a list of the caller's own tasks holding slots
1024    /// (other sessions' are only counted); a foreground command always starts,
1025    /// and one promoted at the limit keeps
1026    /// running, so the count can briefly exceed the limit.
1027    pub max_background_bash_tasks: usize,
1028    /// Emit reminders for long-running bash tasks (default: true).
1029    pub bash_long_running_reminder_enabled: bool,
1030    /// Milliseconds between long-running bash reminders (default: 10 minutes).
1031    pub bash_long_running_reminder_interval_ms: u64,
1032    /// Milliseconds to wait before a foreground bash task is promoted to background handling.
1033    #[serde(skip, default = "default_foreground_wait_window_ms")]
1034    pub foreground_wait_window_ms: u64,
1035    /// Plugin-owned bash settings accepted by configure but inert in the engine.
1036    pub bash: BashConfig,
1037    pub shell: ShellConfig,
1038    /// Enable OpenCode-style bash permission prompts (default: false).
1039    pub bash_permissions: bool,
1040    /// Native sandbox policy for first-party bash and PTY processes.
1041    pub sandbox: SandboxConfig,
1042    /// Remote runs requested per bash call with `runon`. Off by default.
1043    pub remote_exec: RemoteExecConfig,
1044    /// Maximum file size to fully index in bytes (default: 1MB).
1045    pub search_index_max_file_size: u64,
1046    pub semantic: SemanticBackendConfig,
1047    /// `search.*` settings; today only the optional reranker.
1048    pub search: SearchConfig,
1049    pub inspect: InspectConfig,
1050    pub backup: BackupConfig,
1051    /// Resolved GitHub integration gates. User configuration only.
1052    pub github: GithubConfig,
1053    /// Binary configuration for the managed `gh` shim (no enable state).
1054    pub gh_shim: GhShimConfig,
1055
1056    /// Git attribution for AFT-spawned agent children. Default off.
1057    pub git: GitConfig,
1058    /// Enable Astral ty as an experimental Python LSP server (default: false).
1059    pub experimental_lsp_ty: bool,
1060    /// User-defined LSP servers registered by the OpenCode plugin.
1061    pub lsp_servers: Vec<UserServerDef>,
1062    #[serde(skip)]
1063    #[doc(hidden)]
1064    pub invalid_lsp_initialization_options: Vec<String>,
1065    /// Lowercase LSP server IDs disabled by user config.
1066    pub disabled_lsp: HashSet<String>,
1067    /// Whether the system should request inline diagnostics after a tool call edits or writes a file.
1068    #[serde(skip)]
1069    pub diagnostics_on_edit: bool,
1070    pub lsp_idle_minutes: u32,
1071    pub lsp_idle_shutdown: bool,
1072    /// Maximum live language servers, including reserved starts.
1073    pub lsp_max_servers: usize,
1074    /// Trusted user ceiling before project tightening; not a configure input.
1075    #[serde(skip)]
1076    pub lsp_user_max_servers: Option<usize>,
1077    /// Extra directories to search when resolving LSP binaries.
1078    /// The plugin populates these from its own auto-install cache (e.g.
1079    /// `~/.cache/aft/lsp-packages/<pkg>/node_modules/.bin/`) so an LSP binary
1080    /// installed by AFT is discoverable without needing it on PATH.
1081    /// Resolution order: `<project_root>/node_modules/.bin/<bin>` →
1082    /// `lsp_paths_extra/<bin>` (in order) → PATH via `which`. Python-family
1083    /// servers additionally probe the selected workspace's `.venv`/`venv` first.
1084    pub lsp_paths_extra: Vec<PathBuf>,
1085    /// Binary names the hosting plugin knows how to auto-install.
1086    ///
1087    /// Built-in LSPs discovered from files only emit missing-binary warnings
1088    /// when their binary is in this set. User-configured `lsp_servers` keep
1089    /// warning unconditionally.
1090    pub lsp_auto_install_binaries: HashSet<String>,
1091    /// Binary names with plugin-managed auto-installs currently in flight.
1092    ///
1093    /// Missing-binary warnings are suppressed while the install is actively
1094    /// running; install failure reporting is handled by the plugin after the
1095    /// background work settles.
1096    pub lsp_inflight_installs: HashSet<String>,
1097    /// Persistent storage directory for indexes (trigram, semantic).
1098    /// Set by the plugin to the XDG-compliant path (e.g. ~/.local/share/opencode/storage/plugin/aft/).
1099    /// Falls back to ~/.cache/aft/ if not set.
1100    pub storage_dir: Option<PathBuf>,
1101    /// Allow URL-fetch commands to access private network hosts.
1102    /// Default false; hosting plugins only forward this from user-level config.
1103    pub url_fetch_allow_private: bool,
1104    /// Resolved agent-visible tool names that are not registered, sorted. A
1105    /// tool is registered exactly when its canonical name is absent from this
1106    /// list; the resolver always produces it explicitly (even when empty).
1107    pub disabled_tools: Vec<String>,
1108    /// Hosting harness identity supplied by configure.
1109    #[serde(default)]
1110    pub harness: Option<Harness>,
1111    /// Maximum number of (server, file) entries kept in the in-memory
1112    /// diagnostic cache. Older entries are evicted in LRU order when the
1113    /// cap is exceeded. Set to 0 to disable the cap entirely.
1114    /// Default: 5000 (covers very large monorepos with bounded memory).
1115    pub diagnostic_cache_size: usize,
1116    /// Idle reclamation windows for unbound-root artifacts and language servers.
1117    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            // Default OFF: formatting after an edit can silently reflow the file
1140            // under the agent (a formatter splitting/joining lines), staling the
1141            // context for the next edit/patch. Agents that want formatting opt in
1142            // via `format_on_edit: true`.
1143            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            // Default to false to match OpenCode's existing permission-based model.
1150            // The plugin opts into root restriction explicitly when desired.
1151            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    /// Whether the host's tagged `read` slot is registered, i.e. `read` is not
1208    /// in the resolved disabled list.
1209    ///
1210    /// Only a tagged read mints the `[path#TAG]` snapshots a hashline patch can
1211    /// address, so a session that lost the read slot must not be offered the
1212    /// hashline edit arm. The predicate is deliberately spelled the same way as
1213    /// the plugins' registration check so both sides of the boundary classify a
1214    /// given config identically.
1215    pub fn read_slot_survives(&self) -> bool {
1216        !self.disabled_tools.iter().any(|name| name == "read")
1217    }
1218
1219    /// Whether a canonical tool name is registered under the resolved list.
1220    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        // An unrelated disabled tool leaves the read slot alone.
1249        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        // The index.roots refusal keeps its own key name and exact text.
1323        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;
1331/// Default upper bound for one automatic undo snapshot (64 MiB).
1332pub const DEFAULT_MAX_BACKUP_FILE_SIZE: u64 = 64 * 1024 * 1024;