Skip to main content

aft/
config.rs

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