Skip to main content

aft/
config.rs

1use std::collections::{HashMap, HashSet};
2use std::path::PathBuf;
3
4use serde::{Deserialize, Serialize};
5
6pub(crate) const DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS: u64 = 3_000;
7pub(crate) const MIN_SEMANTIC_QUERY_TIMEOUT_MS: u64 = 500;
8pub(crate) const MAX_SEMANTIC_QUERY_TIMEOUT_MS: u64 = 15_000;
9
10const fn default_semantic_query_timeout_ms() -> u64 {
11    DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS
12}
13
14use crate::harness::Harness;
15
16/// Runtime configuration for the aft process.
17///
18/// Holds project-scoped settings and tuning knobs. Values are set at startup
19/// and remain immutable for the lifetime of the process.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "snake_case")]
22pub enum SemanticBackend {
23    Fastembed,
24    #[serde(rename = "openai_compatible")]
25    OpenAiCompatible,
26    Ollama,
27}
28
29impl SemanticBackend {
30    pub const fn as_str(&self) -> &'static str {
31        match self {
32            Self::Fastembed => "fastembed",
33            Self::OpenAiCompatible => "openai_compatible",
34            Self::Ollama => "ollama",
35        }
36    }
37
38    pub fn from_name(name: &str) -> Option<Self> {
39        match name {
40            "fastembed" => Some(Self::Fastembed),
41            "openai_compatible" => Some(Self::OpenAiCompatible),
42            "ollama" => Some(Self::Ollama),
43            _ => None,
44        }
45    }
46}
47
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49pub struct SemanticBackendConfig {
50    pub backend: SemanticBackend,
51    pub model: String,
52    pub base_url: Option<String>,
53    pub api_key_env: Option<String>,
54    pub timeout_ms: u64,
55    /// Deadline for one interactive query embedding request. Unlike `timeout_ms`,
56    /// this budget never controls background index builds.
57    #[serde(default = "default_semantic_query_timeout_ms")]
58    pub query_timeout_ms: u64,
59    pub max_batch_size: usize,
60    /// Maximum number of project files to semantically index. Guards local
61    /// fastembed memory (model + embeddings + batch buffers) on huge project
62    /// roots; remote backends that embed server-side can raise it freely.
63    pub max_files: usize,
64}
65
66#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
67pub struct UserServerDef {
68    pub id: String,
69    pub extensions: Vec<String>,
70    pub binary: String,
71    pub args: Vec<String>,
72    pub root_markers: Vec<String>,
73    pub env: HashMap<String, String>,
74    pub initialization_options: Option<serde_json::Value>,
75    pub disabled: bool,
76}
77
78impl Default for SemanticBackendConfig {
79    fn default() -> Self {
80        Self {
81            backend: SemanticBackend::Fastembed,
82            model: DEFAULT_SEMANTIC_MODEL.to_string(),
83            base_url: None,
84            api_key_env: None,
85            // Keep the default below the plugin bridge timeout to avoid bridge-killed
86            // semantic_search requests when callers do not set an explicit timeout.
87            timeout_ms: 25_000,
88            query_timeout_ms: DEFAULT_SEMANTIC_QUERY_TIMEOUT_MS,
89            max_batch_size: 64,
90            max_files: 20_000,
91        }
92    }
93}
94
95#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
96#[serde(default)]
97pub struct InspectConfig {
98    pub enabled: bool,
99    pub duplicates: InspectDuplicatesConfig,
100}
101
102#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
103#[serde(default)]
104pub struct InspectDuplicatesConfig {
105    pub expected_mirrors: Vec<[String; 2]>,
106}
107
108impl Default for InspectConfig {
109    fn default() -> Self {
110        Self {
111            enabled: true,
112            duplicates: InspectDuplicatesConfig::default(),
113        }
114    }
115}
116
117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
118#[serde(default)]
119pub struct BackupConfig {
120    pub enabled: Option<bool>,
121    pub max_depth: Option<usize>,
122    pub max_file_size: Option<u64>,
123}
124
125impl Default for BackupConfig {
126    fn default() -> Self {
127        Self {
128            enabled: Some(true),
129            max_depth: Some(crate::backup::DEFAULT_MAX_UNDO_DEPTH),
130            max_file_size: None,
131        }
132    }
133}
134
135pub const DEFAULT_SEMANTIC_MODEL: &str = "all-MiniLM-L6-v2";
136
137impl Config {
138    pub fn semantic_backend_label(&self) -> &'static str {
139        self.semantic.backend.as_str()
140    }
141}
142
143#[derive(Debug, Clone, Serialize, Deserialize)]
144#[serde(default)]
145pub struct Config {
146    /// Root directory of the project being analyzed. `None` if not scoped.
147    pub project_root: Option<PathBuf>,
148    /// How many levels of call-graph edges to follow during validation (default: 1).
149    pub validation_depth: u32,
150    /// Hours before a checkpoint expires and is eligible for cleanup (default: 24).
151    pub checkpoint_ttl_hours: u32,
152    /// Maximum depth for recursive symbol resolution (default: 10).
153    pub max_symbol_depth: u32,
154    /// Seconds before killing a formatter subprocess (default: 10).
155    pub formatter_timeout_secs: u32,
156    /// Seconds before killing a type-checker subprocess (default: 30).
157    pub type_checker_timeout_secs: u32,
158    /// Whether to auto-format files after edits (default: true).
159    pub format_on_edit: bool,
160    /// Whether to auto-validate files after edits (default: false).
161    /// When "syntax", only tree-sitter parse check. When "full", runs type checker.
162    pub validate_on_edit: Option<String>,
163    /// Per-language formatter overrides. Keys: "typescript", "python", "rust", "go".
164    /// Values: "biome", "oxfmt", "prettier", "deno", "ruff", "black", "rustfmt", "goimports", "gofmt", "none".
165    pub formatter: HashMap<String, String>,
166    /// Per-language type checker overrides. Keys: "typescript", "python", "rust", "go".
167    /// Values: "tsc", "tsgo", "biome", "pyright", "ruff", "cargo", "go", "staticcheck", "none".
168    pub checker: HashMap<String, String>,
169    /// Whether to restrict file operations to within `project_root` (default: false).
170    /// When true, write-capable commands reject paths outside the project root.
171    pub restrict_to_project_root: bool,
172    /// Enable the trigram search index (default: false).
173    pub search_index: bool,
174    /// Enable semantic search (default: false).
175    pub semantic_search: bool,
176    /// Whether the plugin registered the `aft_search` tool for this surface
177    /// (default: false). Forwarded by the plugin's resolved registration
178    /// predicate (semantic on + not minimal + not disabled). Used only to pick
179    /// the grep-rewrite footer: when true the footer steers to `aft_search`,
180    /// otherwise to the `grep` tool. Not a capability gate.
181    pub aft_search_registered: bool,
182    /// Enable the persisted callgraph store substrate (default: true).
183    pub callgraph_store: bool,
184    /// Number of files to parse in a single batch during callgraph store cold build (default: 100).
185    /// Lower values reduce peak memory during cold build.
186    /// Set to 0 to disable chunking and parse all files at once.
187    pub callgraph_chunk_size: usize,
188    /// Enable experimental bash command rewriting (default: false).
189    pub experimental_bash_rewrite: bool,
190    /// Enable experimental bash command compression (default: false).
191    pub experimental_bash_compress: bool,
192    /// Enable experimental bash background execution (default: false).
193    pub experimental_bash_background: bool,
194    /// Maximum number of background bash tasks allowed to run concurrently (default: 8).
195    pub max_background_bash_tasks: usize,
196    /// Emit reminders for long-running bash tasks (default: true).
197    pub bash_long_running_reminder_enabled: bool,
198    /// Milliseconds between long-running bash reminders (default: 10 minutes).
199    pub bash_long_running_reminder_interval_ms: u64,
200    /// Milliseconds to wait before a foreground bash task is promoted to background handling.
201    #[serde(skip, default = "default_foreground_wait_window_ms")]
202    pub foreground_wait_window_ms: u64,
203    /// Enable OpenCode-style bash permission prompts (default: false).
204    pub bash_permissions: bool,
205    /// Maximum file size to fully index in bytes (default: 1MB).
206    pub search_index_max_file_size: u64,
207    pub semantic: SemanticBackendConfig,
208    pub inspect: InspectConfig,
209    pub backup: BackupConfig,
210    /// Enable Astral ty as an experimental Python LSP server (default: false).
211    pub experimental_lsp_ty: bool,
212    /// User-defined LSP servers registered by the OpenCode plugin.
213    pub lsp_servers: Vec<UserServerDef>,
214    /// Lowercase LSP server IDs disabled by user config.
215    pub disabled_lsp: HashSet<String>,
216    /// Whether the system should request inline diagnostics after a tool call edits or writes a file.
217    #[serde(skip)]
218    pub diagnostics_on_edit: bool,
219    /// Extra directories to search when resolving LSP binaries.
220    /// The plugin populates these from its own auto-install cache (e.g.
221    /// `~/.cache/aft/lsp-packages/<pkg>/node_modules/.bin/`) so a binary AFT
222    /// installed itself is discoverable without needing it on PATH.
223    /// Resolution order: `<project_root>/node_modules/.bin/<bin>` →
224    /// `lsp_paths_extra/<bin>` (in order) → PATH via `which`.
225    pub lsp_paths_extra: Vec<PathBuf>,
226    /// Binary names the hosting plugin knows how to auto-install.
227    ///
228    /// Built-in LSPs discovered from files only emit missing-binary warnings
229    /// when their binary is in this set. User-configured `lsp_servers` keep
230    /// warning unconditionally.
231    pub lsp_auto_install_binaries: HashSet<String>,
232    /// Binary names with plugin-managed auto-installs currently in flight.
233    ///
234    /// Missing-binary warnings are suppressed while the install is actively
235    /// running; install failure reporting is handled by the plugin after the
236    /// background work settles.
237    pub lsp_inflight_installs: HashSet<String>,
238    /// Persistent storage directory for indexes (trigram, semantic).
239    /// Set by the plugin to the XDG-compliant path (e.g. ~/.local/share/opencode/storage/plugin/aft/).
240    /// Falls back to ~/.cache/aft/ if not set.
241    pub storage_dir: Option<PathBuf>,
242    /// Allow URL-fetch commands to access private network hosts.
243    /// Default false; hosting plugins only forward this from user-level config.
244    pub url_fetch_allow_private: bool,
245    /// Hosting harness identity supplied by configure.
246    #[serde(default)]
247    pub harness: Option<Harness>,
248    /// Maximum number of (server, file) entries kept in the in-memory
249    /// diagnostic cache. Older entries are evicted in LRU order when the
250    /// cap is exceeded. Set to 0 to disable the cap entirely.
251    /// Default: 5000 (covers very large monorepos with bounded memory).
252    pub diagnostic_cache_size: usize,
253}
254
255impl Default for Config {
256    fn default() -> Self {
257        Config {
258            project_root: None,
259            validation_depth: 1,
260            checkpoint_ttl_hours: 24,
261            max_symbol_depth: 10,
262            formatter_timeout_secs: 10,
263            type_checker_timeout_secs: 30,
264            // Default OFF: formatting after an edit can silently reflow the file
265            // under the agent (a formatter splitting/joining lines), staling the
266            // context for the next edit/patch. Agents that want formatting opt in
267            // via `format_on_edit: true`.
268            format_on_edit: false,
269            validate_on_edit: None,
270            formatter: HashMap::new(),
271            checker: HashMap::new(),
272            // Default to false to match OpenCode's existing permission-based model.
273            // The plugin opts into root restriction explicitly when desired.
274            restrict_to_project_root: false,
275            search_index: false,
276            semantic_search: false,
277            aft_search_registered: false,
278            callgraph_store: true,
279            callgraph_chunk_size: 100,
280            experimental_bash_rewrite: false,
281            experimental_bash_compress: false,
282            experimental_bash_background: false,
283            max_background_bash_tasks: 8,
284            bash_long_running_reminder_enabled: true,
285            bash_long_running_reminder_interval_ms: 600_000,
286            foreground_wait_window_ms: default_foreground_wait_window_ms(),
287            bash_permissions: false,
288            search_index_max_file_size: 1_048_576,
289            semantic: SemanticBackendConfig::default(),
290            inspect: InspectConfig::default(),
291            backup: BackupConfig::default(),
292            experimental_lsp_ty: false,
293            lsp_servers: Vec::new(),
294            disabled_lsp: HashSet::new(),
295            diagnostics_on_edit: false,
296            lsp_paths_extra: Vec::new(),
297            lsp_auto_install_binaries: HashSet::new(),
298            lsp_inflight_installs: HashSet::new(),
299            storage_dir: None,
300            url_fetch_allow_private: false,
301            harness: None,
302            diagnostic_cache_size: 5000,
303        }
304    }
305}
306
307fn default_foreground_wait_window_ms() -> u64 {
308    15_000
309}