1use std::collections::{BTreeMap, HashMap, HashSet};
9use std::path::PathBuf;
10
11use serde::de;
12use serde::{Deserialize, Deserializer};
13use serde_json::{Map, Value};
14
15use crate::config::{
16 expand_index_root_path, normalize_git_co_author, BackupConfig, Config, GhShimConfig, GitConfig,
17 GithubConfig, IdleConfig, IndexConfig, IndexKind, IndexRootConfig, IndexesConfig,
18 InspectCategories, InspectConfig, RemoteExecConfig, RerankBackendKind, RerankConfig,
19 SandboxConfig, SearchConfig, SemanticBackend, SemanticBackendConfig, UserServerDef,
20 DEFAULT_BASH_WATCH_SYNC_MAX_MS, DEFAULT_BASH_WORKER_WAIT_MAX_MS, DEFAULT_IDLE_ROOT_TTL_MINUTES,
21 DEFAULT_INSPECT_DIAGNOSTICS_TIMEOUT_MS, MAX_BASH_WATCH_SYNC_MAX_MS, MAX_IDLE_ROOT_TTL_MINUTES,
22 MAX_INSPECT_DIAGNOSTICS_TIMEOUT_MS, MAX_SEMANTIC_QUERY_TIMEOUT_MS, MIN_BASH_WATCH_SYNC_MAX_MS,
23 MIN_BASH_WORKER_WAIT_MAX_MS, MIN_IDLE_ROOT_TTL_MINUTES, MIN_INSPECT_DIAGNOSTICS_TIMEOUT_MS,
24 MIN_SEMANTIC_QUERY_TIMEOUT_MS,
25};
26use crate::feature_config;
27use crate::harness::Harness;
28use crate::jsonc::strip_jsonc;
29
30mod parsed;
31pub mod schema;
32pub(crate) use parsed::ParsedConfigDocument;
33
34const FOREGROUND_WAIT_WINDOW_DEFAULT_MS: u64 = 15_000;
35const FOREGROUND_WAIT_WINDOW_MIN_MS: u64 = 5_000;
36
37const MAX_SEMANTIC_TIMEOUT_MS: u64 = 120_000;
41const MAX_SEMANTIC_BATCH_SIZE: usize = 1_024;
42
43const USER_ONLY_REASON: &str =
44 "security: this setting only honors user-level config and project values are ignored";
45const SEMANTIC_SECRET_REASON: &str =
46 "security: semantic backend credentials and endpoints must come from user-level config";
47const PROTECTED_TOOL_REASON: &str =
48 "security: a project config cannot disable aft_safety or a host tool slot (read, write, edit, apply_patch, grep, glob, bash)";
49const LSP_USER_ONLY_REASON: &str =
50 "security: LSP executable-origin and diagnostic-suppression settings must come from user-level config";
51const REMOTE_EXEC_PROJECT_REASON: &str =
52 "security: a project config may only turn remote_exec off; enabling remote runs and choosing their runner must come from user-level config";
53const RERANK_PROJECT_REASON: &str =
54 "security: a project config may only turn search.rerank off; every other rerank setting must come from user-level config";
55
56#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct ConfigTier {
62 pub tier: String,
63 pub source: String,
64 pub doc: String,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct DroppedKey {
70 pub key: String,
71 pub tier: String,
72 pub reason: String,
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct ConfigWarning {
78 pub code: &'static str,
79 pub key: &'static str,
80 pub tier: String,
81 pub value: String,
82 pub message: String,
83}
84
85#[derive(Debug, Clone, Default, PartialEq, Eq)]
87pub struct ResolveDiagnostics {
88 pub dropped: Vec<DroppedKey>,
89 pub warnings: Vec<ConfigWarning>,
90 pub errors: Vec<String>,
93}
94
95#[derive(Debug, Clone)]
97pub struct ResolveResult {
98 pub config: Config,
99 pub dropped: Vec<DroppedKey>,
100 pub warnings: Vec<ConfigWarning>,
101 pub errors: Vec<String>,
106}
107
108#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
112#[serde(default, deny_unknown_fields)]
113#[schemars(
114 description = "Configuration schema for the @cortexkit/aft-opencode and @cortexkit/aft-pi plugins. Place as aft.jsonc in ~/.config/opencode/, <project>/.opencode/, ~/.pi/agent/, or <project>/.pi/."
115)]
116pub struct RawAftConfig {
117 #[schemars(
118 description = "Machine-local resource profile, user config base only. lean uses less memory and can build more slowly: it uses a smaller shared block cache, four call-graph resolver threads on Linux and macOS, and immediate freed-memory return on Linux. Windows keeps all CPUs. balanced keeps the previous limits. When unset, total physical RAM selects lean below 8 GiB, otherwise balanced; unreadable RAM selects balanced. Changes apply to subsequent builds and shared block cache sizing without a restart. Other limits and meaning-search settings stay unchanged."
119 )]
120 pub memory: Option<crate::memory_profile::MemoryMode>,
121 #[schemars(
122 description = "Process-wide file flush policy from the user config base only. Project values and all harness overrides have no effect."
123 )]
124 pub durability: Option<RawDurability>,
125 #[schemars(
126 description = "Storage-wide settings from the user config base only. Project values and every harness override are ignored."
127 )]
128 pub storage: Option<RawStorage>,
129 #[serde(rename = "$schema")]
130 pub schema: Option<String>,
131 #[schemars(
132 description = "Select the edit/read surface. Hashline mode renders tagged reads and changes edit arguments to exactly { patch }."
133 )]
134 pub edit_mode: Option<RawEditMode>,
135 #[schemars(
136 description = "Auto-format files after edits with the language's configured formatter. Default false: formatting can reflow the file under the agent and stale the next edit's context."
137 )]
138 pub format_on_edit: Option<bool>,
139 #[schemars(
140 description = "Let read, aft_outline and aft_zoom take a `ref` argument that reads a file as it is at a git revision (branch, tag, SHA, or forms like HEAD~2) from the repository's object store, without touching the working tree. Default false: the argument is not offered and a call that passes it is refused."
141 )]
142 pub revision_reads: Option<bool>,
143 #[serde(deserialize_with = "deserialize_opt_timeout_secs")]
144 #[schemars(range(min = 1, max = 600))]
145 #[schemars(
146 description = "Maximum seconds an external formatter is allowed to run before AFT kills it and reports `format_skipped_reason: \"timeout\"`. Raise for slow formatters in large projects."
147 )]
148 pub formatter_timeout_secs: Option<u32>,
149 #[serde(deserialize_with = "deserialize_opt_timeout_secs")]
150 #[schemars(range(min = 1, max = 600))]
151 #[schemars(
152 description = "Maximum time in seconds for an external type checker to run. The default is 30 seconds."
153 )]
154 pub type_checker_timeout_secs: Option<u32>,
155 #[schemars(
156 description = "Auto-validate after edits: 'syntax' (tree-sitter parse check) or 'full' (also runs type checker)."
157 )]
158 pub validate_on_edit: Option<RawValidateOnEdit>,
159 #[schemars(
160 description = "Per-language formatter overrides keyed by language (e.g. 'typescript', 'python', 'rust', 'go')."
161 )]
162 pub formatter: Option<HashMap<String, RawFormatter>>,
163 #[schemars(
164 description = "Per-language type checker overrides keyed by language (e.g. 'typescript', 'python', 'rust', 'go')."
165 )]
166 pub checker: Option<HashMap<String, RawChecker>>,
167 #[schemars(
168 description = "How missing formatter/checker/LSP binary warnings are shown after configure. 'toast' (default) uses a 10s TUI or HTTP toast without adding session chat messages. 'log' writes to the plugin log only. 'chat' uses legacy ignored user messages in the session transcript. Warnings for formatters/checkers are only emitted when format_on_edit is true or a per-language formatter is set; checker warnings require validate_on_edit 'syntax' or 'full' or an explicit checker. There is no top-level 'formatters' key — use format_on_edit, formatter, and checker instead."
169 )]
170 pub configure_warnings_delivery: Option<RawConfigureWarningsDelivery>,
171 #[schemars(
174 description = "Tool names that are not registered; every other AFT tool is registered. When absent from the user config it defaults to [\"aft_move\", \"aft_delete\"]; an explicit list (including []) replaces that default. Host tool names ('read', 'grep', 'bash', ...) leave the host's own tool in place. Project config may only add names and cannot disable aft_safety or a host tool slot."
175 )]
176 pub disabled_tools: Option<Vec<String>>,
177 #[schemars(
178 description = "Restrict file operations to within project root. When true, write-capable commands reject paths outside project_root. Default: false (matches OpenCode built-in behavior)."
179 )]
180 pub restrict_to_project_root: Option<bool>,
181 #[schemars(
182 description = "Background indexes. Each defaults on and builds independently of which tools are registered. Project config can only turn an index off."
183 )]
184 pub indexes: Option<RawIndexes>,
185 #[schemars(
186 description = "Configure indexes for folders even when no session is open in them. By default, no folders are configured for standing indexing."
187 )]
188 pub index: Option<RawIndex>,
189 #[schemars(
190 description = "Codebase health inspection config. Enabled by default; set inspect.enabled=false to hide aft_inspect."
191 )]
192 pub inspect: Option<RawInspect>,
193 #[schemars(
194 description = "Idle windows: when an unbound root's indexes are evicted, and when an unused checkout drops its in-memory index state."
195 )]
196 pub idle: Option<RawIdle>,
197 pub backup: Option<RawBackup>,
198 #[schemars(
199 description = "User-scoped GitHub integration gates. Project config cannot change capabilities or host-wide tool descriptions."
200 )]
201 pub github: Option<RawGithub>,
202 #[schemars(
203 description = "Managed gh shim binary override. Whether the shim is used is github.shim; binary_path is the advanced AFT-image override."
204 )]
205 pub gh_shim: Option<RawGhShim>,
206 #[schemars(
207 description = "Agent-child Git attribution injected through environment-scoped core.hooksPath configuration."
208 )]
209 pub git: Option<RawGit>,
210 #[schemars(description = "Pi and OMP harness-specific configuration.")]
211 pub pi: Option<RawPi>,
212 #[schemars(
213 description = "Shell sandbox profiles: stamped workers default to relaxed, all other sessions to off; untrusted routes always use strict."
214 )]
215 pub sandbox: Option<RawSandbox>,
216 #[schemars(
217 description = "Bash runtime configuration (runtime gate + rewrite + compress + background execution and user-only environment defaults). Registration of bash and its companions is controlled by disabled_tools. Replaces `experimental.bash.*`."
218 )]
219 pub bash: Option<RawBashFeatures>,
220 #[schemars(
221 description = "User-only shell environment settings. Project configuration cannot select an environment provider."
222 )]
223 pub shell: Option<crate::config::ShellConfig>,
224 #[schemars(description = "Experimental opt-in features. May change between releases.")]
225 pub experimental: Option<RawExperimental>,
226 #[schemars(description = "User-defined and built-in LSP server configuration.")]
227 pub lsp: Option<RawLsp>,
228 #[schemars(
229 description = "Allow `aft_outline`/`aft_zoom` URL fetches to request private/link-local hosts. Default: false (rejects RFC1918, loopback, and link-local)."
230 )]
231 pub url_fetch_allow_private: Option<bool>,
232 #[schemars(
233 description = "External semantic backend configuration for embedding and retrieval."
234 )]
235 pub semantic: Option<RawSemantic>,
236 #[schemars(description = "aft_search settings.")]
237 pub search: Option<RawSearch>,
238 #[schemars(
239 description = "OpenCode only: auto-refresh the cached @cortexkit/aft-opencode package when a newer channel version is published. User-scoped only — project configs cannot disable updates silently."
240 )]
241 pub auto_update: Option<bool>,
242 #[schemars(
243 description = "Shared NDJSON bridge transport tuning (OpenCode and Pi). User-scoped only — project configs cannot set this block (bridge safety and per-machine transport budget)."
244 )]
245 pub bridge: Option<RawBridge>,
246 #[schemars(
247 description = "Subconscious (subc) daemon transport selection. User-scoped only — a project config cannot redirect transport. Presence of connection_file switches AFT from a spawned child process to a daemon-supervised module."
248 )]
249 pub subc: Option<RawSubc>,
250
251 #[schemars(
252 description = "Remote runs requested per bash call with runon. See docs/tools.md (bash: running on the remote build server)."
253 )]
254 pub remote_exec: Option<RawRemoteExec>,
255 #[serde(skip)]
258 pub remote_exec_project_off: bool,
259 #[schemars(
262 description = "Per-harness overrides. The active harness applies its override after the base config within each tier: user base, user override, project base, project override. storage.cache_dir, durability.macos_full_sync and memory apply to the whole process; none can be overridden here. Nested harnesses are ignored; unknown harness names are reserved for forward compatibility."
263 )]
264 pub harnesses: Option<BTreeMap<String, Value>>,
265}
266
267#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
268#[serde(default, deny_unknown_fields)]
269pub struct RawDurability {
270 #[schemars(
271 description = "On macOS, restore F_FULLFSYNC drive-cache flushes instead of faster plain fsync. Plain fsync can lose recent writes on power loss, but adds no loss on daemon kill or OS crash. Applies to AFT files and directories, not SQLite; ignored on Linux and Windows. Takes effect on the next sync."
272 )]
273 pub macos_full_sync: Option<bool>,
274}
275
276#[derive(Debug, Clone, PartialEq, Eq)]
277pub enum RawEditMode {
278 Default,
279 Hashline,
280 Unknown(String),
281}
282
283impl<'de> Deserialize<'de> for RawEditMode {
284 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
285 where
286 D: Deserializer<'de>,
287 {
288 let value = String::deserialize(deserializer)?;
289 Ok(match value.as_str() {
290 "default" => Self::Default,
291 "hashline" => Self::Hashline,
292 _ => Self::Unknown(value),
293 })
294 }
295}
296
297#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
298#[serde(rename_all = "snake_case")]
299pub enum RawValidateOnEdit {
300 Syntax,
301 Full,
302}
303
304impl RawValidateOnEdit {
305 const fn as_str(self) -> &'static str {
306 match self {
307 Self::Syntax => "syntax",
308 Self::Full => "full",
309 }
310 }
311}
312
313#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
314#[serde(rename_all = "snake_case")]
315pub enum RawFormatter {
316 Biome,
317 Oxfmt,
318 Prettier,
319 Deno,
320 Ruff,
321 Black,
322 Rustfmt,
323 Goimports,
324 Gofmt,
325 None,
326}
327
328impl RawFormatter {
329 const fn as_str(self) -> &'static str {
330 match self {
331 Self::Biome => "biome",
332 Self::Oxfmt => "oxfmt",
333 Self::Prettier => "prettier",
334 Self::Deno => "deno",
335 Self::Ruff => "ruff",
336 Self::Black => "black",
337 Self::Rustfmt => "rustfmt",
338 Self::Goimports => "goimports",
339 Self::Gofmt => "gofmt",
340 Self::None => "none",
341 }
342 }
343}
344
345#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
346#[serde(rename_all = "snake_case")]
347pub enum RawChecker {
348 Tsc,
349 Tsgo,
350 Biome,
351 Pyright,
352 Ruff,
353 Cargo,
354 Go,
355 Staticcheck,
356 None,
357}
358
359impl RawChecker {
360 const fn as_str(self) -> &'static str {
361 match self {
362 Self::Tsc => "tsc",
363 Self::Tsgo => "tsgo",
364 Self::Biome => "biome",
365 Self::Pyright => "pyright",
366 Self::Ruff => "ruff",
367 Self::Cargo => "cargo",
368 Self::Go => "go",
369 Self::Staticcheck => "staticcheck",
370 Self::None => "none",
371 }
372 }
373}
374
375#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
376#[serde(rename_all = "snake_case")]
377pub enum RawConfigureWarningsDelivery {
378 Toast,
379 Log,
380 Chat,
381}
382
383#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
385#[serde(default)]
386pub struct RawIndexes {
387 #[schemars(
388 description = "Trigram index for indexed grep/glob and the lexical aft_search lane. With false, no text index is built, and grep and glob walk the folder."
389 )]
390 pub trigram: Option<bool>,
391 #[schemars(
392 description = "Semantic (embedding) index for the semantic aft_search lane. The default local backend may download an ONNX runtime and model and use CPU."
393 )]
394 pub semantic: Option<bool>,
395 #[schemars(description = "Persisted call-graph store used by aft_callgraph and enrichment.")]
396 pub callgraph: Option<bool>,
397}
398
399#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
400#[serde(default)]
401pub struct RawStorage {
402 #[schemars(
403 description = "Existing absolute cache parent (~ is expanded); AFT creates only its marked aft/ namespace. A path through symlinks is resolved once when first used and pinned by device and inode; if it later names a different directory, or is missing, unwritable or identity-changed, all disk caches turn off with cache_dir_unavailable and never fall back to storage. Rechecked on binds and at most once a minute. First enrollment requires a different device from durable storage; cache_dir_on_storage_device refuses main-disk mount stubs on every platform. Once a storage root has used a cache directory, removing this key keeps caches off; set it to null to move caches back to the storage root. Only the user config base may set this; harness/project overrides are dropped. Old caches are not migrated; doctor --fix reclaims only identity- and ownership-verified inactive cache domains. Choose default for the same behavior as omitting the setting; choose main_disk to return caches to the storage root (the old null spelling); choose dir with path to use a cache parent.",
404 with = "RawCacheDir"
405 )]
406 pub cache_dir: Option<RawCacheDir>,
407}
408
409#[derive(Debug, Clone, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
410#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
411pub enum RawCacheDir {
412 Default {},
413 MainDisk {},
414 Dir { path: String },
415}
416
417#[derive(Debug, Clone, Deserialize, PartialEq, schemars::JsonSchema)]
418pub struct RawSemantic {
423 #[schemars(
424 description = "Embedding backend. 'fastembed' uses local ONNX runtime, 'openai_compatible' calls a configured OpenAI-style API, 'ollama' calls a local Ollama embedding endpoint, and 'synapse' dials CortexKit Synapse over SubC."
425 )]
426 pub backend: Option<SemanticBackend>,
427 #[serde(default, deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
428 #[schemars(
429 description = "Model identifier passed to the backend. Required for synapse; fastembed defaults to all-MiniLM-L6-v2."
430 )]
431 pub model: Option<String>,
432 #[serde(default, deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
433 #[schemars(
434 description = "Base URL of the backend API endpoint. Required for openai_compatible. Default for ollama: http://localhost:11434."
435 )]
436 pub base_url: Option<String>,
437 #[serde(default, deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
438 #[schemars(
439 description = "Environment variable name containing the API key (e.g. 'OPENAI_API_KEY'). Project-scoped configs cannot set this field — only user-scoped configs can."
440 )]
441 pub api_key_env: Option<String>,
442 #[serde(default, deserialize_with = "deserialize_opt_positive_u64")]
445 #[schemars(description = "Background build embedding request timeout in milliseconds.")]
446 pub timeout_ms: Option<u64>,
447 #[serde(default, deserialize_with = "deserialize_opt_positive_u64")]
448 #[schemars(
449 description = "Interactive query embedding deadline in milliseconds. Project-scoped configs cannot set this field; values are clamped to 500..30000."
450 )]
451 pub query_timeout_ms: Option<u64>,
452 #[serde(default, deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
453 #[schemars(
454 description = "Query-only task instruction sent to the embedding backend: \"auto\" applies the model family's documented recipe (Qwen3-Embedding: the model-card retrieval task; fastembed and other families stay bare), \"off\" sends bare queries, any other value is used as literal task text. Never changes document vectors or the index fingerprint."
455 )]
456 pub query_instruction: Option<String>,
457 #[serde(default, deserialize_with = "deserialize_opt_positive_usize")]
458 #[schemars(description = "Maximum batch size used by the semantic embedding pipeline.")]
459 pub max_batch_size: Option<usize>,
460 #[serde(default, deserialize_with = "deserialize_opt_positive_usize")]
461 #[schemars(
462 description = "Whole-row input token budget for remote embedding backends. Absent keeps the MiniLM-era chunk caps. Fingerprinted: changing it rebuilds the semantic index."
463 )]
464 pub max_input_tokens: Option<usize>,
465 #[serde(default, deserialize_with = "deserialize_opt_positive_usize")]
466 #[schemars(
467 description = "Most project files to embed for semantic search (default 20000): a limit on embedding cost and time; files past it are not embedded. Raise it for remote backends that embed server-side."
468 )]
469 pub max_files: Option<usize>,
470}
471
472impl RawSemantic {
473 fn is_empty(&self) -> bool {
474 self.backend.is_none()
475 && self.model.is_none()
476 && self.base_url.is_none()
477 && self.api_key_env.is_none()
478 && self.timeout_ms.is_none()
479 && self.query_timeout_ms.is_none()
480 && self.query_instruction.is_none()
481 && self.max_batch_size.is_none()
482 && self.max_input_tokens.is_none()
483 && self.max_files.is_none()
484 }
485}
486
487#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
488#[serde(default)]
489pub struct RawSearch {
490 #[schemars(
491 description = "Optional cross-encoder reranking of aft_search results. Default off."
492 )]
493 pub rerank: Option<RawRerank>,
494}
495
496#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
499#[serde(default)]
500pub struct RawRerank {
501 #[schemars(
502 description = "Cross-encoder reranker for the head of aft_search results. Only prose questions are reranked, and exact matches keep their order. 'off' keeps fused order, 'onnx' runs a local model through ONNX Runtime (downloaded in the background on first use), 'remote' calls a Cohere-style /rerank endpoint, 'synapse' uses CortexKit Synapse. A project config may only set 'off'."
503 )]
504 pub backend: Option<RerankBackendKind>,
505 #[serde(deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
506 #[schemars(
507 description = "Reranker model. For onnx: bge-reranker-base (default), bge-reranker-v2-m3, jina-reranker-v1-turbo or gte-reranker-modernbert-base. Required for remote and synapse. User config only."
508 )]
509 pub model: Option<String>,
510 #[serde(deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
511 #[schemars(
512 description = "Base URL of the remote rerank endpoint; AFT appends /rerank. Prefix with tei+ for a TEI server. User config only."
513 )]
514 pub endpoint: Option<String>,
515 #[serde(deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
516 #[schemars(
517 description = "Environment variable holding the remote rerank endpoint's API key. User config only."
518 )]
519 pub api_key_env: Option<String>,
520 #[serde(deserialize_with = "deserialize_opt_positive_u64")]
521 #[schemars(
522 description = "How many leading results are reranked (default 20, at most 200). User config only."
523 )]
524 pub top_n: Option<u64>,
525 #[serde(deserialize_with = "deserialize_opt_positive_u64")]
526 #[schemars(
527 description = "Reranking budget per search in milliseconds (default 1500, clamped to 50..15000). On timeout the fused order is kept. User config only."
528 )]
529 pub timeout_ms: Option<u64>,
530}
531
532#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
533pub struct RawLsp {
534 #[schemars(
535 description = "Minutes since the last AFT tool call on that repository. Default 60; integers are clamped to 5..=1440. Project config may only lower the user value. Applies live."
536 )]
537 pub idle_minutes: Option<i64>,
538 #[schemars(
539 description = "Shut down idle language servers (default true). When false, servers still stop on unbind, eviction and shutdown. A project may turn idle shutdown on, never off. Applies live."
540 )]
541 pub idle_shutdown: Option<bool>,
542 #[schemars(
543 description = "Maximum live language servers process-wide, including starts in progress. Evicts the least recently used client with no pending requests before refusing a start. Project config may only lower the user value. Zero prevents new starts."
544 )]
545 pub max_servers: Option<usize>,
546 #[serde(default, deserialize_with = "deserialize_opt_lsp_servers")]
547 #[schemars(
548 description = "User-defined LSP server map keyed by server id (e.g. { 'terraform-ls': { ... } })."
549 )]
550 pub servers: Option<BTreeMap<String, RawLspServerEntry>>,
551 #[serde(
552 default,
553 deserialize_with = "deserialize_opt_trimmed_non_empty_string_vec"
554 )]
555 #[schemars(
556 description = "Built-in LSP server ids to disable (e.g. ['python', 'biome']). See README for the full list."
557 )]
558 pub disabled: Option<Vec<String>>,
559 #[schemars(
560 description = "Which Python LSP to use. 'auto' stays on Pyright while ty is experimental; select 'ty' explicitly to opt in without fallback."
561 )]
562 pub python: Option<RawPythonLsp>,
563 #[schemars(
564 description = "Wait for inline LSP diagnostics on every edit/write/apply_patch call. Default: false."
565 )]
566 pub diagnostics_on_edit: Option<bool>,
567 #[schemars(
568 description = "Auto-install npm-distributed and GitHub-release LSP servers when the project needs them. Set false to require manual install on PATH."
569 )]
570 pub auto_install: Option<bool>,
571 #[serde(default, deserialize_with = "deserialize_opt_positive_u64")]
572 #[schemars(
573 description = "Supply-chain grace window. AFT only installs versions that have been on the registry / GitHub releases for at least this many days. User pins via `lsp.versions` bypass this."
574 )]
575 pub grace_days: Option<u64>,
576 #[serde(default, deserialize_with = "deserialize_opt_versions_map")]
577 #[schemars(
578 description = "Per-package version pin map keyed by npm package or GitHub repo. Pins bypass the grace filter and any weekly version recheck (e.g. { 'typescript-language-server': '5.0.0', 'clangd/clangd': '21.1.0' })."
579 )]
580 pub versions: Option<HashMap<String, String>>,
581}
582
583impl RawLsp {
584 fn is_empty(&self) -> bool {
585 self.idle_minutes.is_none()
586 && self.idle_shutdown.is_none()
587 && self.max_servers.is_none()
588 && self.servers.is_none()
589 && self.disabled.is_none()
590 && self.python.is_none()
591 && self.diagnostics_on_edit.is_none()
592 && self.auto_install.is_none()
593 && self.grace_days.is_none()
594 && self.versions.is_none()
595 }
596}
597
598#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
599#[serde(rename_all = "snake_case")]
600pub enum RawPythonLsp {
601 Pyright,
602 Ty,
603 Auto,
604}
605
606#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
607#[serde(default)]
608pub struct RawLspServerEntry {
609 #[serde(deserialize_with = "deserialize_opt_lsp_extensions")]
610 #[schemars(
611 description = "File extensions this server handles (e.g. ['.tf', '.tfvars']). Optional when overriding a built-in server — the built-in's extensions are inherited."
612 )]
613 pub extensions: Option<Vec<String>>,
614 #[serde(deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
615 #[schemars(
616 description = "LSP binary command (must be on PATH or absolute path). Optional when overriding a built-in server — the built-in's binary is inherited."
617 )]
618 pub binary: Option<String>,
619 #[schemars(description = "Extra command-line arguments passed to the LSP binary.")]
620 pub args: Option<Vec<String>>,
621 #[serde(deserialize_with = "deserialize_opt_trimmed_non_empty_string_vec")]
622 #[schemars(
623 description = "Workspace root marker files. AFT walks up from each opened file looking for any of these."
624 )]
625 pub root_markers: Option<Vec<String>>,
626 #[schemars(description = "Disable this server entirely without removing the config block.")]
627 pub disabled: Option<bool>,
628 #[schemars(
629 description = "Extra environment variables passed to the LSP server child process."
630 )]
631 pub env: Option<HashMap<String, String>>,
632 #[schemars(
633 description = "JSON text passed as `initializationOptions` in the LSP `initialize` request. Invalid JSON prevents this server from starting."
634 )]
635 pub initialization_options: Option<String>,
636}
637
638#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
639#[serde(default)]
640pub struct RawBashFeatures {
641 #[schemars(
642 description = "Report watcher-observed project changes after bash commands. User opt-in; projects may only set off. Diff mode uses clean git before-images and bounded output."
643 )]
644 pub changed_files: Option<crate::config::BashChangedFiles>,
645 #[schemars(
647 description = "Runtime gate for every bash operation, including bash_status/bash_write/bash_watch/bash_kill. When false they report bash_disabled; registration is controlled by disabled_tools."
648 )]
649 pub enabled: Option<bool>,
650 #[schemars(
651 description = "Rewrite common bash commands (cat, grep, find, sed, ls) into AFT tool calls for faster, formatted output."
652 )]
653 pub rewrite: Option<bool>,
654 #[schemars(
655 description = "Compress bash output via per-tool compressors (git, cargo, npm, bun, pnpm, pytest, tsc, eslint, biome, vitest, prettier, ruff, mypy, go, golangci-lint, playwright, next) plus TOML filter pipeline. Adds `[cmpaft]` marker."
656 )]
657 pub compress: Option<bool>,
658 #[schemars(
659 description = "Allow agents to launch bash with `{ background: true }` for long-running tasks. Foreground bash always auto-promotes to background after the foreground wait window (default 8s) regardless of this flag."
660 )]
661 pub background: Option<bool>,
662 #[schemars(
663 description = "Break-glass host execution when AFT's module transport is unavailable. Project-settable. Every fallback command requires a fresh host permission prompt and runs without AFT rewrites, compression, or background support."
664 )]
665 pub host_fallback: Option<bool>,
666 #[schemars(
667 description = "Allow subagents to run background bash. Default true because workers are multi-turn and wait with bash_watch; when false, subagent `background: true` requests are converted to foreground calls that block up to the hard cap."
668 )]
669 pub subagent_background: Option<bool>,
670 #[schemars(
671 description = "Detach a `wait: true` bash call when a new user message arrives. Default true. Set false to keep the wait blocking; a message containing the literal `&detach` still forces detachment, the token is stripped before delivery and the rest of the message is preserved; a token-only message becomes `(requested background detach)`. Project-safe."
672 )]
673 pub detach_on_user_message: Option<bool>,
674 #[schemars(
675 description = "Append AFT read-only database schema hints after missing-table or missing-column errors. SQLite on Unix only; supported literal database paths only. Project-safe."
676 )]
677 pub db_schema_hints: Option<bool>,
678 #[schemars(
679 description = "Periodically remind the agent that a background bash task is still running. When false, completion is delivered but mid-flight reminders are suppressed."
680 )]
681 pub long_running_reminder_enabled: Option<bool>,
682 #[serde(deserialize_with = "deserialize_opt_positive_u64")]
683 #[schemars(
684 description = "Interval in milliseconds between mid-flight reminders for a still-running background bash task."
685 )]
686 pub long_running_reminder_interval_ms: Option<u64>,
687 #[serde(deserialize_with = "deserialize_opt_positive_u64")]
688 #[schemars(
689 description = "How long foreground bash blocks before auto-promoting the task to background, in milliseconds. Minimum 5000; values below the floor are clamped up."
690 )]
691 pub foreground_wait_window_ms: Option<u64>,
692 #[serde(deserialize_with = "deserialize_opt_positive_u64")]
693 #[schemars(
694 description = "Maximum synchronous bash_watch wait in milliseconds. Defaults to 120 seconds for short remaining waits; set to 1800000 to restore the old 30-minute cap."
695 )]
696 pub watch_sync_max_ms: Option<u64>,
697 #[serde(deserialize_with = "deserialize_opt_worker_wait_max_ms")]
698 #[schemars(
699 description = "Longest a delegated worker (subagent) waits on one command before control returns to it, in milliseconds: a bash_watch without a timeout, or a bash call that blocks until the command finishes (wait: true, or every foreground call when subagent_background is false). The command keeps running in the background; the worker is told it is still running and can wait again or kill it. While a worker keeps waiting, the command's default 30-minute hard kill is pushed back by this much. Default 1800000 (30 minutes); values below 60000 are a config error. Project-safe."
700 )]
701 pub worker_wait_max_ms: Option<u64>,
702 #[schemars(
703 description = "Linux daemon scopes are on by default (user config only). User config can disable them. Standalone mode, PTY tasks, and native-sandbox launches use the usual spawn path. If systemd-run, the user manager, or cgroup access is unavailable, AFT uses the usual path."
704 )]
705 pub linux_scope: Option<bool>,
706 #[serde(deserialize_with = "deserialize_opt_linux_scope_max_runtime_secs")]
707 #[schemars(range(min = 1, max = 4294967295_u64))]
708 #[schemars(
709 description = "User-only Linux daemon scope ceiling in seconds. Worker waits do not extend it. An explicit timeout uses its own limit plus 60 seconds."
710 )]
711 pub linux_scope_max_runtime_secs: Option<u64>,
712 #[serde(deserialize_with = "deserialize_opt_memory_limit_mib")]
713 #[schemars(range(min = 1, max = 4294967295_u64))]
714 #[schemars(
715 description = "Optional aggregate local-command memory cap in MiB. Off by default; projects may only lower a user cap. Remote runon jobs use server limits."
716 )]
717 pub memory_limit_mib: Option<u64>,
718 #[schemars(
719 description = "On macOS, agent shells and governed gh commands do not inherit the supervisor's privacy grants. Default false. Live for future commands; user tier controls it and projects may only enable it. Protected folders such as ~/Downloads should be read with AFT's read tool. Accepted but inert on other platforms; unavailable spawn attributes refuse the command instead of inheriting grants."
720 )]
721 pub disclaim_privacy: Option<bool>,
722 #[schemars(
723 description = "Pi-only fallback for manually mirroring Pi's optional PowerShell default tool when the host does not expose its enabled-tool registry. OpenCode never registers this tool."
724 )]
725 pub powershell_tool: Option<bool>,
726 #[schemars(
727 description = "Fixed environment variables for local shell commands, at either tier. A project's names apply only while the project is trusted (aft doctor filters trust; a linked worktree inherits its main checkout); a user value wins when both tiers set the same name, and the first bash reply in a session names each applied variable with its tier, never its value. Per-call env values and the command's own export both override these. Names that hijack startup, redirect lookup roots, inject into interpreters or Git, or drive AFT, the sandbox, or a build worker are rejected at every tier; credentials, identity, proxy, and TLS-trust names are rejected at the project tier. These values never reach a runon build-server job unless a user name is listed in bash.runon_env."
728 )]
729 pub env: Option<BTreeMap<String, String>>,
730 #[serde(skip)]
733 pub project_env: Option<BTreeMap<String, String>>,
734 #[schemars(
736 description = "User-only list of bash.env names that are also sent to a runon build-server job. Every other bash.env value applies to local commands only; a project's values are never sent, even when their name is listed. Unlisted names appear in the job's \"does not receive\" disclosure."
737 )]
738 pub runon_env: Option<Vec<String>>,
739}
740
741#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
742#[serde(default)]
743pub struct RawExperimental {
744 #[schemars(
745 description = "Run the experimental Python `ty` type checker alongside Pyright. Use lsp.python = 'ty' to select ty exclusively."
746 )]
747 pub lsp_ty: Option<bool>,
748}
749
750impl RawExperimental {
751 fn is_empty(&self) -> bool {
752 self.lsp_ty.is_none()
753 }
754}
755
756#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
757#[serde(default)]
758pub struct RawInspect {
759 #[schemars(
760 description = "Runtime switch for aft_inspect. Defaults to true. When false the registered tool reports inspect_disabled; use disabled_tools to unregister it."
761 )]
762 pub enabled: Option<bool>,
763 #[serde(default, deserialize_with = "deserialize_opt_positive_u64")]
764 #[schemars(
765 description = "Blocking LSP diagnostics deadline in milliseconds. Values are clamped to 10000..600000. User config sets the baseline; project config may only raise the effective deadline so a repository cannot silently reduce diagnostic completeness for another consumer."
766 )]
767 pub diagnostics_timeout_ms: Option<u64>,
768 #[serde(default, deserialize_with = "deserialize_opt_positive_u64")]
769 #[schemars(
770 description = "Hard deadline for one Tier-2 pass, including projection and scanning. On expiry AFT cooperatively cancels the pass and releases its cold-build slot."
771 )]
772 pub tier2_pass_timeout_ms: Option<u64>,
773 #[serde(deserialize_with = "deserialize_opt_inspect_categories")]
774 #[schemars(with = "Option<InspectCategories>")]
775 #[schemars(
776 description = "Per-category computation switches, all true by default. Off categories run no scans or refreshes and render as off, never incomplete. Project config may only turn a category off."
777 )]
778 pub categories: Option<BTreeMap<String, bool>>,
779 #[schemars(description = "Duplicate suppression config for the duplicates inspect category.")]
780 pub duplicates: Option<RawInspectDuplicates>,
781}
782
783impl RawInspect {
784 fn is_empty(&self) -> bool {
785 self.enabled.is_none()
786 && self.diagnostics_timeout_ms.is_none()
787 && self.tier2_pass_timeout_ms.is_none()
788 && self.categories.is_none()
789 && self.duplicates.is_none()
790 }
791}
792
793#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
798#[serde(default)]
799pub struct RawInspectDuplicates {
800 #[schemars(
801 description = "Intentional mirror paths for duplicate suppression. Each source and mirror glob matches project-root-relative forward-slash paths; groups fully straddling the pair are counted as suppressed instead of reported."
802 )]
803 pub expected_mirrors: Option<Vec<RawExpectedMirror>>,
804}
805
806#[derive(Debug, Clone, Deserialize, PartialEq, schemars::JsonSchema)]
807#[serde(deny_unknown_fields)]
808pub struct RawExpectedMirror {
809 pub source: String,
810 pub mirror: String,
811}
812
813impl RawInspectDuplicates {
814 fn is_empty(&self) -> bool {
815 self.expected_mirrors.is_none()
816 }
817}
818
819#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
820#[serde(default)]
821pub struct RawIdle {
822 #[schemars(
823 description = "Minutes without tool traffic before an unbound root's indexes are evicted. Default 30; values outside 5..=30 are clamped. Reclaimed state rebuilds on the next request. User and project tiers."
824 )]
825 pub root_ttl_minutes: Option<Value>,
826 #[schemars(
827 description = "Hours without use after which a checkout counts as idle and drops its in-memory index state; its state on disk stays. Default 168 (one week); values outside 1..=8760 are clamped. Replaces views.idle_checkout_hours. User and project tiers. Applies live."
828 )]
829 pub checkout_hours: Option<Value>,
830}
831
832impl RawIdle {
833 fn is_empty(&self) -> bool {
834 self.root_ttl_minutes.is_none() && self.checkout_hours.is_none()
835 }
836}
837
838#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
839#[serde(default)]
840pub struct RawBridge {
841 #[serde(deserialize_with = "deserialize_opt_bridge_request_timeout_ms")]
842 #[schemars(
843 description = "Per-request bridge transport timeout in milliseconds. Default 30000. Raise on slow filesystems (WSL/DrvFs/NFS) where cold aft operations exceed the default."
844 )]
845 pub request_timeout_ms: Option<u64>,
846}
847
848#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
849#[serde(default)]
850pub struct RawSubc {
851 #[schemars(
852 description = "Absolute path to the Subconscious (subc) daemon connection file. When present (non-empty), the plugin talks to AFT as a daemon-supervised module over subc instead of spawning the aft binary; absent/empty means standalone NDJSON (the default). macOS default: ~/.local/share/cortexkit/run/subc-connection.json."
853 )]
854 pub connection_file: Option<String>,
855 #[schemars(
856 description = "Close the plugin's Subconscious routes to a checkout after two consecutive checks find the folder missing. Off by default."
857 )]
858 pub client_reaper: Option<bool>,
859}
860
861#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
862#[serde(default)]
863pub struct RawGithub {
864 #[schemars(description = "Interpose the governed gh shim in agent child PATHs.")]
865 pub shim: Option<bool>,
866 #[schemars(
867 description = "Enable structured issue:// and pr:// reads. github.write=true also enables this to keep comment ordinals visible."
868 )]
869 pub read: Option<bool>,
870 #[schemars(
871 description = "Enable creating and editing issue and pull-request conversation comments. Implies github.read."
872 )]
873 pub write: Option<bool>,
874}
875
876#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
877#[serde(default)]
878pub struct RawGhShim {
879 #[serde(deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
880 #[schemars(
881 description = "Absolute deployed or development AFT binary used by the managed gh entry. Defaults to the running AFT image. User-scoped only."
882 )]
883 pub binary_path: Option<String>,
884}
885
886#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
887#[serde(default)]
888pub struct RawGit {
889 #[serde(deserialize_with = "deserialize_opt_git_co_author")]
890 #[schemars(
891 description = "Git co-author attribution for AFT-spawned agent children: 'off', 'auto', or an explicit 'Name <email>' identity. User and project tiers are accepted with project precedence."
892 )]
893 pub co_author: Option<String>,
894}
895
896#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
897#[serde(default)]
898pub struct RawPi {
899 #[schemars(
900 description = "Pi and OMP tool presentation mode. 'top_level' registers tools with loadMode: essential on OMP so they appear at top level (default). 'host_default' uses host default loadMode (mounting tools under xd:// on OMP). User and project tiers are accepted with project precedence."
901 )]
902 pub tool_presentation: Option<RawPiToolPresentation>,
903 #[schemars(
906 description = "Plain Pi only: ask before an AFT tool reaches a path outside the project. On (default), Pi's own terminal UI asks; print, JSON and RPC sessions have no screen to ask on and allow it without asking. Off, outside access is allowed without asking. Credentials, AFT's data folder, sandbox.read_deny and restrict_to_project_root: true refuse either way. Does not apply on OMP, where OMP's approval mode (tools.approvalMode) decides through the tools' declared approval tiers. A project config may turn it on, never off."
907 )]
908 pub external_access_ask: Option<bool>,
909}
910
911impl RawPi {
912 fn is_empty(&self) -> bool {
913 self.tool_presentation.is_none() && self.external_access_ask.is_none()
914 }
915}
916
917#[derive(Debug, Clone, PartialEq, Eq)]
918pub enum RawPiToolPresentation {
919 TopLevel,
920 HostDefault,
921 Unknown(String),
922}
923
924impl<'de> Deserialize<'de> for RawPiToolPresentation {
925 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
926 where
927 D: Deserializer<'de>,
928 {
929 let s = String::deserialize(deserializer)?;
930 match s.as_str() {
931 "top_level" => Ok(Self::TopLevel),
932 "host_default" => Ok(Self::HostDefault),
933 other => Ok(Self::Unknown(other.to_string())),
934 }
935 }
936}
937
938#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
939#[serde(default)]
940pub struct RawBackup {
941 #[schemars(
942 description = "Master switch for agent-facing undo backups. When false aft_safety stays registered and reports that backups are disabled. User-only; project config is ignored."
943 )]
944 pub enabled: Option<bool>,
945 #[serde(default, deserialize_with = "deserialize_opt_positive_usize")]
946 #[schemars(description = "Per-file undo stack depth. User-only; project config is ignored.")]
947 pub max_depth: Option<usize>,
948 #[schemars(
949 description = "Maximum existing-file size captured for undo, in bytes. Defaults to 64 MiB. User and project tiers may set it; explicit larger values are honored. Zero disables automatic snapshots. Mutations still proceed when capture is skipped."
950 )]
951 pub max_file_size: Option<u64>,
952}
953
954#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
957#[serde(default)]
958pub struct RawRemoteExec {
959 #[schemars(
960 description = "Offer bash's runon argument, which runs a command line on the remote Linux build server (subc mode only). User-scoped: a project config may set false to turn remote runs off for itself, never true."
961 )]
962 pub enabled: Option<bool>,
963 #[schemars(
964 description = "The runner demand a runon call without specifics runs under (today only \"linux\"). Never makes a call remote by itself. User-scoped only."
965 )]
966 pub default_demand: Option<String>,
967}
968
969#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
970#[serde(default)]
971pub struct RawSandbox {
972 #[schemars(
973 description = "User-selected sandbox profiles by role. Projects may only select a stricter profile (off < relaxed < strict)."
974 )]
975 pub profile: Option<RawSandboxRoles>,
976 #[schemars(
977 description = "Additional absolute writable directories. User-scoped only; project config cannot add write access."
978 )]
979 pub write_allow: Option<Vec<PathBuf>>,
980 #[schemars(
981 description = "Additional absolute paths sandboxed commands may not read. Project config may add deny entries but cannot remove user or built-in entries."
982 )]
983 pub read_deny: Option<Vec<PathBuf>>,
984}
985
986#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
987#[serde(default)]
988pub struct RawSandboxRoles {
989 pub worker: Option<crate::config::SandboxMode>,
990 pub head: Option<crate::config::SandboxMode>,
991}
992
993#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
997#[serde(default)]
998pub struct RawIndex {
999 #[schemars(
1000 description = "List the folders to index, with a path and a list of indexes to build for each folder. The default is an empty list."
1001 )]
1002 pub roots: Option<Vec<RawIndexRoot>>,
1003}
1004
1005#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
1006#[serde(default)]
1007pub struct RawIndexRoot {
1008 pub path: Option<String>,
1009 pub indexes: Option<Vec<String>>,
1010 #[serde(flatten)]
1011 pub unknown: BTreeMap<String, Value>,
1012}
1013
1014pub fn resolve_config(tiers: &[ConfigTier]) -> ResolveResult {
1021 resolve_config_for_harness(tiers, None)
1022}
1023
1024pub fn resolve_config_for_harness(
1027 tiers: &[ConfigTier],
1028 harness: Option<&Harness>,
1029) -> ResolveResult {
1030 let documents: Vec<_> = tiers.iter().map(ParsedConfigDocument::new).collect();
1031 resolve_parsed_config_for_harness(tiers.iter().zip(&documents), harness)
1032}
1033
1034pub(crate) fn resolve_parsed_config_for_harness<'a>(
1035 tiers: impl Iterator<Item = (&'a ConfigTier, &'a ParsedConfigDocument)> + Clone,
1036 harness: Option<&Harness>,
1037) -> ResolveResult {
1038 let mut merged = RawAftConfig::default();
1039 let mut lsp_user_max_servers = 8;
1040 let mut dropped = Vec::new();
1041 let mut warnings = Vec::new();
1042
1043 let errors = tiers
1047 .clone()
1048 .find_map(|(_, doc)| (!doc.removed_keys.is_empty()).then(|| doc.removed_keys.clone()))
1049 .unwrap_or_default();
1050 if !errors.is_empty() {
1051 return ResolveResult {
1052 config: rejected_cache_config(tiers, Config::default(), &errors),
1053 dropped,
1054 warnings,
1055 errors,
1056 };
1057 }
1058
1059 let mut parsed = Vec::with_capacity(tiers.size_hint().0);
1060 for (tier, doc) in tiers.clone() {
1061 let outcome = match parse_tier_document(tier, doc, harness, &mut warnings, &mut dropped) {
1062 Ok(outcome) => outcome,
1063 Err(errors) => {
1064 let config = cache_location_checked_config(tiers.clone(), &mut warnings);
1068 return ResolveResult {
1069 config: rejected_cache_config(tiers, config, &errors),
1070 dropped,
1071 warnings,
1072 errors,
1073 };
1074 }
1075 };
1076 let (raw, translation) = outcome;
1077 if translation.legacy_input {
1078 log_retired_keys_once(tier, &translation);
1079 }
1080 for warning in translation.warnings {
1081 if warning.code == "superseded_legacy_config"
1088 && !first_superseded_note(&tier.source, &warning.key, &warning.message)
1089 {
1090 continue;
1091 }
1092 crate::slog_info!(
1093 "config {} [{}]: {} ({})",
1094 tier.tier,
1095 warning.key,
1096 warning.message,
1097 warning.code
1098 );
1099 }
1100 parsed.push((tier, raw));
1101 }
1102
1103 let default_disabled = || {
1106 feature_config::DEFAULT_DISABLED_TOOLS
1107 .iter()
1108 .map(|name| (*name).to_string())
1109 .collect::<Vec<_>>()
1110 };
1111 if !parsed.iter().any(|(tier, _)| tier.tier == "user") {
1112 merged.disabled_tools = Some(default_disabled());
1113 }
1114
1115 for (tier, mut raw) in parsed {
1116 let is_user = tier.tier == "user";
1117 if is_user && raw.disabled_tools.is_none() {
1118 raw.disabled_tools = Some(default_disabled());
1119 }
1120 let tier_kind = if is_user {
1121 crate::bash_env::BashEnvTier::User
1122 } else {
1123 crate::bash_env::BashEnvTier::Project
1124 };
1125 let harness_refusal = apply_harness_override(
1126 &mut raw,
1127 harness,
1128 tier,
1129 is_user,
1130 tier_kind,
1131 &mut warnings,
1132 &mut dropped,
1133 );
1134 if let Some(error) =
1135 harness_refusal.or_else(|| raw_bash_env_refusal(&raw, tier, tier_kind, None))
1136 {
1137 let errors = vec![error];
1138 return ResolveResult {
1139 config: rejected_cache_config(tiers, Config::default(), &errors),
1140 dropped,
1141 warnings,
1142 errors,
1143 };
1144 }
1145 if let Some(RawEditMode::Unknown(value)) = raw.edit_mode.as_ref() {
1146 warnings.push(ConfigWarning {
1147 code: "invalid_edit_mode",
1148 key: "edit_mode",
1149 tier: tier.tier.clone(),
1150 value: value.clone(),
1151 message: format!("Unknown edit_mode value {value:?}; falling back to \"default\""),
1152 });
1153 }
1154
1155 if is_user {
1156 merge_trusted_config(&mut merged, raw);
1157 lsp_user_max_servers = merged
1158 .lsp
1159 .as_ref()
1160 .and_then(|lsp| lsp.max_servers)
1161 .unwrap_or(8);
1162 } else {
1163 record_project_drops(&raw, &tier.tier, &mut dropped);
1164 record_resource_loosening(&merged, &raw, &tier.tier, &mut dropped);
1165 merge_project_config(&mut merged, raw);
1166 }
1167 }
1168
1169 let mut config = cache_location_checked_config(tiers.clone(), &mut warnings);
1170 if let Err(missing) = apply_resolved_config(&merged, &mut config, &mut warnings) {
1171 return ResolveResult {
1172 config: rejected_cache_config(tiers, config, &missing),
1173 dropped,
1174 warnings,
1175 errors: missing,
1176 };
1177 }
1178 config.index = resolve_index_config(merged.index.as_ref(), &mut warnings);
1179 config.lsp_user_max_servers = Some(lsp_user_max_servers);
1180 let cache_dir = merged.storage.and_then(|storage| storage.cache_dir);
1181 if let Some(RawCacheDir::Dir { path: raw }) = cache_dir.as_ref() {
1182 let home = std::env::var_os("HOME")
1183 .or_else(|| std::env::var_os("USERPROFILE"))
1184 .map(std::path::PathBuf::from);
1185 match crate::config::expand_cache_dir_path(raw, home.as_deref()) {
1186 Ok(path) => config.cache_dir = Some(path),
1187 Err(error) => {
1188 let path = std::path::PathBuf::from(raw);
1189 config.cache_dir = Some(path.clone());
1190 config.cache_unavailable = Some(error.clone());
1191 warnings.push(crate::cache_location::unavailable_warning(&path, &error));
1192 }
1193 }
1194 }
1195 config.cache_dir_opt_out = matches!(cache_dir, Some(RawCacheDir::MainDisk {}));
1196 config.idle = resolve_idle_config(merged.idle.as_ref(), &mut warnings);
1197 let resolved = serde_json::to_value(&config).unwrap_or(Value::Null);
1198 if let Err(invalid) = feature_config::validate_resolved_config(&resolved) {
1199 return ResolveResult {
1200 config: rejected_cache_config(tiers, config, &invalid),
1201 dropped,
1202 warnings,
1203 errors: invalid,
1204 };
1205 }
1206 let errors = config
1207 .cache_config_unknown
1208 .as_ref()
1209 .filter(|reason| reason.contains("unknown field"))
1210 .and_then(|reason| {
1211 let (_, detail) = reason.split_once("unknown field `")?;
1214 let key = detail.split('`').next().unwrap_or_default();
1215 Some(vec![format!("invalid_cache_config: unknown field `{key}`")])
1216 })
1217 .unwrap_or_default();
1218 ResolveResult {
1219 config,
1220 dropped,
1221 warnings,
1222 errors,
1223 }
1224}
1225
1226fn cache_location_checked_config<'a>(
1230 mut tiers: impl Iterator<Item = (&'a ConfigTier, &'a ParsedConfigDocument)>,
1231 warnings: &mut Vec<ConfigWarning>,
1232) -> Config {
1233 let mut config = Config::default();
1234 config.cache_config_unknown = tiers.find_map(|(_, doc)| doc.cache_location_error.clone());
1235 if let Some(reason) = &config.cache_config_unknown {
1236 warnings.push(ConfigWarning {
1237 code: "cache_dir_config_unknown", key: "storage.cache_dir", tier: "user".into(),
1238 value: "unknown".into(),
1239 message: format!("User configuration is unreadable or invalid ({reason}); AFT is running without its caches until the configuration is valid."),
1240 });
1241 }
1242 config
1243}
1244
1245fn rejected_cache_config<'a>(
1246 tiers: impl Iterator<Item = (&'a ConfigTier, &'a ParsedConfigDocument)>,
1247 mut config: Config,
1248 errors: &[String],
1249) -> Config {
1250 if config.cache_dir.is_none() {
1251 let mut choice = None;
1255 for next in tiers.filter_map(|(_, doc)| doc.cache_choice_after_rejection.clone()) {
1256 merge_cache_dir(&mut choice, next);
1257 }
1258 match choice {
1259 Some(RawCacheDir::Dir { path: raw }) => {
1260 let home = std::env::var_os("HOME")
1261 .or_else(|| std::env::var_os("USERPROFILE"))
1262 .map(std::path::PathBuf::from);
1263 config.cache_dir = Some(
1264 crate::config::expand_cache_dir_path(&raw, home.as_deref())
1265 .unwrap_or_else(|_| std::path::PathBuf::from(raw)),
1266 );
1267 }
1268 Some(RawCacheDir::MainDisk {}) => config.cache_dir_opt_out = true,
1269 Some(RawCacheDir::Default {}) | None => {}
1270 }
1271 }
1272 config
1273 .cache_config_unknown
1274 .get_or_insert_with(|| format!("configuration rejected: {}", errors.join(", ")));
1275 config
1276}
1277
1278pub fn resolve_config_onto(tiers: &[ConfigTier], base: &mut Config) -> Vec<DroppedKey> {
1307 resolve_config_onto_with_diagnostics(tiers, base).dropped
1308}
1309
1310pub fn resolve_config_onto_for_harness(
1313 tiers: &[ConfigTier],
1314 harness: &Harness,
1315 base: &mut Config,
1316) -> Vec<DroppedKey> {
1317 resolve_config_onto_with_diagnostics_for_harness(tiers, Some(harness), base).dropped
1318}
1319
1320pub fn resolve_config_onto_with_diagnostics(
1323 tiers: &[ConfigTier],
1324 base: &mut Config,
1325) -> ResolveDiagnostics {
1326 resolve_config_onto_with_diagnostics_for_harness(tiers, None, base)
1327}
1328
1329pub fn resolve_config_onto_with_diagnostics_for_harness(
1331 tiers: &[ConfigTier],
1332 harness: Option<&Harness>,
1333 base: &mut Config,
1334) -> ResolveDiagnostics {
1335 let ResolveResult {
1336 mut config,
1337 dropped,
1338 warnings,
1339 errors,
1340 } = resolve_config_for_harness(tiers, harness);
1341 if !errors.is_empty() {
1342 return ResolveDiagnostics {
1345 dropped,
1346 warnings,
1347 errors,
1348 };
1349 }
1350 carry_process_state(base, &mut config);
1351 *base = config;
1352 ResolveDiagnostics {
1353 dropped,
1354 warnings,
1355 errors,
1356 }
1357}
1358
1359fn carry_process_state(base: &Config, resolved: &mut Config) {
1365 resolved.project_root = base.project_root.clone();
1366 resolved.harness = base.harness.clone();
1367 resolved.validation_depth = base.validation_depth;
1368 resolved.checkpoint_ttl_hours = base.checkpoint_ttl_hours;
1369 resolved.max_symbol_depth = base.max_symbol_depth;
1370 resolved.diagnostic_cache_size = base.diagnostic_cache_size;
1371 resolved.max_background_bash_tasks = base.max_background_bash_tasks;
1372 resolved.bash_permissions = base.bash_permissions;
1373 resolved.search_index_max_file_size = base.search_index_max_file_size;
1374 resolved.storage_dir = base.storage_dir.clone();
1375 resolved.storage_lease = base.storage_lease.clone();
1376 resolved.lsp_paths_extra = base.lsp_paths_extra.clone();
1377 resolved.lsp_auto_install_binaries = base.lsp_auto_install_binaries.clone();
1378 resolved.lsp_inflight_installs = base.lsp_inflight_installs.clone();
1379}
1380
1381fn log_retired_keys_once(tier: &ConfigTier, translation: &feature_config::DocumentTranslation) {
1387 let keys = translation
1388 .retired_keys
1389 .iter()
1390 .cloned()
1391 .collect::<Vec<_>>()
1392 .join(", ");
1393 if !first_superseded_note(&tier.source, "retired_keys", &keys) {
1394 return;
1395 }
1396 let notice = if tier.tier == "user" {
1397 let mut parts = Vec::new();
1398 if translation.legacy_input {
1399 parts.push(format!(
1400 "{} uses retired keys ({}); AFT applied their current equivalents in memory",
1401 tier.source,
1402 translation.retired_keys.join(", ")
1403 ));
1404 }
1405 parts.retain(|part| !part.is_empty());
1406 parts.join(". ")
1407 } else {
1408 feature_config::project_retired_keys_notice(&tier.source, translation)
1409 };
1410 crate::slog_warn!("config {}: {}", tier.tier, notice);
1411}
1412
1413fn first_superseded_note(source: &str, key: &str, message: &str) -> bool {
1415 static SEEN: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> =
1416 std::sync::OnceLock::new();
1417 SEEN.get_or_init(Default::default)
1418 .lock()
1419 .unwrap_or_else(std::sync::PoisonError::into_inner)
1420 .insert(format!("{source}\u{0}{key}\u{0}{message}"))
1421}
1422
1423#[cfg(test)]
1424fn parse_tier(
1425 tier: &ConfigTier,
1426 harness: Option<&Harness>,
1427 warnings: &mut Vec<ConfigWarning>,
1428 dropped: &mut Vec<DroppedKey>,
1429) -> Result<(RawAftConfig, feature_config::DocumentTranslation), Vec<String>> {
1430 parse_tier_document(
1431 tier,
1432 &ParsedConfigDocument::new(tier),
1433 harness,
1434 warnings,
1435 dropped,
1436 )
1437}
1438
1439fn parse_tier_document(
1440 tier: &ConfigTier,
1441 doc: &ParsedConfigDocument,
1442 harness: Option<&Harness>,
1443 warnings: &mut Vec<ConfigWarning>,
1444 dropped: &mut Vec<DroppedKey>,
1445) -> Result<(RawAftConfig, feature_config::DocumentTranslation), Vec<String>> {
1446 let (mut map, translation) = doc
1447 .translated
1448 .clone()
1449 .ok_or_else(|| vec!["invalid_config_document".to_string()])?;
1450 if tier.tier != "user" && map.remove("memory").is_some() {
1453 push_drop(dropped, "memory", &tier.tier, USER_ONLY_REASON);
1454 }
1455 if let Some(blocks) = map.get_mut("harnesses").and_then(Value::as_object_mut) {
1456 for block in blocks.values_mut().filter_map(Value::as_object_mut) {
1457 if block.remove("memory").is_some() {
1458 push_drop(dropped, "memory", &tier.tier, USER_ONLY_REASON);
1459 }
1460 }
1461 }
1462 normalize_config_for_harness(&mut map, harness);
1463
1464 let security_errors = malformed_security_config_errors(&map, harness);
1465 if !security_errors.is_empty() {
1466 return Err(security_errors);
1467 }
1468 if let Some(path) = feature_config::settings_shape::null_path(&map) {
1469 return Err(vec![format!("invalid_config_null:{path}")]);
1470 }
1471 if tier.tier == "user" {
1472 let malformed_choice = |block: &Map<String, Value>| {
1473 block
1474 .get("storage")
1475 .and_then(|storage| storage.get("cache_dir"))
1476 .filter(|choice| choice.is_object())
1477 .is_some_and(|choice| {
1478 serde_json::from_value::<RawCacheDir>(choice.clone()).is_err()
1479 })
1480 };
1481 if malformed_choice(&map)
1482 || map
1483 .get("harnesses")
1484 .and_then(Value::as_object)
1485 .is_some_and(|blocks| {
1486 blocks
1487 .values()
1488 .filter_map(Value::as_object)
1489 .any(malformed_choice)
1490 })
1491 {
1492 return Err(vec!["invalid_cache_config: storage.cache_dir".into()]);
1493 }
1494 }
1495
1496 let raw = match serde_json::from_value::<RawAftConfig>(Value::Object(map.clone())) {
1497 Ok(config) => config,
1498 Err(_) => parse_config_partially(map, tier, warnings),
1499 };
1500 Ok((raw, translation))
1501}
1502
1503const OPENCODE_ONLY_CONFIG_KEYS: &[&str] = &["auto_update"];
1505const PI_ONLY_CONFIG_KEYS: &[&str] = &[];
1506
1507fn harness_ignored_config_keys(harness: Option<&Harness>) -> &'static [&'static str] {
1508 match harness {
1509 Some(Harness::Pi) => OPENCODE_ONLY_CONFIG_KEYS,
1510 Some(Harness::Opencode) => PI_ONLY_CONFIG_KEYS,
1511 _ => &[],
1512 }
1513}
1514
1515fn normalize_config_for_harness(map: &mut Map<String, Value>, harness: Option<&Harness>) {
1516 let ignored = harness_ignored_config_keys(harness);
1517 for key in ignored {
1518 map.remove(*key);
1519 }
1520 let Some(harness) = harness else { return };
1521 let Some(block) = map
1522 .get_mut("harnesses")
1523 .and_then(Value::as_object_mut)
1524 .and_then(|blocks| blocks.get_mut(&harness.wire_label()))
1525 .and_then(Value::as_object_mut)
1526 else {
1527 return;
1528 };
1529 for key in ignored {
1533 block.remove(*key);
1534 }
1535}
1536
1537fn security_config_section(key: &str, harness: Option<&Harness>) -> bool {
1540 if harness_ignored_config_keys(harness).contains(&key) {
1541 return false;
1542 }
1543 matches!(
1544 key,
1545 "restrict_to_project_root"
1546 | "url_fetch_allow_private"
1547 | "sandbox"
1548 | "indexes"
1549 | "index"
1550 | "remote_exec"
1551 | "disabled_tools"
1552 | "bash"
1553 | "lsp"
1554 | "semantic"
1555 | "search"
1556 | "subc"
1557 | "opencode"
1558 | "github"
1559 | "gh_shim"
1560 | "auto_update"
1561 )
1562}
1563
1564fn malformed_security_config_errors(
1565 map: &Map<String, Value>,
1566 harness: Option<&Harness>,
1567) -> Vec<String> {
1568 let mut errors = Vec::new();
1569 for (key, value) in map {
1570 if !security_config_section(key, harness) {
1571 continue;
1572 }
1573 let mut field = Map::new();
1574 field.insert(key.clone(), value.clone());
1575 if value.is_null() || serde_json::from_value::<RawAftConfig>(Value::Object(field)).is_err()
1576 {
1577 errors.push(format!("invalid_security_config:{key}"));
1578 }
1579 }
1580 if let Some(harness) = harness {
1581 let label = harness.wire_label();
1582 if let Some(blocks) = map.get("harnesses") {
1583 match blocks.as_object() {
1584 None => errors.push("invalid_security_config:harnesses".into()),
1585 Some(blocks) => {
1586 if let Some(block) = blocks.get(&label) {
1587 if let Some(block) = block.as_object() {
1588 let mut block = block.clone();
1589 block.remove("harnesses");
1590 let invalid: Vec<_> = block
1591 .iter()
1592 .filter_map(|(key, value)| {
1593 let mut field = Map::new();
1594 field.insert(key.clone(), value.clone());
1595 (value.is_null()
1596 || serde_json::from_value::<RawAftConfig>(Value::Object(
1597 field,
1598 ))
1599 .is_err())
1600 .then_some(key)
1601 })
1602 .collect();
1603 let invalid_security: Vec<_> = invalid
1604 .iter()
1605 .filter(|key| security_config_section(key, Some(harness)))
1606 .collect();
1607 if !invalid_security.is_empty() {
1608 errors.extend(invalid_security.into_iter().map(|key| {
1609 format!("invalid_security_config:harnesses.{label}.{key}")
1610 }));
1611 } else if !invalid.is_empty()
1612 && block
1613 .keys()
1614 .any(|key| security_config_section(key, Some(harness)))
1615 {
1616 errors.push(format!("invalid_security_config:harnesses.{label}"));
1619 }
1620 } else {
1621 errors.push(format!("invalid_security_config:harnesses.{label}"));
1622 }
1623 }
1624 }
1625 }
1626 }
1627 }
1628 errors.sort();
1629 errors.dedup();
1630 errors
1631}
1632
1633fn parse_cache_dir(value: Value) -> serde_json::Result<RawCacheDir> {
1634 let canonical = feature_config::settings_shape::cache_dir_replacement(&value)
1635 .map_or(value, |(replacement, _)| replacement);
1636 serde_json::from_value(canonical)
1637}
1638
1639fn merge_cache_dir(base: &mut Option<RawCacheDir>, next: RawCacheDir) {
1640 if base.is_none()
1643 || matches!(next, RawCacheDir::Dir { .. })
1644 || (matches!(next, RawCacheDir::MainDisk {})
1645 && !matches!(base, Some(RawCacheDir::Dir { .. })))
1646 {
1647 *base = Some(next);
1648 }
1649}
1650
1651pub(crate) fn storage_like_key(key: &str, value: Option<&Value>) -> bool {
1653 if key == "storage_dir" {
1655 return false;
1656 }
1657 let normalized: String = key
1658 .chars()
1659 .filter(char::is_ascii_alphanumeric)
1660 .map(|c| c.to_ascii_lowercase())
1661 .collect();
1662 if normalized.starts_with("storage") || matches!(normalized.as_str(), "cachedir" | "cacheroot")
1663 {
1664 return true;
1665 }
1666 if value
1667 .and_then(Value::as_object)
1668 .is_some_and(|fields| fields.contains_key("cache_dir"))
1669 {
1670 return true;
1671 }
1672 let target = b"storage";
1673 if normalized.len().abs_diff(target.len()) > 2 {
1674 return false;
1675 }
1676 let mut row: Vec<usize> = (0..=target.len()).collect();
1677 for (i, byte) in normalized.bytes().enumerate() {
1678 let mut next = vec![i + 1];
1679 for (j, expected) in target.iter().enumerate() {
1680 next.push(
1681 (row[j] + usize::from(byte != *expected))
1682 .min(row[j + 1] + 1)
1683 .min(next[j] + 1),
1684 );
1685 }
1686 row = next;
1687 }
1688 row[target.len()] <= 2
1689}
1690
1691pub fn cache_location_config_error(tier: &ConfigTier) -> Option<String> {
1694 match parsed::parse_config_object(tier) {
1695 Ok(map) => cache_location_error_for_map(tier, &map),
1696 Err(error) => Some(error),
1697 }
1698}
1699
1700fn cache_location_error_for_map(tier: &ConfigTier, map: &Map<String, Value>) -> Option<String> {
1701 if let Some(error) = feature_config::removed_config_key_errors(map)
1702 .into_iter()
1703 .find(|error| error.contains("storage"))
1704 {
1705 return Some(format!(
1706 "{} has a removed storage setting: {error}",
1707 tier.source
1708 ));
1709 }
1710 let unknown_key = |map: &Map<String, Value>| -> Option<String> {
1711 let mut map = map.clone();
1712 feature_config::translate_document(&mut map, feature_config::DocumentTier::User);
1713 map.keys().find_map(|key| {
1714 let field = Map::from_iter([(key.clone(), Value::Null)]);
1717 serde_json::from_value::<RawAftConfig>(Value::Object(field))
1718 .err()
1719 .map(|error| error.to_string())
1720 .filter(|error| {
1721 error.starts_with("unknown field") && storage_like_key(key, map.get(key))
1722 })
1723 })
1724 };
1725 if let Some(error) = unknown_key(map) {
1726 return Some(format!("{} has an invalid setting: {error}", tier.source));
1727 }
1728 #[derive(Deserialize)]
1732 #[serde(deny_unknown_fields)]
1733 #[allow(dead_code)]
1734 struct StrictStorage {
1735 cache_dir: Option<RawCacheDir>,
1736 }
1737 let invalid_storage = |section: &Value| -> Option<String> {
1738 if section.is_null() {
1739 return None;
1740 }
1741 if let Some(key) = section
1742 .as_object()
1743 .and_then(|fields| fields.keys().find(|key| key.as_str() != "cache_dir"))
1744 {
1745 return Some(format!("unknown field `{key}`, expected `cache_dir`"));
1746 }
1747 let mut section = section.clone();
1748 if let Some(cache_dir) = section.get_mut("cache_dir") {
1749 if let Some((replacement, _)) =
1750 feature_config::settings_shape::cache_dir_replacement(cache_dir)
1751 {
1752 *cache_dir = replacement;
1753 }
1754 }
1755 serde_json::from_value::<StrictStorage>(section)
1756 .err()
1757 .map(|error| error.to_string())
1758 };
1759 if let Some(error) = map.get("storage").and_then(invalid_storage) {
1760 return Some(format!(
1761 "{} has an invalid storage section: {error}",
1762 tier.source
1763 ));
1764 }
1765 if let Some(Value::Object(harnesses)) = map.get("harnesses") {
1766 for (name, block) in harnesses {
1767 if let Some(error) = block.as_object().and_then(unknown_key) {
1768 return Some(format!(
1769 "{} has an invalid harnesses.{name} setting: {error}",
1770 tier.source
1771 ));
1772 }
1773 if let Some(error) = block.get("storage").and_then(invalid_storage) {
1774 return Some(format!(
1775 "{} has an invalid harnesses.{name}.storage section: {error}",
1776 tier.source
1777 ));
1778 }
1779 }
1780 }
1781 None
1782}
1783
1784pub fn strict_tier_error(tier: &ConfigTier, harness: Option<&Harness>) -> Option<String> {
1796 let stripped = strip_jsonc(&tier.doc);
1797 let value = match serde_json::from_str::<Value>(&stripped) {
1798 Ok(value) => value,
1799 Err(error) => return Some(format!("{} does not parse: {error}", tier.source)),
1800 };
1801 let Value::Object(mut map) = value else {
1802 return Some(format!("{} is not a JSON object", tier.source));
1803 };
1804 let removed = feature_config::removed_config_key_errors_for_file(&map, tier.tier == "user");
1806 if !removed.is_empty() {
1807 return Some(removed.join(", "));
1808 }
1809 let document_tier = if tier.tier == "user" {
1810 feature_config::DocumentTier::User
1811 } else {
1812 feature_config::DocumentTier::Project
1813 };
1814 feature_config::translate_document(&mut map, document_tier);
1815 normalize_config_for_harness(&mut map, harness);
1816 if let Some(path) = feature_config::settings_shape::null_path(&map) {
1817 return Some(format!("invalid_config_null:{path}"));
1818 }
1819 let raw = match serde_json::from_value::<RawAftConfig>(Value::Object(map)) {
1820 Ok(raw) => raw,
1821 Err(error) => {
1822 return Some(format!("{} has an invalid setting: {error}", tier.source));
1823 }
1824 };
1825 let tier_kind = if tier.tier == "user" {
1829 crate::bash_env::BashEnvTier::User
1830 } else {
1831 crate::bash_env::BashEnvTier::Project
1832 };
1833 let harness_context = harness.map(|harness| {
1837 let label = harness.wire_label();
1838 let block = raw
1839 .harnesses
1840 .as_ref()
1841 .and_then(|blocks| blocks.get(&label))
1842 .cloned();
1843 (label, block)
1844 });
1845 let harness_refusal = match harness_context.as_ref() {
1848 Some((label, Some(Value::Object(block)))) => {
1849 let mut block = block.clone();
1850 block.remove("harnesses");
1852 match serde_json::from_value::<RawAftConfig>(Value::Object(block)) {
1853 Ok(parsed) => raw_bash_env_refusal(&parsed, tier, tier_kind, Some(label)),
1854 Err(_) => None,
1855 }
1856 }
1857 _ => None,
1858 };
1859 let base_refusal = raw_bash_env_refusal(&raw, tier, tier_kind, None);
1860 harness_refusal.or(base_refusal)
1861}
1862
1863fn refused_bash_env_error(
1867 tier: &ConfigTier,
1868 tier_kind: crate::bash_env::BashEnvTier,
1869 key: &str,
1870 harness_label: Option<&str>,
1871) -> String {
1872 let where_set = match harness_label {
1873 Some(label) => format!(" in harnesses.{label}"),
1874 None => String::new(),
1875 };
1876 let scope = match tier_kind {
1877 crate::bash_env::BashEnvTier::User => "cannot be configured",
1878 crate::bash_env::BashEnvTier::Project => {
1879 "cannot be configured by a project; set it in user config if you need it"
1880 }
1881 };
1882 format!(
1883 "{} has blocked bash.env key {key}{where_set}; environment startup hooks, lookup roots, interpreter injectors, Git redirection, AFT controls, sandbox controls and credentials {scope}",
1884 tier.source
1885 )
1886}
1887
1888fn raw_bash_env_refusal(
1893 raw: &RawAftConfig,
1894 tier: &ConfigTier,
1895 tier_kind: crate::bash_env::BashEnvTier,
1896 harness_label: Option<&str>,
1897) -> Option<String> {
1898 let env = match raw.bash.as_ref() {
1899 Some(features) => features.env.as_ref(),
1900 _ => None,
1901 };
1902 let found = crate::bash_env::first_refused_env_key(env?, tier_kind);
1903 let key = found?;
1904 Some(refused_bash_env_error(tier, tier_kind, key, harness_label))
1905}
1906
1907fn parse_config_partially(
1908 raw_config: Map<String, Value>,
1909 tier: &ConfigTier,
1910 warnings: &mut Vec<ConfigWarning>,
1911) -> RawAftConfig {
1912 let mut partial = RawAftConfig::default();
1913
1914 for (key, value) in raw_config {
1915 let mut one_field = Map::new();
1916 one_field.insert(key.clone(), value);
1917 if let Ok(section) = serde_json::from_value::<RawAftConfig>(Value::Object(one_field)) {
1918 merge_trusted_config(&mut partial, section);
1919 } else {
1920 warnings.push(ConfigWarning {
1921 code: "invalid_config_section",
1922 key: "config",
1923 tier: tier.tier.clone(),
1924 value: "[discarded]".into(),
1925 message: format!("Discarded invalid configuration section: {key}"),
1926 });
1927 }
1928 }
1929
1930 partial
1931}
1932
1933fn apply_harness_override(
1940 raw: &mut RawAftConfig,
1941 harness: Option<&Harness>,
1942 tier: &ConfigTier,
1943 trusted: bool,
1944 tier_kind: crate::bash_env::BashEnvTier,
1945 warnings: &mut Vec<ConfigWarning>,
1946 dropped: &mut Vec<DroppedKey>,
1947) -> Option<String> {
1948 let Some(overrides) = raw.harnesses.take() else {
1949 return None;
1950 };
1951 let Some(harness) = harness else {
1952 return None;
1953 };
1954 let key = harness.wire_label();
1955 let Some(value) = overrides.get(&key) else {
1956 return None;
1957 };
1958 let Value::Object(mut override_map) = value.clone() else {
1959 warnings.push(ConfigWarning {
1960 code: "invalid_harness_override",
1961 key: "harnesses",
1962 tier: tier.tier.clone(),
1963 value: key,
1964 message: "Ignoring non-object harness override; overrides must be config objects"
1965 .to_string(),
1966 });
1967 return None;
1968 };
1969
1970 if override_map.remove("harnesses").is_some() {
1971 warnings.push(ConfigWarning {
1972 code: "nested_harnesses_ignored",
1973 key: "harnesses",
1974 tier: tier.tier.clone(),
1975 value: key.clone(),
1976 message: format!(
1977 "Ignoring nested harnesses in harnesses.{key}; harness overrides cannot recurse"
1978 ),
1979 });
1980 }
1981
1982 normalize_config_for_harness(&mut override_map, Some(harness));
1983
1984 let refusal = serde_json::from_value::<RawAftConfig>(Value::Object(override_map.clone()))
1987 .ok()
1988 .and_then(|parsed| raw_bash_env_refusal(&parsed, tier, tier_kind, Some(&key)));
1989
1990 match serde_json::from_value::<RawAftConfig>(Value::Object(override_map)) {
1991 Ok(mut override_config) => {
1992 if override_config
1993 .durability
1994 .take()
1995 .is_some_and(|durability| durability.macos_full_sync.is_some())
1996 {
1997 push_drop(
1998 dropped,
1999 "durability.macos_full_sync",
2000 &tier.tier,
2001 "sync policy is process-wide; only the user-tier base may set it",
2002 );
2003 }
2004 if override_config
2005 .storage
2006 .take()
2007 .is_some_and(|storage| storage.cache_dir.is_some())
2008 {
2009 push_drop(
2010 dropped,
2011 "storage.cache_dir",
2012 &tier.tier,
2013 "cache location is storage-wide; only the user-tier base may set it",
2014 );
2015 }
2016 let override_indexes = override_config.indexes.take();
2019 merge_trusted_config(raw, override_config);
2020 raw.indexes = merge_indexes(raw.indexes, override_indexes, !trusted);
2021 }
2022 Err(_) => warnings.push(ConfigWarning {
2023 code: "invalid_harness_override",
2024 key: "harnesses",
2025 tier: tier.tier.clone(),
2026 value: key,
2027 message: "Ignoring invalid harness override; it must use the root config shape"
2028 .to_string(),
2029 }),
2030 }
2031 refusal
2032}
2033
2034fn merge_trusted_config(base: &mut RawAftConfig, override_config: RawAftConfig) {
2035 if override_config.shell.is_some() {
2036 base.shell = override_config.shell.clone();
2037 }
2038 if let Some(value) = override_config
2039 .durability
2040 .and_then(|durability| durability.macos_full_sync)
2041 {
2042 base.durability
2043 .get_or_insert_with(RawDurability::default)
2044 .macos_full_sync = Some(value);
2045 }
2046 if let Some(choice) = override_config
2047 .storage
2048 .and_then(|storage| storage.cache_dir)
2049 {
2050 merge_cache_dir(
2051 &mut base
2052 .storage
2053 .get_or_insert_with(RawStorage::default)
2054 .cache_dir,
2055 choice,
2056 );
2057 }
2058 if override_config.harnesses.is_some() {
2059 base.harnesses = override_config.harnesses.clone();
2060 }
2061 if override_config.schema.is_some() {
2062 base.schema = override_config.schema;
2063 }
2064 if override_config.edit_mode.is_some() {
2065 base.edit_mode = override_config.edit_mode;
2066 }
2067 if override_config.format_on_edit.is_some() {
2068 base.format_on_edit = override_config.format_on_edit;
2069 }
2070 if override_config.revision_reads.is_some() {
2071 base.revision_reads = override_config.revision_reads;
2072 }
2073 if override_config.formatter_timeout_secs.is_some() {
2074 base.formatter_timeout_secs = override_config.formatter_timeout_secs;
2075 }
2076 if override_config.type_checker_timeout_secs.is_some() {
2077 base.type_checker_timeout_secs = override_config.type_checker_timeout_secs;
2078 }
2079 if override_config.validate_on_edit.is_some() {
2080 base.validate_on_edit = override_config.validate_on_edit;
2081 }
2082 if override_config.formatter.is_some() {
2083 base.formatter = override_config.formatter;
2084 }
2085 if override_config.checker.is_some() {
2086 base.checker = override_config.checker;
2087 }
2088 if override_config.configure_warnings_delivery.is_some() {
2089 base.configure_warnings_delivery = override_config.configure_warnings_delivery;
2090 }
2091 union_disabled_tools(&mut base.disabled_tools, override_config.disabled_tools);
2094 if override_config.restrict_to_project_root.is_some() {
2095 base.restrict_to_project_root = override_config.restrict_to_project_root;
2096 }
2097 base.indexes = merge_indexes(base.indexes, override_config.indexes, false);
2098 if override_config.index.is_some() {
2099 base.index = override_config.index;
2100 }
2101 if override_config.memory.is_some() {
2102 base.memory = override_config.memory;
2103 }
2104 if override_config.inspect.is_some() {
2105 base.inspect = override_config.inspect;
2106 }
2107 if override_config.idle.is_some() {
2108 base.idle = merge_idle_config(base.idle.take(), override_config.idle);
2111 }
2112 if override_config.backup.is_some() {
2113 base.backup = override_config.backup;
2114 }
2115 if override_config.github.is_some() {
2116 base.github = override_config.github;
2117 }
2118 if override_config.gh_shim.is_some() {
2119 base.gh_shim = override_config.gh_shim;
2120 }
2121 if override_config.git.is_some() {
2122 base.git = override_config.git;
2123 }
2124 if override_config.pi.is_some() {
2125 base.pi = override_config.pi;
2126 }
2127 if let Some(next) = override_config.sandbox {
2128 let sandbox = base.sandbox.get_or_insert_with(RawSandbox::default);
2129 if let Some(next) = next.profile {
2130 let profile = sandbox.profile.get_or_insert_with(RawSandboxRoles::default);
2131 if next.worker.is_some() {
2132 profile.worker = next.worker;
2133 }
2134 if next.head.is_some() {
2135 profile.head = next.head;
2136 }
2137 }
2138 if next.write_allow.is_some() {
2139 sandbox.write_allow = next.write_allow;
2140 }
2141 if next.read_deny.is_some() {
2142 sandbox.read_deny = next.read_deny;
2143 }
2144 }
2145 if override_config.bash.is_some() {
2146 base.bash = merge_bash_config(base.bash.take(), override_config.bash);
2154 }
2155 if override_config.experimental.is_some() {
2156 base.experimental = override_config.experimental;
2157 }
2158 if override_config.lsp.is_some() {
2159 base.lsp = override_config.lsp;
2160 }
2161 if override_config.url_fetch_allow_private.is_some() {
2162 base.url_fetch_allow_private = override_config.url_fetch_allow_private;
2163 }
2164 if override_config.semantic.is_some() {
2165 base.semantic = override_config.semantic;
2166 }
2167 if override_config.search.is_some() {
2168 base.search = override_config.search;
2169 }
2170 if override_config.auto_update.is_some() {
2171 base.auto_update = override_config.auto_update;
2172 }
2173 if override_config.bridge.is_some() {
2174 base.bridge = override_config.bridge;
2175 }
2176 if override_config.subc.is_some() {
2177 base.subc = override_config.subc;
2178 }
2179
2180 if let Some(remote_exec) = override_config.remote_exec {
2181 let merged = base.remote_exec.get_or_insert_with(RawRemoteExec::default);
2182 if remote_exec.enabled.is_some() {
2183 merged.enabled = remote_exec.enabled;
2184 }
2185 if remote_exec.default_demand.is_some() {
2186 merged.default_demand = remote_exec.default_demand;
2187 }
2188 }
2189}
2190
2191fn merge_project_config(base: &mut RawAftConfig, project: RawAftConfig) {
2192 if project.edit_mode.is_some() {
2194 base.edit_mode = project.edit_mode;
2195 }
2196 if project.format_on_edit.is_some() {
2197 base.format_on_edit = project.format_on_edit;
2198 }
2199 if project.revision_reads.is_some() {
2202 base.revision_reads = project.revision_reads;
2203 }
2204 if project.validate_on_edit.is_some() {
2205 base.validate_on_edit = project.validate_on_edit;
2206 }
2207 if project.configure_warnings_delivery.is_some() {
2208 base.configure_warnings_delivery = project.configure_warnings_delivery;
2209 }
2210 base.indexes = merge_indexes(base.indexes, project.indexes, true);
2212
2213 merge_formatter_map(&mut base.formatter, project.formatter);
2214 merge_checker_map(&mut base.checker, project.checker);
2215 merge_disabled_tools(&mut base.disabled_tools, project.disabled_tools);
2216 base.semantic = merge_semantic_config(base.semantic.take(), project.semantic);
2217 base.search = merge_project_search(base.search.take(), project.search);
2218 base.lsp = merge_lsp_config(base.lsp.take(), project.lsp);
2219 base.experimental = merge_experimental_config(base.experimental.take(), project.experimental);
2220 let ceiling = base.bash.as_ref().and_then(|bash| bash.memory_limit_mib);
2221 let mut project_bash = project_safe_bash(project.bash);
2222 if let Some(features) = &mut project_bash {
2223 features.memory_limit_mib = match (ceiling, features.memory_limit_mib) {
2224 (Some(user), Some(project)) => Some(user.min(project)),
2225 (_, value) => value,
2226 };
2227 }
2228 base.bash = merge_bash_config(base.bash.take(), project_bash);
2229 base.inspect = merge_inspect_config(base.inspect.take(), project.inspect);
2230 base.idle = merge_idle_config(base.idle.take(), project.idle);
2231 base.backup = merge_project_backup_config(base.backup.take(), project.backup);
2232 if project.git.is_some() {
2233 base.git = project.git;
2234 }
2235 base.pi = merge_pi_config(base.pi.take(), project.pi);
2236 base.sandbox = merge_project_sandbox(base.sandbox.take(), project.sandbox);
2237 if project
2240 .remote_exec
2241 .as_ref()
2242 .is_some_and(|remote| remote.enabled == Some(false))
2243 {
2244 base.remote_exec_project_off = true;
2245 }
2246}
2247
2248fn merge_project_search(base: Option<RawSearch>, project: Option<RawSearch>) -> Option<RawSearch> {
2251 let disables = project
2252 .and_then(|search| search.rerank)
2253 .is_some_and(|rerank| rerank.backend == Some(RerankBackendKind::Off));
2254 if !disables {
2255 return base;
2256 }
2257 let mut search = base.unwrap_or_default();
2258 search.rerank.get_or_insert_with(RawRerank::default).backend = Some(RerankBackendKind::Off);
2259 Some(search)
2260}
2261
2262fn resolve_search_config(raw: Option<&RawSearch>) -> SearchConfig {
2266 let rerank = raw
2267 .and_then(|search| search.rerank.as_ref())
2268 .map(|rerank| RerankConfig {
2269 backend: rerank.backend,
2270 model: rerank.model.clone(),
2271 endpoint: rerank.endpoint.clone(),
2272 api_key_env: rerank.api_key_env.clone(),
2273 top_n: rerank.top_n,
2274 timeout_ms: rerank.timeout_ms,
2275 });
2276 SearchConfig {
2277 rerank: rerank.filter(|rerank| *rerank != RerankConfig::default()),
2278 }
2279}
2280
2281fn merge_project_backup_config(
2282 base: Option<RawBackup>,
2283 project: Option<RawBackup>,
2284) -> Option<RawBackup> {
2285 let Some(project_max_file_size) = project.and_then(|backup| backup.max_file_size) else {
2286 return base;
2287 };
2288 let mut backup = base.unwrap_or_default();
2289 backup.max_file_size = Some(project_max_file_size);
2290 Some(backup)
2291}
2292
2293fn merge_project_sandbox(
2294 base: Option<RawSandbox>,
2295 project: Option<RawSandbox>,
2296) -> Option<RawSandbox> {
2297 let Some(project) = project else {
2298 return base;
2299 };
2300 let mut sandbox = base.unwrap_or_default();
2301 if let Some(project_denies) = project.read_deny {
2302 let denies = sandbox.read_deny.get_or_insert_with(Vec::new);
2303 for path in project_denies {
2304 if !denies.contains(&path) {
2305 denies.push(path);
2306 }
2307 }
2308 }
2309 if let Some(next) = project.profile {
2310 let floor = resolve_sandbox_config(Some(&sandbox)).profile;
2311 let profile = sandbox.profile.get_or_insert_with(RawSandboxRoles::default);
2312 if let Some(worker) = next.worker.filter(|value| *value >= floor.worker) {
2313 profile.worker = Some(worker);
2314 }
2315 if let Some(head) = next.head.filter(|value| *value >= floor.head) {
2316 profile.head = Some(head);
2317 }
2318 }
2319 (sandbox.profile.is_some() || sandbox.write_allow.is_some() || sandbox.read_deny.is_some())
2320 .then_some(sandbox)
2321}
2322
2323fn merge_formatter_map(
2324 base: &mut Option<HashMap<String, RawFormatter>>,
2325 override_map: Option<HashMap<String, RawFormatter>>,
2326) {
2327 let Some(override_map) = override_map else {
2328 return;
2329 };
2330 if override_map.is_empty() && base.as_ref().is_none_or(HashMap::is_empty) {
2331 return;
2332 }
2333 let target = base.get_or_insert_with(HashMap::new);
2334 target.extend(override_map);
2335}
2336
2337fn merge_checker_map(
2338 base: &mut Option<HashMap<String, RawChecker>>,
2339 override_map: Option<HashMap<String, RawChecker>>,
2340) {
2341 let Some(override_map) = override_map else {
2342 return;
2343 };
2344 if override_map.is_empty() && base.as_ref().is_none_or(HashMap::is_empty) {
2345 return;
2346 }
2347 let target = base.get_or_insert_with(HashMap::new);
2348 target.extend(override_map);
2349}
2350
2351fn merge_disabled_tools(base: &mut Option<Vec<String>>, override_tools: Option<Vec<String>>) {
2352 union_disabled_tools(
2355 base,
2356 override_tools.map(|tools| {
2357 tools
2358 .into_iter()
2359 .filter(|tool| !feature_config::is_project_protected_tool(tool))
2360 .collect()
2361 }),
2362 );
2363}
2364
2365fn union_disabled_tools(base: &mut Option<Vec<String>>, override_tools: Option<Vec<String>>) {
2368 let Some(override_tools) = override_tools else {
2369 return;
2370 };
2371 let mut merged = base.take().unwrap_or_default();
2372 merged.extend(override_tools);
2373 *base = Some(feature_config::normalize_tool_list(merged));
2374}
2375
2376fn merge_indexes(
2379 base: Option<RawIndexes>,
2380 override_indexes: Option<RawIndexes>,
2381 restricted: bool,
2382) -> Option<RawIndexes> {
2383 let Some(override_indexes) = override_indexes else {
2384 return base;
2385 };
2386 let mut merged = base.unwrap_or_default();
2387 let apply = |slot: &mut Option<bool>, value: Option<bool>| match value {
2388 Some(false) => *slot = Some(false),
2389 Some(true) if !restricted => *slot = Some(true),
2390 _ => {}
2391 };
2392 apply(&mut merged.trigram, override_indexes.trigram);
2393 apply(&mut merged.semantic, override_indexes.semantic);
2394 apply(&mut merged.callgraph, override_indexes.callgraph);
2395 Some(merged)
2396}
2397
2398fn merge_semantic_config(
2399 base: Option<RawSemantic>,
2400 override_semantic: Option<RawSemantic>,
2401) -> Option<RawSemantic> {
2402 let mut semantic = base.unwrap_or(RawSemantic {
2403 backend: None,
2404 model: None,
2405 base_url: None,
2406 api_key_env: None,
2407 timeout_ms: None,
2408 query_timeout_ms: None,
2409 query_instruction: None,
2410 max_batch_size: None,
2411 max_input_tokens: None,
2412 max_files: None,
2413 });
2414
2415 if let Some(project) = override_semantic {
2416 if project.model.is_some() {
2417 semantic.model = project.model;
2418 }
2419 if project.timeout_ms.is_some() {
2420 semantic.timeout_ms = project.timeout_ms;
2421 }
2422 if project.query_instruction.is_some() {
2423 semantic.query_instruction = project.query_instruction;
2424 }
2425 if project.max_batch_size.is_some() {
2426 semantic.max_batch_size = project.max_batch_size;
2427 }
2428 if project.max_input_tokens.is_some() {
2429 semantic.max_input_tokens = project.max_input_tokens;
2430 }
2431 if project.max_files.is_some() {
2432 semantic.max_files = project.max_files;
2433 }
2434 }
2435
2436 (!semantic.is_empty()).then_some(semantic)
2437}
2438
2439fn merge_lsp_config(base: Option<RawLsp>, override_lsp: Option<RawLsp>) -> Option<RawLsp> {
2440 let mut lsp = base.unwrap_or_default();
2441
2442 if let Some(project) = override_lsp {
2443 if let Some(max_servers) = project.max_servers {
2444 if max_servers <= lsp.max_servers.unwrap_or(8) {
2445 lsp.max_servers = Some(max_servers);
2446 }
2447 }
2448 if let Some(idle) = project.idle_minutes {
2449 if lsp_idle_minutes(Some(idle)) <= lsp_idle_minutes(lsp.idle_minutes) {
2450 lsp.idle_minutes = Some(idle);
2451 }
2452 }
2453 if project.idle_shutdown == Some(true) {
2454 lsp.idle_shutdown = Some(true);
2455 }
2456 if project.python.is_some() {
2457 lsp.python = project.python;
2458 }
2459 if project.diagnostics_on_edit.is_some() {
2460 lsp.diagnostics_on_edit = project.diagnostics_on_edit;
2461 }
2462 }
2463
2464 (!lsp.is_empty()).then_some(lsp)
2465}
2466
2467fn merge_experimental_config(
2468 base: Option<RawExperimental>,
2469 override_experimental: Option<RawExperimental>,
2470) -> Option<RawExperimental> {
2471 let Some(override_experimental) = override_experimental else {
2472 return base;
2473 };
2474
2475 let mut experimental = base.unwrap_or_default();
2476 experimental.lsp_ty = override_experimental.lsp_ty.or(experimental.lsp_ty);
2477
2478 (!experimental.is_empty()).then_some(experimental)
2479}
2480
2481fn project_safe_bash(project: Option<RawBashFeatures>) -> Option<RawBashFeatures> {
2482 project.map(|mut features| {
2483 features.changed_files = features
2484 .changed_files
2485 .filter(|mode| *mode == crate::config::BashChangedFiles::Off);
2486 features.linux_scope = None;
2487 features.linux_scope_max_runtime_secs = None;
2488 features.project_env = features.env.take();
2490 features.runon_env = None;
2491 features.disclaim_privacy = features.disclaim_privacy.filter(|value| *value);
2492 features
2493 })
2494}
2495
2496#[cfg(any(test, feature = "test-support"))]
2497#[test]
2498fn retired_runon_gate_preserves_explicit_user_choice_and_project_cannot_change_it() {
2499 assert!(!resolve_config(&[]).config.remote_exec.enabled);
2500 for (legacy, expected) in [(Some(false), false), (Some(true), true), (None, true)] {
2501 let mut user = serde_json::json!({"remote_exec":{"enabled":true}});
2502 if let Some(legacy) = legacy {
2503 user["bash"] = serde_json::json!({"runon_enabled":legacy});
2504 }
2505 let result = resolve_config(&[
2506 ConfigTier {
2507 tier: "user".into(),
2508 source: "user.jsonc".into(),
2509 doc: user.to_string(),
2510 },
2511 ConfigTier {
2512 tier: "project".into(),
2513 source: "project.jsonc".into(),
2514 doc: r#"{"bash":{"runon_enabled":false}}"#.into(),
2515 },
2516 ]);
2517 assert!(result.errors.is_empty(), "{:?}", result.errors);
2518 assert_eq!(result.config.remote_exec.enabled, expected);
2519 }
2520}
2521
2522#[cfg(any(test, feature = "test-support"))]
2523#[test]
2524fn macos_full_sync_is_user_only_and_defaults_off() {
2525 let defaults = resolve_config(&[]);
2526 assert!(!defaults.config.durability.macos_full_sync);
2527 assert!(!Config::default().durability.macos_full_sync);
2528 for enabled in [false, true] {
2529 let result = resolve_config(&[
2530 ConfigTier {
2531 tier: "user".into(),
2532 source: "user.jsonc".into(),
2533 doc: format!("{{\"durability\":{{\"macos_full_sync\":{enabled}}}}}"),
2534 },
2535 ConfigTier {
2536 tier: "project".into(),
2537 source: "project.jsonc".into(),
2538 doc: format!("{{\"durability\":{{\"macos_full_sync\":{}}}}}", !enabled),
2539 },
2540 ]);
2541 assert!(result.errors.is_empty(), "{:?}", result.errors);
2542 assert_eq!(result.config.durability.macos_full_sync, enabled);
2543 assert!(result
2544 .dropped
2545 .iter()
2546 .any(|drop| { drop.key == "durability.macos_full_sync" && drop.tier == "project" }));
2547 }
2548 let project = resolve_config(&[ConfigTier {
2549 tier: "project".into(),
2550 source: "project.jsonc".into(),
2551 doc: r#"{"durability":{"macos_full_sync":true}}"#.into(),
2552 }]);
2553 assert!(!project.config.durability.macos_full_sync);
2554 assert_eq!(project.dropped[0].key, "durability.macos_full_sync");
2555}
2556
2557#[cfg(test)]
2558#[test]
2559fn macos_full_sync_ignores_all_harness_overrides() {
2560 for harness in [Harness::Opencode, Harness::Pi] {
2561 for base in [false, true] {
2562 let key = harness.wire_label();
2563 let result = resolve_config_for_harness(
2564 &[
2565 ConfigTier {
2566 tier: "user".into(),
2567 source: "user.jsonc".into(),
2568 doc: serde_json::json!({
2569 "durability": {"macos_full_sync": base},
2570 "harnesses": {(key.clone()): {"durability": {"macos_full_sync": !base}}}
2571 })
2572 .to_string(),
2573 },
2574 ConfigTier {
2575 tier: "project".into(),
2576 source: "project.jsonc".into(),
2577 doc: serde_json::json!({
2578 "harnesses": {(key.clone()): {"durability": {"macos_full_sync": !base}}}
2579 })
2580 .to_string(),
2581 },
2582 ],
2583 Some(&harness),
2584 );
2585 assert!(result.errors.is_empty(), "{:?}", result.errors);
2586 assert_eq!(result.config.durability.macos_full_sync, base);
2587 for tier in ["user", "project"] {
2588 assert!(result
2589 .dropped
2590 .iter()
2591 .any(|drop| { drop.key == "durability.macos_full_sync" && drop.tier == tier }));
2592 }
2593 }
2594 }
2595}
2596
2597#[cfg(test)]
2598#[test]
2599fn bash_memory_limit_parses_and_project_cannot_raise_it() {
2600 let resolve = |user: &str, project: &str| {
2601 serde_json::to_value(
2602 resolve_config(&[
2603 ConfigTier {
2604 tier: "user".into(),
2605 source: "user.jsonc".into(),
2606 doc: user.into(),
2607 },
2608 ConfigTier {
2609 tier: "project".into(),
2610 source: "project.jsonc".into(),
2611 doc: project.into(),
2612 },
2613 ])
2614 .config
2615 .bash,
2616 )
2617 .unwrap()["memory_limit_mib"]
2618 .clone()
2619 };
2620 assert_eq!(
2621 resolve(r#"{"bash":{"memory_limit_mib":64}}"#, "{}"),
2622 serde_json::json!(64)
2623 );
2624 assert_eq!(
2625 resolve(
2626 r#"{"bash":{"memory_limit_mib":64}}"#,
2627 r#"{"bash":{"memory_limit_mib":128}}"#
2628 ),
2629 serde_json::json!(64)
2630 );
2631 assert_eq!(
2632 resolve(
2633 r#"{"bash":{"memory_limit_mib":64}}"#,
2634 r#"{"bash":{"memory_limit_mib":32}}"#
2635 ),
2636 serde_json::json!(32)
2637 );
2638 assert_eq!(
2639 resolve(r#"{"bash":{"memory_limit_mib":64}}"#, r#"{"bash":false}"#),
2640 serde_json::json!(64)
2641 );
2642}
2643
2644#[cfg(any(test, feature = "test-support"))]
2645#[test]
2646fn bash_memory_limit_rejects_invalid_values() {
2647 assert!(resolve_config(&[]).config.bash.memory_limit_mib.is_none());
2648 for value in ["0", "-1", "1.5", "true", "\"4GB\"", "4294967296"] {
2649 let doc = format!("{{\"bash\":{{\"memory_limit_mib\":{value}}}}}");
2650 assert!(serde_json::from_str::<RawAftConfig>(&doc).is_err(), "{doc}");
2651 }
2652}
2653
2654fn merge_bash_config(
2655 base: Option<RawBashFeatures>,
2656 override_bash: Option<RawBashFeatures>,
2657) -> Option<RawBashFeatures> {
2658 match (base, override_bash) {
2659 (None, None) => None,
2660 (None, Some(override_bash)) => Some(override_bash),
2661 (Some(base), None) => Some(base),
2662 (Some(base), Some(override_bash)) => {
2663 let override_features = override_bash;
2664 Some(RawBashFeatures {
2665 changed_files: override_features.changed_files.or(base.changed_files),
2666 enabled: override_features.enabled.or(base.enabled),
2667 rewrite: override_features.rewrite.or(base.rewrite),
2668 compress: override_features.compress.or(base.compress),
2669 background: override_features.background.or(base.background),
2670 host_fallback: override_features.host_fallback.or(base.host_fallback),
2671 subagent_background: override_features
2672 .subagent_background
2673 .or(base.subagent_background),
2674 detach_on_user_message: override_features
2675 .detach_on_user_message
2676 .or(base.detach_on_user_message),
2677 db_schema_hints: override_features.db_schema_hints.or(base.db_schema_hints),
2678 long_running_reminder_enabled: override_features
2679 .long_running_reminder_enabled
2680 .or(base.long_running_reminder_enabled),
2681 long_running_reminder_interval_ms: override_features
2682 .long_running_reminder_interval_ms
2683 .or(base.long_running_reminder_interval_ms),
2684 foreground_wait_window_ms: override_features
2685 .foreground_wait_window_ms
2686 .or(base.foreground_wait_window_ms),
2687 watch_sync_max_ms: override_features
2688 .watch_sync_max_ms
2689 .or(base.watch_sync_max_ms),
2690 worker_wait_max_ms: override_features
2691 .worker_wait_max_ms
2692 .or(base.worker_wait_max_ms),
2693 linux_scope: override_features.linux_scope.or(base.linux_scope),
2694 linux_scope_max_runtime_secs: override_features
2695 .linux_scope_max_runtime_secs
2696 .or(base.linux_scope_max_runtime_secs),
2697 memory_limit_mib: override_features.memory_limit_mib.or(base.memory_limit_mib),
2698 disclaim_privacy: override_features.disclaim_privacy.or(base.disclaim_privacy),
2699 powershell_tool: override_features.powershell_tool.or(base.powershell_tool),
2700 env: merge_env_maps(base.env, override_features.env),
2701 project_env: merge_env_maps(base.project_env, override_features.project_env),
2702 runon_env: override_features.runon_env.or(base.runon_env),
2703 })
2704 }
2705 }
2706}
2707
2708fn merge_env_maps(
2711 base: Option<BTreeMap<String, String>>,
2712 override_map: Option<BTreeMap<String, String>>,
2713) -> Option<BTreeMap<String, String>> {
2714 match (base, override_map) {
2715 (None, None) => None,
2716 (Some(base), None) => Some(base),
2717 (None, Some(override_map)) => Some(override_map),
2718 (Some(mut base), Some(override_map)) => {
2719 base.extend(override_map);
2720 Some(base)
2721 }
2722 }
2723}
2724
2725fn merge_idle_config(base: Option<RawIdle>, override_idle: Option<RawIdle>) -> Option<RawIdle> {
2726 let Some(override_idle) = override_idle else {
2727 return base;
2728 };
2729 let mut idle = base.unwrap_or_default();
2730 if override_idle.root_ttl_minutes.is_some() {
2731 idle.root_ttl_minutes = override_idle.root_ttl_minutes;
2732 }
2733 if override_idle.checkout_hours.is_some() {
2734 idle.checkout_hours = override_idle.checkout_hours;
2735 }
2736 (!idle.is_empty()).then_some(idle)
2737}
2738
2739fn merge_inspect_config(
2740 base: Option<RawInspect>,
2741 override_inspect: Option<RawInspect>,
2742) -> Option<RawInspect> {
2743 let Some(override_inspect) = override_inspect else {
2744 return base;
2745 };
2746
2747 let mut inspect = base.unwrap_or_default();
2748 inspect.enabled = override_inspect.enabled.or(inspect.enabled);
2749 if let Some(project_timeout) = override_inspect.diagnostics_timeout_ms {
2750 inspect.diagnostics_timeout_ms = Some(
2753 project_timeout.max(
2754 inspect
2755 .diagnostics_timeout_ms
2756 .unwrap_or(DEFAULT_INSPECT_DIAGNOSTICS_TIMEOUT_MS),
2757 ),
2758 );
2759 }
2760 inspect.tier2_pass_timeout_ms = override_inspect
2761 .tier2_pass_timeout_ms
2762 .or(inspect.tier2_pass_timeout_ms);
2763 if let Some(project) = override_inspect.categories {
2764 let categories = inspect.categories.get_or_insert_with(BTreeMap::new);
2765 for (key, enabled) in project {
2766 let user_enabled = categories.get(&key).copied().unwrap_or(true);
2767 categories.insert(key, enabled && user_enabled);
2768 }
2769 }
2770 inspect.duplicates = merge_inspect_duplicates(inspect.duplicates, override_inspect.duplicates);
2771
2772 (!inspect.is_empty()).then_some(inspect)
2773}
2774
2775fn merge_pi_config(base: Option<RawPi>, override_pi: Option<RawPi>) -> Option<RawPi> {
2780 let Some(override_pi) = override_pi else {
2781 return base;
2782 };
2783
2784 let mut pi = base.unwrap_or_default();
2785 pi.tool_presentation = override_pi.tool_presentation.or(pi.tool_presentation);
2786 pi.external_access_ask = override_pi
2787 .external_access_ask
2788 .filter(|ask| *ask)
2789 .or(pi.external_access_ask);
2790 (!pi.is_empty()).then_some(pi)
2791}
2792
2793fn merge_inspect_duplicates(
2794 base: Option<RawInspectDuplicates>,
2795 override_duplicates: Option<RawInspectDuplicates>,
2796) -> Option<RawInspectDuplicates> {
2797 let Some(override_duplicates) = override_duplicates else {
2798 return base;
2799 };
2800
2801 let mut duplicates = base.unwrap_or_default();
2802 duplicates.expected_mirrors = override_duplicates
2803 .expected_mirrors
2804 .or(duplicates.expected_mirrors);
2805
2806 (!duplicates.is_empty()).then_some(duplicates)
2807}
2808
2809fn record_resource_loosening(
2812 base: &RawAftConfig,
2813 project: &RawAftConfig,
2814 tier: &str,
2815 dropped: &mut Vec<DroppedKey>,
2816) {
2817 let floor = resolve_sandbox_config(base.sandbox.as_ref()).profile;
2818 if let Some(profile) = project
2819 .sandbox
2820 .as_ref()
2821 .and_then(|sandbox| sandbox.profile.as_ref())
2822 {
2823 for (role, next, floor) in [
2824 ("worker", profile.worker, floor.worker),
2825 ("head", profile.head, floor.head),
2826 ] {
2827 if next.is_some_and(|next| next < floor) {
2828 push_drop(
2829 dropped,
2830 &format!("sandbox.profile.{role}"),
2831 tier,
2832 "projects may only select a stricter sandbox profile",
2833 );
2834 }
2835 }
2836 }
2837 const REASON: &str = "resource: project settings may only tighten the user budget";
2838 if let Some(next) = project.lsp.as_ref().and_then(|lsp| lsp.max_servers) {
2839 let floor = base
2840 .lsp
2841 .as_ref()
2842 .and_then(|lsp| lsp.max_servers)
2843 .unwrap_or(8);
2844 if next > floor {
2845 push_drop(dropped, "lsp.max_servers", tier, REASON);
2846 }
2847 }
2848 let cap = |raw: &RawAftConfig| raw.bash.as_ref().and_then(|bash| bash.memory_limit_mib);
2849 if let (Some(user), Some(project)) = (cap(base), cap(project)) {
2850 if project > user {
2851 push_drop(dropped, "bash.memory_limit_mib", tier, REASON);
2852 }
2853 }
2854 if let Some(next) = project.lsp.as_ref().and_then(|lsp| lsp.idle_minutes) {
2855 let floor = base.lsp.as_ref().and_then(|lsp| lsp.idle_minutes);
2856 if lsp_idle_minutes(Some(next)) > lsp_idle_minutes(floor) {
2857 push_drop(dropped, "lsp.idle_minutes", tier, REASON);
2858 }
2859 }
2860 if project.lsp.as_ref().and_then(|lsp| lsp.idle_shutdown) == Some(false)
2861 && base.lsp.as_ref().and_then(|lsp| lsp.idle_shutdown) != Some(false)
2862 {
2863 push_drop(dropped, "lsp.idle_shutdown", tier, REASON);
2864 }
2865 if let Some(categories) = project
2866 .inspect
2867 .as_ref()
2868 .and_then(|inspect| inspect.categories.as_ref())
2869 {
2870 for (key, enabled) in categories {
2871 let floor = base
2872 .inspect
2873 .as_ref()
2874 .and_then(|inspect| inspect.categories.as_ref())
2875 .and_then(|categories| categories.get(key))
2876 .copied()
2877 .unwrap_or(true);
2878 if *enabled && !floor {
2879 push_drop(dropped, &format!("inspect.categories.{key}"), tier, REASON);
2880 }
2881 }
2882 }
2883}
2884
2885fn record_project_drops(raw: &RawAftConfig, tier: &str, dropped: &mut Vec<DroppedKey>) {
2886 if raw
2887 .shell
2888 .as_ref()
2889 .is_some_and(|shell| shell.env_provider.is_some())
2890 {
2891 push_drop(dropped, "shell.env_provider", tier, USER_ONLY_REASON);
2892 }
2893 if raw
2894 .durability
2895 .as_ref()
2896 .is_some_and(|durability| durability.macos_full_sync.is_some())
2897 {
2898 push_drop(
2899 dropped,
2900 "durability.macos_full_sync",
2901 tier,
2902 USER_ONLY_REASON,
2903 );
2904 }
2905 if raw
2906 .storage
2907 .as_ref()
2908 .is_some_and(|storage| storage.cache_dir.is_some())
2909 {
2910 push_drop(dropped, "storage.cache_dir", tier, USER_ONLY_REASON);
2911 }
2912 if matches!(&raw.bash, Some(features) if features.disclaim_privacy == Some(false)) {
2913 push_drop(
2914 dropped,
2915 "bash.disclaim_privacy",
2916 tier,
2917 "projects may only enable privacy disclaiming",
2918 );
2919 }
2920 if matches!(&raw.bash, Some(features) if features.runon_env.is_some()) {
2923 push_drop(dropped, "bash.runon_env", tier, USER_ONLY_REASON);
2924 }
2925 if raw.restrict_to_project_root.is_some() {
2926 push_drop(dropped, "restrict_to_project_root", tier, USER_ONLY_REASON);
2927 }
2928 if raw.url_fetch_allow_private.is_some() {
2929 push_drop(dropped, "url_fetch_allow_private", tier, USER_ONLY_REASON);
2930 }
2931 if raw.formatter_timeout_secs.is_some() {
2932 push_drop(dropped, "formatter_timeout_secs", tier, USER_ONLY_REASON);
2933 }
2934 if raw.type_checker_timeout_secs.is_some() {
2935 push_drop(dropped, "type_checker_timeout_secs", tier, USER_ONLY_REASON);
2936 }
2937 if raw.auto_update.is_some() {
2938 push_drop(dropped, "auto_update", tier, USER_ONLY_REASON);
2939 }
2940 if raw.bridge.is_some() {
2941 push_drop(dropped, "bridge", tier, USER_ONLY_REASON);
2942 }
2943 if raw.subc.is_some() {
2944 push_drop(dropped, "subc", tier, USER_ONLY_REASON);
2945 }
2946 if raw
2947 .pi
2948 .as_ref()
2949 .is_some_and(|pi| pi.external_access_ask == Some(false))
2950 {
2951 push_drop(
2952 dropped,
2953 "pi.external_access_ask",
2954 tier,
2955 "security: a project config may only turn the outside-access prompt on",
2956 );
2957 }
2958
2959 if raw
2960 .backup
2961 .as_ref()
2962 .is_some_and(|backup| backup.enabled.is_some() || backup.max_depth.is_some())
2963 {
2964 push_drop(dropped, "backup", tier, USER_ONLY_REASON);
2965 }
2966 if raw.github.is_some() {
2967 push_drop(dropped, "github", tier, USER_ONLY_REASON);
2968 }
2969 if raw.gh_shim.is_some() {
2970 push_drop(dropped, "gh_shim", tier, USER_ONLY_REASON);
2971 }
2972 if let Some(remote_exec) = &raw.remote_exec {
2973 if remote_exec.enabled == Some(true) {
2974 push_drop(
2975 dropped,
2976 "remote_exec.enabled",
2977 tier,
2978 REMOTE_EXEC_PROJECT_REASON,
2979 );
2980 }
2981 if remote_exec.default_demand.is_some() {
2982 push_drop(
2983 dropped,
2984 "remote_exec.default_demand",
2985 tier,
2986 REMOTE_EXEC_PROJECT_REASON,
2987 );
2988 }
2989 }
2990 if raw
2991 .index
2992 .as_ref()
2993 .and_then(|index| index.roots.as_ref())
2994 .is_some()
2995 {
2996 push_drop(dropped, "index.roots", tier, USER_ONLY_REASON);
2997 }
2998 if let Some(sandbox) = &raw.sandbox {
2999 if sandbox.write_allow.is_some() {
3000 push_drop(dropped, "sandbox.write_allow", tier, USER_ONLY_REASON);
3001 }
3002 }
3003 if raw.bash.as_ref().is_some_and(
3004 |bash| matches!(bash, features if features.changed_files.is_some_and(|mode| mode != crate::config::BashChangedFiles::Off)),
3005 ) {
3006 push_drop(dropped, "bash.changed_files", tier, "a project config may only turn changed-file reporting off");
3007 }
3008 if raw
3009 .bash
3010 .as_ref()
3011 .is_some_and(|bash| matches!(bash, features if features.linux_scope.is_some()))
3012 {
3013 push_drop(dropped, "bash.linux_scope", tier, USER_ONLY_REASON);
3014 }
3015 if raw.bash.as_ref().is_some_and(
3016 |bash| matches!(bash, features if features.linux_scope_max_runtime_secs.is_some()),
3017 ) {
3018 push_drop(
3019 dropped,
3020 "bash.linux_scope_max_runtime_secs",
3021 tier,
3022 USER_ONLY_REASON,
3023 );
3024 }
3025 for tool in feature_config::normalize_tool_list(
3026 raw.disabled_tools
3027 .iter()
3028 .flatten()
3029 .filter(|tool| feature_config::is_project_protected_tool(tool))
3030 .cloned(),
3031 ) {
3032 push_drop(
3033 dropped,
3034 &format!("disabled_tools.{tool}"),
3035 tier,
3036 PROTECTED_TOOL_REASON,
3037 );
3038 }
3039
3040 if let Some(semantic) = &raw.semantic {
3041 if semantic.backend.is_some() {
3042 push_drop(dropped, "semantic.backend", tier, SEMANTIC_SECRET_REASON);
3043 }
3044 if semantic.base_url.is_some() {
3045 push_drop(dropped, "semantic.base_url", tier, SEMANTIC_SECRET_REASON);
3046 }
3047 if semantic.api_key_env.is_some() {
3048 push_drop(
3049 dropped,
3050 "semantic.api_key_env",
3051 tier,
3052 SEMANTIC_SECRET_REASON,
3053 );
3054 }
3055 if semantic.query_timeout_ms.is_some() {
3056 push_drop(dropped, "semantic.query_timeout_ms", tier, USER_ONLY_REASON);
3057 }
3058 }
3059
3060 if let Some(rerank) = raw
3061 .search
3062 .as_ref()
3063 .and_then(|search| search.rerank.as_ref())
3064 {
3065 if rerank
3069 .backend
3070 .is_some_and(|backend| backend != RerankBackendKind::Off)
3071 {
3072 push_drop(
3073 dropped,
3074 "search.rerank.backend",
3075 tier,
3076 RERANK_PROJECT_REASON,
3077 );
3078 }
3079 for (key, present) in [
3080 ("search.rerank.model", rerank.model.is_some()),
3081 ("search.rerank.endpoint", rerank.endpoint.is_some()),
3082 ("search.rerank.api_key_env", rerank.api_key_env.is_some()),
3083 ("search.rerank.top_n", rerank.top_n.is_some()),
3084 ("search.rerank.timeout_ms", rerank.timeout_ms.is_some()),
3085 ] {
3086 if present {
3087 push_drop(dropped, key, tier, RERANK_PROJECT_REASON);
3088 }
3089 }
3090 }
3091
3092 if let Some(lsp) = &raw.lsp {
3093 if lsp.servers.is_some() {
3094 push_drop(dropped, "lsp.servers", tier, LSP_USER_ONLY_REASON);
3095 }
3096 if lsp.versions.is_some() {
3097 push_drop(dropped, "lsp.versions", tier, LSP_USER_ONLY_REASON);
3098 }
3099 if lsp.auto_install.is_some() {
3100 push_drop(dropped, "lsp.auto_install", tier, LSP_USER_ONLY_REASON);
3101 }
3102 if lsp.grace_days.is_some() {
3103 push_drop(dropped, "lsp.grace_days", tier, LSP_USER_ONLY_REASON);
3104 }
3105 if lsp.disabled.is_some() {
3106 push_drop(dropped, "lsp.disabled", tier, LSP_USER_ONLY_REASON);
3107 }
3108 }
3109}
3110
3111fn push_drop(dropped: &mut Vec<DroppedKey>, key: &str, tier: &str, reason: &str) {
3112 dropped.push(DroppedKey {
3113 key: key.to_string(),
3114 tier: tier.to_string(),
3115 reason: reason.to_string(),
3116 });
3117}
3118
3119fn apply_resolved_config(
3124 raw: &RawAftConfig,
3125 config: &mut Config,
3126 warnings: &mut Vec<ConfigWarning>,
3127) -> Result<(), Vec<String>> {
3128 config.shell = raw.shell.clone().unwrap_or_default();
3129 if let Some(provider) = &config.shell.env_provider {
3130 provider.validate().map_err(|error| vec![error])?;
3131 }
3132 config.hashline_enabled = matches!(raw.edit_mode, Some(RawEditMode::Hashline));
3133 config.durability.macos_full_sync = raw
3134 .durability
3135 .as_ref()
3136 .and_then(|durability| durability.macos_full_sync)
3137 .unwrap_or(false);
3138 let Some(disabled_tools) = &raw.disabled_tools else {
3141 return Err(vec![
3142 "invalid_resolved_config:missing:disabled_tools".to_string()
3143 ]);
3144 };
3145 config.disabled_tools = feature_config::normalize_tool_list(disabled_tools.iter().cloned());
3146 config.aft_search_registered = config.tool_registered("aft_search");
3147 let indexes = raw.indexes.unwrap_or_default();
3148 let defaults = IndexesConfig::default();
3149 config.indexes = IndexesConfig {
3150 trigram: indexes.trigram.unwrap_or(defaults.trigram),
3151 semantic: indexes.semantic.unwrap_or(defaults.semantic),
3152 callgraph: indexes.callgraph.unwrap_or(defaults.callgraph),
3153 };
3154 if let Some(value) = raw.format_on_edit {
3155 config.format_on_edit = value;
3156 }
3157 if let Some(value) = raw.revision_reads {
3158 config.revision_reads = value;
3159 }
3160 if let Some(value) = raw.formatter_timeout_secs {
3161 config.formatter_timeout_secs = value;
3162 }
3163 if let Some(value) = raw.type_checker_timeout_secs {
3164 config.type_checker_timeout_secs = value;
3165 }
3166 if let Some(value) = raw.validate_on_edit {
3167 config.validate_on_edit = Some(value.as_str().to_string());
3168 }
3169 if let Some(formatter) = &raw.formatter {
3170 config.formatter = formatter
3171 .iter()
3172 .map(|(language, formatter)| (language.clone(), formatter.as_str().to_string()))
3173 .collect();
3174 }
3175 if let Some(checker) = &raw.checker {
3176 config.checker = checker
3177 .iter()
3178 .map(|(language, checker)| (language.clone(), checker.as_str().to_string()))
3179 .collect();
3180 }
3181 if let Some(value) = raw.restrict_to_project_root {
3182 config.restrict_to_project_root = value;
3183 }
3184 config.memory = raw.memory;
3185 if let Some(value) = raw.url_fetch_allow_private {
3186 config.url_fetch_allow_private = value;
3187 }
3188 config.semantic = resolve_semantic_config(raw.semantic.as_ref(), raw.subc.as_ref());
3189 config.search = resolve_search_config(raw.search.as_ref());
3190 config.inspect = resolve_inspect_config(raw.inspect.as_ref());
3191 config.backup = resolve_backup_config(raw.backup.as_ref());
3192 config.github = resolve_github_config(raw.github.as_ref(), warnings);
3193 config.gh_shim = resolve_gh_shim_config(raw.gh_shim.as_ref());
3194
3195 config.git = resolve_git_config(raw.git.as_ref());
3196 config.sandbox = resolve_sandbox_config(raw.sandbox.as_ref());
3197 config.remote_exec = resolve_remote_exec_config(raw);
3198 resolve_lsp_config(raw, config);
3199 resolve_bash_fields(raw, config, warnings);
3200 Ok(())
3201}
3202
3203fn resolve_index_config(raw: Option<&RawIndex>, warnings: &mut Vec<ConfigWarning>) -> IndexConfig {
3204 let Some(raw) = raw else {
3205 return IndexConfig::default();
3206 };
3207 let Some(roots) = raw.roots.as_ref() else {
3208 return IndexConfig::default();
3209 };
3210
3211 let home = crate::environment::non_empty_os_var("HOME")
3212 .or_else(|| crate::environment::non_empty_os_var("USERPROFILE"))
3213 .map(PathBuf::from);
3214 let mut normalized_roots = Vec::with_capacity(roots.len());
3215
3216 for (position, root) in roots.iter().enumerate() {
3217 for field in root.unknown.keys() {
3218 warnings.push(ConfigWarning {
3219 code: "unknown_index_root_field",
3220 key: "index.roots",
3221 tier: "user".to_string(),
3222 value: field.clone(),
3223 message: format!(
3224 "Ignoring unknown field index.roots[{position}].{field}; only path and indexes are defined"
3225 ),
3226 });
3227 }
3228
3229 let result = (|| -> Result<IndexRootConfig, String> {
3230 let path = root.path.as_deref().ok_or_else(|| {
3231 "index.roots entry is missing required string field path".to_string()
3232 })?;
3233 expand_index_root_path(path, home.as_deref())?;
3234
3235 let indexes = root.indexes.as_ref().ok_or_else(|| {
3236 "index.roots entry is missing required non-empty indexes array".to_string()
3237 })?;
3238 if indexes.is_empty() {
3239 return Err("index.roots indexes must be a non-empty array".to_string());
3240 }
3241
3242 let mut normalized = Vec::with_capacity(indexes.len() + 1);
3243 for name in indexes {
3244 let kind = IndexKind::from_name(name).ok_or_else(|| {
3245 format!(
3246 "index.roots indexes contains unknown name {name:?}; valid names: search, semantic, callgraph"
3247 )
3248 })?;
3249 if normalized.contains(&kind) {
3250 return Err(format!(
3251 "index.roots indexes contains duplicate name {name:?}"
3252 ));
3253 }
3254 normalized.push(kind);
3255 }
3256 if normalized.contains(&IndexKind::Semantic) && !normalized.contains(&IndexKind::Search)
3257 {
3258 normalized.push(IndexKind::Search);
3259 warnings.push(ConfigWarning {
3260 code: "index_dependency_closure",
3261 key: "index.roots",
3262 tier: "user".to_string(),
3263 value: path.to_string(),
3264 message: format!(
3265 "Added search to index.roots[{position}].indexes because semantic depends on search"
3266 ),
3267 });
3268 }
3269 normalized.sort_unstable();
3270 Ok(IndexRootConfig {
3271 path: path.to_string(),
3272 indexes: normalized,
3273 })
3274 })();
3275
3276 match result {
3277 Ok(root) => normalized_roots.push(root),
3278 Err(message) => {
3279 warnings.push(ConfigWarning {
3280 code: "invalid_index_roots",
3281 key: "index.roots",
3282 tier: "user".to_string(),
3283 value: position.to_string(),
3284 message,
3285 });
3286 return IndexConfig::default();
3287 }
3288 }
3289 }
3290
3291 IndexConfig {
3292 roots: normalized_roots,
3293 }
3294}
3295
3296fn resolve_semantic_config(
3297 raw: Option<&RawSemantic>,
3298 subc: Option<&RawSubc>,
3299) -> SemanticBackendConfig {
3300 let mut semantic = SemanticBackendConfig::default();
3301 semantic.subc_connection_file = subc
3302 .and_then(|subc| subc.connection_file.as_deref())
3303 .map(str::trim)
3304 .filter(|path| !path.is_empty())
3305 .map(PathBuf::from);
3306 let Some(raw) = raw else {
3307 return semantic;
3308 };
3309
3310 if let Some(value) = raw.backend {
3311 semantic.backend = value;
3312 if value == SemanticBackend::Synapse && raw.model.is_none() {
3313 semantic.model.clear();
3316 }
3317 }
3318 if let Some(value) = &raw.model {
3319 semantic.model = value.clone();
3320 }
3321 if let Some(value) = &raw.base_url {
3322 semantic.base_url = Some(value.clone());
3323 }
3324 if let Some(value) = &raw.api_key_env {
3325 semantic.api_key_env = Some(value.clone());
3326 }
3327 if let Some(value) = raw.timeout_ms {
3328 semantic.timeout_ms = value.min(MAX_SEMANTIC_TIMEOUT_MS);
3329 }
3330 if let Some(value) = &raw.query_instruction {
3331 semantic.query_instruction = value.clone();
3332 }
3333 if let Some(value) = raw.query_timeout_ms {
3334 semantic.query_timeout_ms =
3335 value.clamp(MIN_SEMANTIC_QUERY_TIMEOUT_MS, MAX_SEMANTIC_QUERY_TIMEOUT_MS);
3336 }
3337 if let Some(value) = raw.max_batch_size {
3338 semantic.max_batch_size = value.min(MAX_SEMANTIC_BATCH_SIZE);
3339 }
3340 if let Some(value) = raw.max_input_tokens {
3341 semantic.max_input_tokens = Some(value);
3342 }
3343 if let Some(value) = raw.max_files {
3344 semantic.max_files = value;
3345 }
3346
3347 semantic
3348}
3349
3350fn resolve_idle_config(raw: Option<&RawIdle>, warnings: &mut Vec<ConfigWarning>) -> IdleConfig {
3351 let mut idle = IdleConfig::default();
3352 let Some(raw) = raw else {
3353 return idle;
3354 };
3355 idle.root_ttl_minutes = resolve_clamped_minutes(
3356 raw.root_ttl_minutes.as_ref(),
3357 "idle.root_ttl_minutes",
3358 DEFAULT_IDLE_ROOT_TTL_MINUTES,
3359 MIN_IDLE_ROOT_TTL_MINUTES,
3360 MAX_IDLE_ROOT_TTL_MINUTES,
3361 warnings,
3362 );
3363 idle.checkout_hours = resolve_clamped_minutes(
3364 raw.checkout_hours.as_ref(),
3365 "idle.checkout_hours",
3366 crate::config::DEFAULT_IDLE_CHECKOUT_HOURS,
3367 crate::config::MIN_IDLE_CHECKOUT_HOURS,
3368 crate::config::MAX_IDLE_CHECKOUT_HOURS,
3369 warnings,
3370 );
3371 idle
3372}
3373
3374fn resolve_clamped_minutes(
3378 raw: Option<&Value>,
3379 key: &'static str,
3380 default: u32,
3381 min: u32,
3382 max: u32,
3383 warnings: &mut Vec<ConfigWarning>,
3384) -> u32 {
3385 let Some(value) = raw else {
3386 return default;
3387 };
3388 let Some(parsed) = json_integer(value) else {
3389 warnings.push(ConfigWarning {
3390 code: "invalid_idle_ttl",
3391 key,
3392 tier: "config".to_string(),
3393 value: value.to_string(),
3394 message: format!("{key} must be an integer; using default {default}"),
3395 });
3396 return default;
3397 };
3398 let clamped = parsed.clamp(i64::from(min), i64::from(max)) as u32;
3399 if i64::from(clamped) != parsed {
3400 warnings.push(ConfigWarning {
3401 code: "clamped_idle_ttl",
3402 key,
3403 tier: "config".to_string(),
3404 value: parsed.to_string(),
3405 message: format!("{key}={parsed} is outside {min}..={max}; clamped to {clamped}"),
3406 });
3407 }
3408 clamped
3409}
3410
3411fn resolve_clamped_bash_watch_sync_max_ms(
3412 raw: Option<u64>,
3413 warnings: &mut Vec<ConfigWarning>,
3414) -> u64 {
3415 let Some(raw) = raw else {
3416 return DEFAULT_BASH_WATCH_SYNC_MAX_MS;
3417 };
3418 let clamped = raw.clamp(MIN_BASH_WATCH_SYNC_MAX_MS, MAX_BASH_WATCH_SYNC_MAX_MS);
3419 if clamped != raw {
3420 warnings.push(ConfigWarning {
3421 code: "clamped_bash_watch_sync_max_ms",
3422 key: "bash.watch_sync_max_ms",
3423 tier: "config".to_string(),
3424 value: raw.to_string(),
3425 message: format!(
3426 "bash.watch_sync_max_ms={raw} is outside {MIN_BASH_WATCH_SYNC_MAX_MS}..={MAX_BASH_WATCH_SYNC_MAX_MS}; clamped to {clamped}"
3427 ),
3428 });
3429 }
3430 clamped
3431}
3432
3433fn json_integer(value: &Value) -> Option<i64> {
3434 match value {
3435 Value::Number(number) if number.is_i64() => number.as_i64(),
3436 Value::Number(number) if number.is_u64() => {
3437 number.as_u64().and_then(|value| i64::try_from(value).ok())
3438 }
3439 _ => None,
3440 }
3441}
3442
3443fn resolve_inspect_config(raw: Option<&RawInspect>) -> InspectConfig {
3444 let mut inspect = InspectConfig::default();
3445 let Some(raw) = raw else {
3446 return inspect;
3447 };
3448 if let Some(enabled) = raw.enabled {
3449 inspect.enabled = enabled;
3450 }
3451 if let Some(categories) = &raw.categories {
3452 inspect.categories = serde_json::from_value(serde_json::to_value(categories).unwrap())
3453 .expect("validated inspect categories");
3454 }
3455 if let Some(value) = raw.diagnostics_timeout_ms {
3456 inspect.diagnostics_timeout_ms = value.clamp(
3457 MIN_INSPECT_DIAGNOSTICS_TIMEOUT_MS,
3458 MAX_INSPECT_DIAGNOSTICS_TIMEOUT_MS,
3459 );
3460 }
3461 if let Some(value) = raw.tier2_pass_timeout_ms {
3462 inspect.tier2_pass_timeout_ms = value;
3463 }
3464 if let Some(expected_mirrors) = raw
3465 .duplicates
3466 .as_ref()
3467 .and_then(|duplicates| duplicates.expected_mirrors.clone())
3468 {
3469 inspect.duplicates.expected_mirrors = expected_mirrors
3470 .into_iter()
3471 .map(|pair| [pair.source, pair.mirror])
3472 .collect();
3473 }
3474 inspect
3475}
3476
3477fn resolve_backup_config(raw: Option<&RawBackup>) -> BackupConfig {
3478 let mut backup = BackupConfig::default();
3479 if let Some(raw) = raw {
3480 if raw.enabled.is_some() {
3481 backup.enabled = raw.enabled;
3482 }
3483 if raw.max_depth.is_some() {
3484 backup.max_depth = raw.max_depth;
3485 }
3486 if raw.max_file_size.is_some() {
3487 backup.max_file_size = raw.max_file_size;
3488 }
3489 }
3490 backup
3491}
3492
3493fn resolve_github_config(
3494 raw: Option<&RawGithub>,
3495 warnings: &mut Vec<ConfigWarning>,
3496) -> GithubConfig {
3497 let mut github = GithubConfig::default();
3498 if let Some(value) = raw.and_then(|raw| raw.shim) {
3499 github.shim = value;
3500 }
3501 if let Some(value) = raw.and_then(|raw| raw.read) {
3502 github.read = value;
3503 }
3504 if let Some(value) = raw.and_then(|raw| raw.write) {
3505 github.write = value;
3506 }
3507
3508 if github.write && !github.read {
3511 github.read = true;
3512 warnings.push(ConfigWarning {
3513 code: "github_write_requires_read",
3514 key: "github.write",
3515 tier: "user".to_string(),
3516 value: "true".to_string(),
3517 message: "github.write=true requires github.read=true; treating github.read as enabled"
3518 .to_string(),
3519 });
3520 }
3521
3522 github
3523}
3524
3525fn resolve_gh_shim_config(raw: Option<&RawGhShim>) -> GhShimConfig {
3526 let mut gh_shim = GhShimConfig::default();
3527 gh_shim.binary_path = raw
3528 .and_then(|raw| raw.binary_path.as_ref())
3529 .map(PathBuf::from);
3530 gh_shim
3531}
3532
3533fn resolve_git_config(raw: Option<&RawGit>) -> GitConfig {
3534 GitConfig {
3535 co_author: raw
3536 .and_then(|raw| raw.co_author.clone())
3537 .unwrap_or_else(|| "off".to_string()),
3538 }
3539}
3540
3541fn resolve_sandbox_config(raw: Option<&RawSandbox>) -> SandboxConfig {
3542 let Some(raw) = raw else {
3543 return SandboxConfig::default();
3544 };
3545 SandboxConfig {
3546 profile: crate::config::SandboxRoles {
3547 worker: raw
3548 .profile
3549 .as_ref()
3550 .and_then(|profile| profile.worker)
3551 .unwrap_or(crate::config::SandboxMode::Relaxed),
3552 head: raw
3553 .profile
3554 .as_ref()
3555 .and_then(|profile| profile.head)
3556 .unwrap_or(crate::config::SandboxMode::Off),
3557 },
3558 write_allow: raw.write_allow.clone().unwrap_or_default(),
3559 read_deny: raw.read_deny.clone().unwrap_or_default(),
3560 }
3561}
3562
3563fn resolve_remote_exec_config(raw: &RawAftConfig) -> RemoteExecConfig {
3564 let user = raw.remote_exec.as_ref();
3565 RemoteExecConfig {
3566 enabled: user.and_then(|r| r.enabled) == Some(true) && !raw.remote_exec_project_off,
3567 default_demand: user.and_then(|r| r.default_demand.clone()),
3568 project_off: raw.remote_exec_project_off,
3569 }
3570}
3571
3572fn resolve_lsp_config(raw: &RawAftConfig, config: &mut Config) {
3573 let lsp = raw.lsp.as_ref();
3574 config.lsp_idle_minutes = lsp_idle_minutes(lsp.and_then(|lsp| lsp.idle_minutes));
3575 config.lsp_idle_shutdown = lsp.and_then(|lsp| lsp.idle_shutdown).unwrap_or(true);
3576 config.lsp_max_servers = lsp.and_then(|lsp| lsp.max_servers).unwrap_or(8);
3577 let mut disabled: HashSet<String> = lsp
3578 .and_then(|lsp| lsp.disabled.as_ref())
3579 .into_iter()
3580 .flatten()
3581 .map(|value| value.to_ascii_lowercase())
3582 .collect();
3583 let mut experimental_ty = raw
3584 .experimental
3585 .as_ref()
3586 .and_then(|experimental| experimental.lsp_ty);
3587
3588 match lsp.and_then(|lsp| lsp.python).unwrap_or(RawPythonLsp::Auto) {
3589 RawPythonLsp::Ty => {
3590 experimental_ty = Some(true);
3591 disabled.insert("python".to_string());
3592 }
3593 RawPythonLsp::Pyright => {
3594 experimental_ty = Some(false);
3595 disabled.insert("ty".to_string());
3596 }
3597 RawPythonLsp::Auto => {}
3598 }
3599
3600 if let Some(value) = experimental_ty {
3601 config.experimental_lsp_ty = value;
3602 }
3603
3604 if let Some(value) = lsp.and_then(|lsp| lsp.diagnostics_on_edit) {
3605 config.diagnostics_on_edit = value;
3606 }
3607
3608 if let Some(servers) = lsp.and_then(|lsp| lsp.servers.as_ref()) {
3609 let invalid = &mut config.invalid_lsp_initialization_options;
3610 config.lsp_servers = servers
3611 .iter()
3612 .map(|(id, server)| UserServerDef {
3613 id: id.clone(),
3614 extensions: server
3615 .extensions
3616 .clone()
3617 .unwrap_or_default()
3618 .into_iter()
3619 .map(|extension| extension.trim_start_matches('.').to_string())
3620 .collect(),
3621 binary: server.binary.clone().unwrap_or_default(),
3622 args: server.args.clone().unwrap_or_default(),
3623 root_markers: server
3624 .root_markers
3625 .clone()
3626 .unwrap_or_else(|| vec![".git".to_string()]),
3627 env: server.env.clone().unwrap_or_default(),
3628 initialization_options: server.initialization_options.as_deref().and_then(|text| {
3629 match serde_json::from_str(text) {
3630 Ok(options) => Some(options),
3631 Err(_) => {
3632 invalid.push(id.clone());
3633 None
3634 }
3635 }
3636 }),
3637 disabled: server.disabled.unwrap_or(false),
3638 })
3639 .collect();
3640 }
3641
3642 if !disabled.is_empty() {
3643 config.disabled_lsp = disabled;
3644 }
3645}
3646
3647fn lsp_idle_minutes(value: Option<i64>) -> u32 {
3648 use crate::config::{DEFAULT_LSP_IDLE_MINUTES, MAX_LSP_IDLE_MINUTES, MIN_LSP_IDLE_MINUTES};
3649 value.unwrap_or(i64::from(DEFAULT_LSP_IDLE_MINUTES)).clamp(
3650 i64::from(MIN_LSP_IDLE_MINUTES),
3651 i64::from(MAX_LSP_IDLE_MINUTES),
3652 ) as u32
3653}
3654
3655#[derive(Debug, Clone, PartialEq, Eq)]
3657pub struct ConfiguredBashEnv {
3658 pub names: BTreeMap<String, String>,
3659 pub tier: crate::bash_env::BashEnvTier,
3660}
3661
3662#[derive(Debug, Clone, PartialEq, Eq)]
3663struct ResolvedBashConfig {
3664 changed_files: crate::config::BashChangedFiles,
3665 enabled: bool,
3666 rewrite: bool,
3667 compress: bool,
3668 background: bool,
3669 host_fallback: bool,
3670 subagent_background: bool,
3671 detach_on_user_message: bool,
3672 db_schema_hints: bool,
3673 long_running_reminder_enabled: Option<bool>,
3674 long_running_reminder_interval_ms: Option<u64>,
3675 foreground_wait_window_ms: u64,
3676 watch_sync_max_ms: u64,
3677 worker_wait_max_ms: u64,
3678 linux_scope: bool,
3679 linux_scope_max_runtime_secs: u64,
3680 memory_limit_mib: Option<u64>,
3681 disclaim_privacy: bool,
3682 powershell_tool: bool,
3683 env: BTreeMap<String, String>,
3684 project_env: BTreeMap<String, String>,
3685 runon_env: Vec<String>,
3686}
3687
3688fn resolve_bash_fields(raw: &RawAftConfig, config: &mut Config, warnings: &mut Vec<ConfigWarning>) {
3689 let bash = resolve_bash_config(raw, warnings);
3690 let _plugin_only = bash.subagent_background;
3693 config.bash.enabled = bash.enabled;
3694 config.bash.changed_files = bash.changed_files;
3695 config.bash.host_fallback = bash.host_fallback;
3696 config.bash.detach_on_user_message = bash.detach_on_user_message;
3697 config.bash.db_schema_hints = bash.db_schema_hints;
3698 config.bash.watch_sync_max_ms = bash.watch_sync_max_ms;
3699 config.bash.worker_wait_max_ms = bash.worker_wait_max_ms;
3700 config.bash.linux_scope = bash.linux_scope;
3701 config.bash.linux_scope_max_runtime_secs = bash.linux_scope_max_runtime_secs;
3702 config.bash.memory_limit_mib = bash.memory_limit_mib;
3703 config.bash.disclaim_privacy = bash.disclaim_privacy;
3704 config.bash.powershell_tool = bash.powershell_tool;
3705 config.bash.env = bash.env;
3706 config.bash.project_env = bash.project_env;
3707 config.bash.runon_env = bash.runon_env;
3708 config.experimental_bash_rewrite = bash.rewrite;
3709 config.experimental_bash_compress = bash.compress;
3710 config.experimental_bash_background = bash.background;
3711 config.foreground_wait_window_ms = bash.foreground_wait_window_ms;
3712 if let Some(value) = bash.long_running_reminder_enabled {
3713 config.bash_long_running_reminder_enabled = value;
3714 }
3715 if let Some(value) = bash.long_running_reminder_interval_ms {
3716 config.bash_long_running_reminder_interval_ms = value;
3717 }
3718}
3719
3720fn resolve_bash_config(
3721 raw: &RawAftConfig,
3722 warnings: &mut Vec<ConfigWarning>,
3723) -> ResolvedBashConfig {
3724 let top = raw.bash.as_ref();
3725
3726 let top_features = top;
3727 let reminder_enabled = top_features.and_then(|features| features.long_running_reminder_enabled);
3728 let reminder_interval =
3729 top_features.and_then(|features| features.long_running_reminder_interval_ms);
3730 let top_host_fallback = top_features
3731 .and_then(|features| features.host_fallback)
3732 .unwrap_or(false);
3733 let top_subagent_background = top_features
3734 .and_then(|features| features.subagent_background)
3735 .unwrap_or(true);
3736 let top_detach_on_user_message = top_features
3737 .and_then(|features| features.detach_on_user_message)
3738 .unwrap_or(true);
3739 let raw_foreground_wait = top_features.and_then(|features| features.foreground_wait_window_ms);
3740 let raw_watch_sync_max = top_features.and_then(|features| features.watch_sync_max_ms);
3741 let watch_sync_max_ms = resolve_clamped_bash_watch_sync_max_ms(raw_watch_sync_max, warnings);
3742 let worker_wait_max_ms = top_features
3745 .and_then(|features| features.worker_wait_max_ms)
3746 .unwrap_or(DEFAULT_BASH_WORKER_WAIT_MAX_MS);
3747 let top_linux_scope = top_features
3748 .and_then(|features| features.linux_scope)
3749 .unwrap_or(true);
3750 let top_powershell_tool = top_features
3751 .and_then(|features| features.powershell_tool)
3752 .unwrap_or(false);
3753 let foreground_wait_window_ms = raw_foreground_wait
3754 .unwrap_or(FOREGROUND_WAIT_WINDOW_DEFAULT_MS)
3755 .max(FOREGROUND_WAIT_WINDOW_MIN_MS);
3756
3757 let base = ResolvedBashConfig {
3758 changed_files: top_features
3759 .and_then(|features| features.changed_files)
3760 .unwrap_or_default(),
3761 enabled: false,
3762 rewrite: false,
3763 compress: false,
3764 background: false,
3765 host_fallback: false,
3766 subagent_background: true,
3767 detach_on_user_message: true,
3768 db_schema_hints: top_features
3769 .and_then(|features| features.db_schema_hints)
3770 .unwrap_or(true),
3771 long_running_reminder_enabled: reminder_enabled,
3772 long_running_reminder_interval_ms: reminder_interval,
3773 foreground_wait_window_ms,
3774 watch_sync_max_ms,
3775 worker_wait_max_ms,
3776 linux_scope: top_linux_scope,
3777 linux_scope_max_runtime_secs: top_features
3778 .and_then(|features| features.linux_scope_max_runtime_secs)
3779 .unwrap_or(crate::config::DEFAULT_LINUX_SCOPE_MAX_RUNTIME_SECS),
3780 memory_limit_mib: top_features.and_then(|features| features.memory_limit_mib),
3781 disclaim_privacy: top_features
3782 .and_then(|features| features.disclaim_privacy)
3783 .unwrap_or(false),
3784 powershell_tool: false,
3785 env: BTreeMap::new(),
3786 project_env: BTreeMap::new(),
3787 runon_env: Vec::new(),
3788 };
3789
3790 match top {
3791 Some(features) => ResolvedBashConfig {
3792 enabled: features.enabled.unwrap_or(true),
3793 rewrite: features.rewrite.unwrap_or(true),
3794 compress: features.compress.unwrap_or(true),
3795 background: features.background.unwrap_or(true),
3796 host_fallback: top_host_fallback,
3797 subagent_background: top_subagent_background,
3798 detach_on_user_message: top_detach_on_user_message,
3799 powershell_tool: top_powershell_tool,
3800 env: features.env.clone().unwrap_or_default(),
3801 project_env: features.project_env.clone().unwrap_or_default(),
3802 runon_env: features.runon_env.clone().unwrap_or_default(),
3803 ..base
3804 },
3805 None => ResolvedBashConfig {
3806 enabled: true,
3807 rewrite: true,
3808 compress: true,
3809 background: true,
3810 ..base
3811 },
3812 }
3813}
3814
3815fn deserialize_opt_git_co_author<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
3816where
3817 D: Deserializer<'de>,
3818{
3819 let value = Option::<String>::deserialize(deserializer)?;
3820 value
3821 .map(|value| {
3822 normalize_git_co_author(&value).ok_or_else(|| {
3823 de::Error::custom(
3824 "git.co_author must be 'off', 'auto', or an explicit 'Name <email>' identity",
3825 )
3826 })
3827 })
3828 .transpose()
3829}
3830
3831fn deserialize_opt_trimmed_non_empty_string<'de, D>(
3832 deserializer: D,
3833) -> Result<Option<String>, D::Error>
3834where
3835 D: Deserializer<'de>,
3836{
3837 let value = Option::<String>::deserialize(deserializer)?;
3838 value
3839 .map(|value| {
3840 let trimmed = value.trim().to_string();
3841 if trimmed.is_empty() {
3842 Err(de::Error::custom("must be a non-empty string"))
3843 } else {
3844 Ok(trimmed)
3845 }
3846 })
3847 .transpose()
3848}
3849
3850fn deserialize_opt_trimmed_non_empty_string_vec<'de, D>(
3851 deserializer: D,
3852) -> Result<Option<Vec<String>>, D::Error>
3853where
3854 D: Deserializer<'de>,
3855{
3856 let value = Option::<Vec<String>>::deserialize(deserializer)?;
3857 value
3858 .map(|values| {
3859 values
3860 .into_iter()
3861 .map(|value| {
3862 let trimmed = value.trim().to_string();
3863 if trimmed.is_empty() {
3864 Err(de::Error::custom("array entries must be non-empty strings"))
3865 } else {
3866 Ok(trimmed)
3867 }
3868 })
3869 .collect()
3870 })
3871 .transpose()
3872}
3873
3874fn deserialize_opt_lsp_extensions<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
3875where
3876 D: Deserializer<'de>,
3877{
3878 let value = Option::<Vec<String>>::deserialize(deserializer)?;
3879 value
3880 .map(|values| {
3881 if values.is_empty() {
3882 return Err(de::Error::custom(
3883 "extensions must contain at least one entry",
3884 ));
3885 }
3886 values
3887 .into_iter()
3888 .map(|value| {
3889 let trimmed = value.trim().to_string();
3890 if trimmed.is_empty() || trimmed.trim_start_matches('.').is_empty() {
3891 Err(de::Error::custom(
3892 "extension must include characters other than leading dots",
3893 ))
3894 } else {
3895 Ok(trimmed)
3896 }
3897 })
3898 .collect()
3899 })
3900 .transpose()
3901}
3902
3903fn deserialize_opt_lsp_servers<'de, D>(
3904 deserializer: D,
3905) -> Result<Option<BTreeMap<String, RawLspServerEntry>>, D::Error>
3906where
3907 D: Deserializer<'de>,
3908{
3909 let value = Option::<BTreeMap<String, RawLspServerEntry>>::deserialize(deserializer)?;
3910 value
3911 .map(|entries| {
3912 entries
3913 .into_iter()
3914 .map(|(key, value)| {
3915 let trimmed = key.trim().to_string();
3916 if trimmed.is_empty() {
3917 Err(de::Error::custom(
3918 "lsp.servers keys must be non-empty strings",
3919 ))
3920 } else {
3921 Ok((trimmed, value))
3922 }
3923 })
3924 .collect()
3925 })
3926 .transpose()
3927}
3928
3929fn deserialize_opt_versions_map<'de, D>(
3930 deserializer: D,
3931) -> Result<Option<HashMap<String, String>>, D::Error>
3932where
3933 D: Deserializer<'de>,
3934{
3935 let value = Option::<HashMap<String, String>>::deserialize(deserializer)?;
3936 value
3937 .map(|entries| {
3938 entries
3939 .into_iter()
3940 .map(|(key, value)| {
3941 let trimmed_key = key.trim().to_string();
3942 let trimmed_value = value.trim().to_string();
3943 if trimmed_key.is_empty() || trimmed_value.is_empty() {
3944 Err(de::Error::custom(
3945 "lsp.versions keys and values must be non-empty strings",
3946 ))
3947 } else {
3948 Ok((trimmed_key, trimmed_value))
3949 }
3950 })
3951 .collect()
3952 })
3953 .transpose()
3954}
3955
3956fn deserialize_opt_positive_u64<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
3957where
3958 D: Deserializer<'de>,
3959{
3960 let value = Option::<u64>::deserialize(deserializer)?;
3961 match value {
3962 Some(0) => Err(de::Error::custom("must be a positive integer")),
3963 other => Ok(other),
3964 }
3965}
3966
3967fn deserialize_opt_linux_scope_max_runtime_secs<'de, D>(
3968 deserializer: D,
3969) -> Result<Option<u64>, D::Error>
3970where
3971 D: Deserializer<'de>,
3972{
3973 let value = Option::<u64>::deserialize(deserializer)
3974 .map_err(|error| de::Error::custom(format!("linux_scope_max_runtime_secs: {error}")))?;
3975 if value.is_some_and(|value| !(1..=4_294_967_295).contains(&value)) {
3976 return Err(de::Error::custom(
3977 "linux_scope_max_runtime_secs must be from 1 to 4294967295",
3978 ));
3979 }
3980 Ok(value)
3981}
3982
3983fn deserialize_opt_memory_limit_mib<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
3984where
3985 D: serde::Deserializer<'de>,
3986{
3987 let value = Option::<u64>::deserialize(deserializer)?;
3988 if value.is_some_and(|value| value == 0 || value > 4_294_967_295) {
3989 return Err(serde::de::Error::custom(
3990 "expected memory limit in MiB from 1 to 4294967295",
3991 ));
3992 }
3993 Ok(value)
3994}
3995
3996fn deserialize_opt_positive_usize<'de, D>(deserializer: D) -> Result<Option<usize>, D::Error>
3997where
3998 D: Deserializer<'de>,
3999{
4000 let value = deserialize_opt_positive_u64(deserializer)?;
4001 value
4002 .map(|value| usize::try_from(value).map_err(|_| de::Error::custom("value is too large")))
4003 .transpose()
4004}
4005
4006fn deserialize_opt_timeout_secs<'de, D>(deserializer: D) -> Result<Option<u32>, D::Error>
4007where
4008 D: Deserializer<'de>,
4009{
4010 let value = Option::<u64>::deserialize(deserializer)?;
4011 match value {
4012 Some(value) if !(1..=600).contains(&value) => {
4013 Err(de::Error::custom("timeout must be in 1..=600 seconds"))
4014 }
4015 Some(value) => u32::try_from(value)
4016 .map(Some)
4017 .map_err(|_| de::Error::custom("timeout is too large")),
4018 None => Ok(None),
4019 }
4020}
4021
4022fn deserialize_opt_bridge_request_timeout_ms<'de, D>(
4023 deserializer: D,
4024) -> Result<Option<u64>, D::Error>
4025where
4026 D: Deserializer<'de>,
4027{
4028 let value = Option::<u64>::deserialize(deserializer)?;
4029 match value {
4030 Some(value) if value < 1_000 => Err(de::Error::custom(
4031 "bridge.request_timeout_ms must be at least 1000",
4032 )),
4033 other => Ok(other),
4034 }
4035}
4036
4037fn deserialize_opt_worker_wait_max_ms<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
4038where
4039 D: Deserializer<'de>,
4040{
4041 let value = Option::<u64>::deserialize(deserializer)?;
4042 match value {
4043 Some(value) if value < MIN_BASH_WORKER_WAIT_MAX_MS => Err(de::Error::custom(format!(
4044 "bash.worker_wait_max_ms must be at least {MIN_BASH_WORKER_WAIT_MAX_MS}"
4045 ))),
4046 other => Ok(other),
4047 }
4048}
4049
4050fn deserialize_opt_inspect_categories<'de, D>(
4051 deserializer: D,
4052) -> Result<Option<BTreeMap<String, bool>>, D::Error>
4053where
4054 D: Deserializer<'de>,
4055{
4056 let value = Option::<BTreeMap<String, bool>>::deserialize(deserializer)?;
4057 if let Some(categories) = &value {
4058 if categories
4059 .keys()
4060 .any(|key| !InspectCategories::KEYS.contains(&key.as_str()))
4061 {
4062 return Err(de::Error::custom("unknown inspect category"));
4063 }
4064 }
4065 Ok(value)
4066}
4067
4068#[cfg(test)]
4069mod tests {
4070 #[test]
4071 fn storage_cache_dir_is_a_recognized_user_setting() {
4072 let raw = serde_json::from_str::<super::RawAftConfig>(
4073 r#"{"storage":{"cache_dir":{"kind":"dir","path":"/cache/aft"}}}"#,
4074 );
4075 assert!(raw.is_ok(), "storage.cache_dir must be recognized: {raw:?}");
4076 }
4077
4078 #[test]
4079 fn storage_cache_dir_rejects_malformed_choices() {
4080 for choice in [
4081 r#"{"kind":"other"}"#,
4082 r#"{"kind":"dir"}"#,
4083 r#"{"kind":"main_disk","path":"/unexpected"}"#,
4084 ] {
4085 let candidate = tier(
4086 "user",
4087 &format!(r#"{{"storage":{{"cache_dir":{choice}}}}}"#),
4088 );
4089 assert!(strict_tier_error(&candidate, None).is_some(), "{choice}");
4090 let result = resolve_config(&[candidate]);
4091 assert_eq!(
4092 result.errors,
4093 ["invalid_cache_config: storage.cache_dir"],
4094 "{choice}"
4095 );
4096 assert!(result.config.cache_config_unknown.is_some(), "{choice}");
4097 assert!(!result.config.cache_dir_opt_out, "{choice}");
4098 }
4099 }
4100
4101 #[test]
4102 fn storage_cache_dir_project_and_harness_choices_are_dropped() {
4103 for choice in [
4104 r#"{"kind":"default"}"#,
4105 r#"{"kind":"main_disk"}"#,
4106 r#"{"kind":"dir","path":"~/do-not-use"}"#,
4107 ] {
4108 let storage = format!(r#""storage":{{"cache_dir":{choice}}}"#);
4109 let result = resolve_config_for_harness(
4110 &[
4111 tier(
4112 "user",
4113 &format!(r#"{{"harnesses":{{"pi":{{{storage}}}}}}}"#),
4114 ),
4115 tier("project", &format!(r#"{{{storage}}}"#)),
4116 ],
4117 Some(&Harness::Pi),
4118 );
4119 assert!(result.errors.is_empty(), "{choice}: {:?}", result.errors);
4120 assert!(result.config.cache_dir.is_none());
4121 assert!(!result.config.cache_dir_opt_out);
4122 for tier in ["user", "project"] {
4123 assert!(result
4124 .dropped
4125 .iter()
4126 .any(|drop| drop.tier == tier && drop.key == "storage.cache_dir"));
4127 }
4128 }
4129 }
4130
4131 #[test]
4132 fn memory_config_only_user_base_selects_machine_limits() {
4133 use crate::memory_profile::MemoryMode;
4134 for (name, expected) in [
4135 ("lean", MemoryMode::Lean),
4136 ("balanced", MemoryMode::Balanced),
4137 ] {
4138 for harness in [Harness::Pi, Harness::Opencode] {
4139 let result = resolve_config_for_harness(
4140 &[
4141 tier(
4142 "user",
4143 &format!(
4144 r#"{{"memory":"{name}","harnesses":{{"pi":{{"memory":{{}},"sandbox":{{"profile":{{"worker":"strict"}}}}}},"opencode":{{"memory":null,"sandbox":{{"profile":{{"worker":"strict"}}}}}}}}}}"#
4145 ),
4146 ),
4147 tier(
4148 "project",
4149 r#"{"memory":5,"harnesses":{"pi":{"memory":"fast"},"opencode":{"memory":"lean"}}}"#,
4150 ),
4151 ],
4152 Some(&harness),
4153 );
4154 assert!(result.errors.is_empty(), "{:?}", result.errors);
4155 assert_eq!(result.config.memory, Some(expected));
4156 assert!(result
4157 .dropped
4158 .iter()
4159 .any(|drop| drop.key == "memory" && drop.tier == "user"));
4160 assert!(result
4161 .dropped
4162 .iter()
4163 .any(|drop| drop.key == "memory" && drop.tier == "project"));
4164 }
4165 }
4166 let project = resolve_config(&[tier("project", r#"{"memory":"lean"}"#)]);
4167 assert!(project.errors.is_empty());
4168 assert_eq!(project.config.memory, None);
4169 }
4170
4171 #[test]
4172 fn storage_cache_dir_only_user_base_can_select_storage_wide_root() {
4173 let result = super::resolve_config_for_harness(&[
4174 super::ConfigTier { tier: "user".into(), source: "user".into(), doc: r#"{"storage":{"cache_dir":"/cache/base"},"harnesses":{"pi":{"storage":{"cache_dir":"/cache/pi"}}}}"#.into() },
4175 super::ConfigTier { tier: "project".into(), source: "project".into(), doc: r#"{"storage":{"cache_dir":"/evil"},"harnesses":{"pi":{"storage":{"cache_dir":"/evil/pi"}}}}"#.into() },
4176 ], Some(&crate::harness::Harness::Pi));
4177 assert!(result.errors.is_empty());
4178 assert_eq!(
4179 result.config.cache_dir,
4180 Some(std::path::PathBuf::from("/cache/base"))
4181 );
4182 assert!(result
4183 .dropped
4184 .iter()
4185 .any(|dropped| dropped.key == "storage.cache_dir"));
4186 }
4187
4188 #[test]
4189 fn cache_dir_and_bash_env_keep_distinct_harness_trust_rules() {
4190 for harness in [
4196 crate::harness::Harness::Opencode,
4197 crate::harness::Harness::Pi,
4198 ] {
4199 let result = super::resolve_config_for_harness(
4200 &[
4201 tier(
4202 "user",
4203 r#"{
4204 "storage":{"cache_dir":"/cache/base"},
4205 "bash":{"env":{"TZ":"UTC"}},
4206 "harnesses":{
4207 "opencode":{"storage":{"cache_dir":"/cache/override"},"bash":{"env":{"TZ":"Etc/GMT"}}},
4208 "pi":{"storage":{"cache_dir":"/cache/override"},"bash":{"env":{"TZ":"Etc/GMT"}}}
4209 }
4210 }"#,
4211 ),
4212 tier(
4213 "project",
4214 r#"{
4215 "storage":{"cache_dir":"/evil"},
4216 "bash":{"env":{"PROJECT_MARKER":"/evil/marker"}},
4217 "harnesses":{
4218 "opencode":{"storage":{"cache_dir":"/evil/override"},"bash":{"env":{"TZ":"project"}}},
4219 "pi":{"storage":{"cache_dir":"/evil/override"},"bash":{"env":{"TZ":"project"}}}
4220 }
4221 }"#,
4222 ),
4223 ],
4224 Some(&harness),
4225 );
4226 assert!(result.errors.is_empty(), "{:?}", result.errors);
4227 assert_eq!(result.config.cache_dir, Some("/cache/base".into()));
4229 assert!(result
4230 .dropped
4231 .iter()
4232 .any(|drop| drop.key == "storage.cache_dir" && drop.tier == "user"));
4233 assert!(result
4234 .dropped
4235 .iter()
4236 .any(|drop| drop.key == "storage.cache_dir" && drop.tier == "project"));
4237 assert_eq!(result.config.bash.env.len(), 1);
4239 assert_eq!(result.config.bash.env["TZ"], "Etc/GMT");
4240 assert_eq!(
4243 result.config.bash.project_env.get("TZ").map(String::as_str),
4244 Some("project")
4245 );
4246 assert!(result
4247 .config
4248 .bash
4249 .project_env
4250 .contains_key("PROJECT_MARKER"));
4251 assert!(!result.dropped.iter().any(|drop| drop.key == "bash.env"));
4252 }
4253 }
4254
4255 #[test]
4256 fn cache_dir_stays_fenced_when_bash_env_rejects_the_user_config() {
4257 for in_harness in [false, true] {
4258 let mut document = serde_json::json!({"storage":{"cache_dir":"/cache/base"}});
4259 let blocked = serde_json::json!({"env":{"BASH_ENV":"/evil/startup"}});
4260 if in_harness {
4261 document["harnesses"] = serde_json::json!({"pi":{"bash":blocked}});
4262 } else {
4263 document["bash"] = blocked;
4264 }
4265 let result = super::resolve_config_for_harness(
4266 &[tier("user", &document.to_string())],
4267 Some(&crate::harness::Harness::Pi),
4268 );
4269 assert!(result
4270 .errors
4271 .iter()
4272 .any(|error| error.contains("blocked bash.env key BASH_ENV")));
4273 assert_eq!(result.config.cache_dir, Some("/cache/base".into()));
4274 assert!(result.config.cache_config_unknown.is_some());
4275 assert!(result.config.bash.env.is_empty());
4276 }
4277 }
4278
4279 #[test]
4280 fn storage_cache_dir_relative_stays_unavailable_without_redirecting() {
4281 let result = super::resolve_config(&[super::ConfigTier {
4282 tier: "user".into(),
4283 source: "user".into(),
4284 doc: r#"{"storage":{"cache_dir":{"kind":"dir","path":"relative"}}}"#.into(),
4285 }]);
4286 assert_eq!(
4287 result.config.cache_dir,
4288 Some(std::path::PathBuf::from("relative"))
4289 );
4290 assert!(result.config.cache_unavailable.is_some());
4291 assert!(result
4292 .warnings
4293 .iter()
4294 .any(|warning| warning.code == "cache_dir_unavailable"
4295 && warning
4296 .message
4297 .contains("AFT is running without its caches until it is back.")));
4298 }
4299
4300 #[test]
4301 fn storage_cache_dir_expands_tilde_before_absolute_validation() {
4302 let home = std::env::var_os("HOME")
4303 .or_else(|| std::env::var_os("USERPROFILE"))
4304 .map(std::path::PathBuf::from)
4305 .unwrap();
4306 let result = super::resolve_config(&[super::ConfigTier {
4307 tier: "user".into(),
4308 source: "user".into(),
4309 doc: r#"{"storage":{"cache_dir":"~/aft-cache"}}"#.into(),
4310 }]);
4311 assert_eq!(result.config.cache_dir, Some(home.join("aft-cache")));
4312 assert!(!result
4313 .warnings
4314 .iter()
4315 .any(|warning| warning.code == "cache_dir_unavailable"));
4316 }
4317 use super::*;
4318
4319 #[test]
4320 fn harness_ignored_keys_match_plugin_declarations() {
4321 let source = include_str!("../../../packages/aft-bridge/src/config-keys.ts");
4322 let declared = |name: &str| -> Vec<String> {
4323 let prefix = format!("export const {name} = [");
4324 let body = source
4325 .split_once(&prefix)
4326 .expect("host key declaration")
4327 .1
4328 .split_once(']')
4329 .expect("host key list end")
4330 .0;
4331 body.split(',')
4332 .map(str::trim)
4333 .filter(|entry| !entry.is_empty())
4334 .map(|entry| serde_json::from_str(entry).expect("literal host key"))
4335 .collect()
4336 };
4337 for (harness, name) in [
4338 (Harness::Pi, "OPENCODE_ONLY_KEYS"),
4339 (Harness::Opencode, "PI_ONLY_KEYS"),
4340 ] {
4341 assert_eq!(declared(name), harness_ignored_config_keys(Some(&harness)));
4342 }
4343 assert!(harness_ignored_config_keys(None).is_empty());
4344 assert!(harness_ignored_config_keys(Some(&Harness::Runner)).is_empty());
4345 }
4346
4347 #[test]
4348 fn pi_ignored_keys_do_not_discard_active_harness_hardening() {
4349 for tier_name in ["user", "project"] {
4350 for ignored in [
4351 serde_json::json!("opaque"),
4352 Value::Null,
4353 serde_json::json!(false),
4354 serde_json::json!({"unexpected": true}),
4355 ] {
4356 let input = tier(
4357 tier_name,
4358 &serde_json::json!({"harnesses":{"pi":{
4359 "auto_update": ignored,
4360 "sandbox":{"profile":{"worker":"strict"}}
4361 }}})
4362 .to_string(),
4363 );
4364 let resolved =
4365 resolve_config_for_harness(std::slice::from_ref(&input), Some(&Harness::Pi));
4366 assert!(resolved.errors.is_empty(), "{:?}", resolved.errors);
4367 assert_eq!(
4368 resolved.config.sandbox.profile.worker,
4369 crate::config::SandboxMode::Strict
4370 );
4371 assert!(strict_tier_error(&input, Some(&Harness::Pi)).is_none());
4372 assert!(!resolved
4373 .warnings
4374 .iter()
4375 .any(|warning| warning.code == "invalid_harness_override"));
4376 let (raw, _) =
4377 parse_tier(&input, Some(&Harness::Pi), &mut Vec::new(), &mut Vec::new())
4378 .unwrap();
4379 assert!(raw.harnesses.unwrap()["pi"].get("auto_update").is_none());
4380 }
4381 }
4382 }
4383
4384 #[test]
4385 fn pi_ignored_keys_do_not_reject_root_hardening_on_reload() {
4386 for tier_name in ["user", "project"] {
4387 for ignored in [
4388 serde_json::json!("opaque"),
4389 Value::Null,
4390 serde_json::json!(false),
4391 serde_json::json!({"unexpected": true}),
4392 ] {
4393 let input = tier(
4394 tier_name,
4395 &serde_json::json!({
4396 "auto_update": ignored,
4397 "sandbox":{"profile":{"worker":"strict"}}
4398 })
4399 .to_string(),
4400 );
4401 let resolved =
4402 resolve_config_for_harness(std::slice::from_ref(&input), Some(&Harness::Pi));
4403 assert!(resolved.errors.is_empty(), "{:?}", resolved.errors);
4404 assert_eq!(
4405 resolved.config.sandbox.profile.worker,
4406 crate::config::SandboxMode::Strict
4407 );
4408 assert!(strict_tier_error(&input, Some(&Harness::Pi)).is_none());
4409 let (raw, _) =
4410 parse_tier(&input, Some(&Harness::Pi), &mut Vec::new(), &mut Vec::new())
4411 .unwrap();
4412 assert_eq!(raw.auto_update, None);
4413 }
4414 }
4415 }
4416
4417 #[test]
4418 fn opencode_owned_auto_update_remains_security_validated() {
4419 let valid = tier("user", r#"{"auto_update":false}"#);
4420 let (raw, _) = parse_tier(
4421 &valid,
4422 Some(&Harness::Opencode),
4423 &mut Vec::new(),
4424 &mut Vec::new(),
4425 )
4426 .unwrap();
4427 assert_eq!(raw.auto_update, Some(false));
4428 for tier_name in ["user", "project"] {
4429 let root = tier(
4430 tier_name,
4431 r#"{"auto_update":"opaque","sandbox":{"profile":{"worker":"strict"}}}"#,
4432 );
4433 let active = tier(
4434 tier_name,
4435 r#"{"harnesses":{"opencode":{"auto_update":"opaque","sandbox":{"profile":{"worker":"strict"}}}}}"#,
4436 );
4437 assert_eq!(
4438 resolve_config_for_harness(&[root], Some(&Harness::Opencode)).errors,
4439 ["invalid_security_config:auto_update"]
4440 );
4441 assert_eq!(
4442 resolve_config_for_harness(&[active], Some(&Harness::Opencode)).errors,
4443 ["invalid_security_config:harnesses.opencode.auto_update"]
4444 );
4445 }
4446 }
4447
4448 #[test]
4449 fn discarded_nonsecurity_sections_are_named_without_rejecting_valid_settings() {
4450 let result = resolve_config(&[tier(
4451 "user",
4452 r#"{"inspect":{"categories":{"diagnostics":"off"}},"format_on_edit":true}"#,
4453 )]);
4454 assert!(result.errors.is_empty());
4455 assert!(result.config.format_on_edit);
4456 assert!(result
4457 .warnings
4458 .iter()
4459 .any(|warning| warning.code == "invalid_config_section"
4460 && warning.message == "Discarded invalid configuration section: inspect"));
4461 }
4462
4463 #[test]
4464 fn malformed_active_harness_hardening_rejects_but_inactive_blocks_stay_opaque() {
4465 let tier = tier(
4466 "user",
4467 r#"{"harnesses":{"opencode":{"sandbox":{"profile":{"worker":5}}},"pi":{"sandbox":{"profile":{"worker":"strict"}}}}}"#,
4468 );
4469 let rejected =
4470 resolve_config_for_harness(std::slice::from_ref(&tier), Some(&Harness::Opencode));
4471 assert_eq!(
4472 rejected.errors,
4473 ["invalid_security_config:harnesses.opencode.sandbox"]
4474 );
4475 let accepted = resolve_config_for_harness(&[tier], Some(&Harness::Pi));
4476 assert!(accepted.errors.is_empty());
4477 assert_eq!(
4478 accepted.config.sandbox.profile.worker,
4479 crate::config::SandboxMode::Strict
4480 );
4481 }
4482
4483 #[test]
4484 fn malformed_security_sections_reject_candidate_without_resetting_last_good() {
4485 for (key, value) in [
4486 ("sandbox", serde_json::json!({"profile": {"worker": 5}})),
4487 ("indexes", serde_json::json!({"semantic":"off"})),
4488 ("remote_exec", serde_json::json!({"enabled":"off"})),
4489 ("disabled_tools", serde_json::json!("aft_write")),
4490 ("restrict_to_project_root", serde_json::json!(1)),
4491 ] {
4492 let tier = ConfigTier {
4493 tier: "user".into(),
4494 source: "malformed-security.jsonc".into(),
4495 doc: serde_json::json!({key:value, "format_on_edit":true}).to_string(),
4496 };
4497 let mut last_good = Config {
4498 restrict_to_project_root: true,
4499 ..Config::default()
4500 };
4501 let before = serde_json::to_value(&last_good).unwrap();
4502 let diagnostics = resolve_config_onto_with_diagnostics(&[tier], &mut last_good);
4503 assert_eq!(
4504 diagnostics.errors,
4505 [format!("invalid_security_config:{key}")]
4506 );
4507 assert_eq!(
4508 serde_json::to_value(&last_good).unwrap(),
4509 before,
4510 "rejected {key} must not reset published hardening"
4511 );
4512 }
4513 }
4514
4515 #[test]
4516 fn unreadable_tier_document_does_not_silently_publish_defaults() {
4517 let tier = ConfigTier {
4518 tier: "user".into(),
4519 source: "broken.jsonc".into(),
4520 doc: "{".into(),
4521 };
4522 assert_eq!(resolve_config(&[tier]).errors, ["invalid_config_document"]);
4523 }
4524
4525 #[test]
4526 fn malformed_security_root_and_active_harness_sections_fail_closed() {
4527 for key in [
4528 "restrict_to_project_root",
4529 "url_fetch_allow_private",
4530 "sandbox",
4531 "indexes",
4532 "index",
4533 "remote_exec",
4534 "disabled_tools",
4535 "bash",
4536 "lsp",
4537 "semantic",
4538 "search",
4539 "subc",
4540 "opencode",
4541 "github",
4542 "gh_shim",
4543 "auto_update",
4544 ] {
4545 let root = tier("user", &serde_json::json!({key: null}).to_string());
4546 assert_eq!(
4547 resolve_config_for_harness(&[root], Some(&Harness::Opencode)).errors,
4548 [format!("invalid_security_config:{key}")]
4549 );
4550 let active = tier(
4551 "project",
4552 &serde_json::json!({"harnesses": {"opencode": {key: null}}}).to_string(),
4553 );
4554 assert_eq!(
4555 resolve_config_for_harness(&[active], Some(&Harness::Opencode)).errors,
4556 [format!("invalid_security_config:harnesses.opencode.{key}")]
4557 );
4558 }
4559 let mixed = tier(
4560 "user",
4561 r#"{"harnesses":{"opencode":{"sandbox":{"profile":{"worker":"strict"}},"inspect":false}}}"#,
4562 );
4563 assert_eq!(
4564 resolve_config_for_harness(&[mixed], Some(&Harness::Opencode)).errors,
4565 ["invalid_security_config:harnesses.opencode"]
4566 );
4567 let pi = tier("user", r#"{"auto_update":"opaque"}"#);
4568 assert!(resolve_config_for_harness(&[pi], Some(&Harness::Pi))
4569 .errors
4570 .is_empty());
4571 for doc in ["null", "[]", "false", "1"] {
4572 assert_eq!(
4573 resolve_config(&[tier("project", doc)]).errors,
4574 ["invalid_config_document"]
4575 );
4576 }
4577 }
4578
4579 #[test]
4580 fn project_merge_moves_owned_semantic_section_without_cloning() {
4581 let mut base: RawAftConfig = serde_json::from_value(serde_json::json!({
4582 "semantic": {"model": "owned-user-model"}
4583 }))
4584 .unwrap();
4585 let model_allocation = base
4586 .semantic
4587 .as_ref()
4588 .unwrap()
4589 .model
4590 .as_ref()
4591 .unwrap()
4592 .as_ptr();
4593 merge_project_config(&mut base, RawAftConfig::default());
4594 assert_eq!(
4595 base.semantic
4596 .as_ref()
4597 .unwrap()
4598 .model
4599 .as_ref()
4600 .unwrap()
4601 .as_ptr(),
4602 model_allocation,
4603 "an unspecified project override must retain the owned model allocation"
4604 );
4605 }
4606
4607 #[test]
4608 fn lsp_idle_default_and_project_tightening() {
4609 let default = resolve_config(&[]).config;
4610 assert_eq!(default.lsp_idle_minutes, 60);
4611 assert!(default.lsp_idle_shutdown);
4612 for (user, project, minutes, shutdown, refused) in [
4613 (
4614 r#"{"idle_minutes":60}"#,
4615 r#"{"idle_minutes":30}"#,
4616 30,
4617 true,
4618 None,
4619 ),
4620 (
4621 r#"{"idle_minutes":30}"#,
4622 r#"{"idle_minutes":60}"#,
4623 30,
4624 true,
4625 Some("lsp.idle_minutes"),
4626 ),
4627 (
4628 r#"{"idle_shutdown":true}"#,
4629 r#"{"idle_minutes":"never"}"#,
4630 60,
4631 true,
4632 Some("lsp.idle_shutdown"),
4633 ),
4634 (
4635 r#"{"idle_minutes":30,"idle_shutdown":false}"#,
4636 r#"{"idle_shutdown":true}"#,
4637 30,
4638 true,
4639 None,
4640 ),
4641 (
4642 r#"{"idle_minutes":"never"}"#,
4643 r#"{"idle_minutes":30,"idle_shutdown":false}"#,
4644 30,
4645 false,
4646 None,
4647 ),
4648 ] {
4649 let result = resolve_config(&[
4650 tier("user", &format!(r#"{{"lsp":{user}}}"#)),
4651 tier("project", &format!(r#"{{"lsp":{project}}}"#)),
4652 ]);
4653 assert!(result.errors.is_empty(), "{:?}", result.errors);
4654 assert_eq!(result.config.lsp_idle_minutes, minutes);
4655 assert_eq!(result.config.lsp_idle_shutdown, shutdown);
4656 assert_eq!(drop_keys(&result).first().map(String::as_str), refused);
4657 }
4658 }
4659
4660 #[test]
4661 fn settings_shapes_preserve_legacy_true_in_harness_and_reject_explicit_null() {
4662 let harness = resolve_config_for_harness(
4663 &[tier(
4664 "user",
4665 r#"{"bash":{"enabled":false,"rewrite":false,"compress":false,"background":false},"harnesses":{"pi":{"bash":true}}}"#,
4666 )],
4667 Some(&Harness::Pi),
4668 );
4669 assert!(harness.errors.is_empty());
4670 assert!(harness.config.bash.enabled);
4671 assert!(harness.config.experimental_bash_rewrite);
4672 assert!(harness.config.experimental_bash_compress);
4673 assert!(harness.config.experimental_bash_background);
4674
4675 for (document, path) in [
4676 (r#"{"lsp":{"idle_minutes":null}}"#, "lsp.idle_minutes"),
4677 (r#"{"lsp":{"idle_shutdown":null}}"#, "lsp.idle_shutdown"),
4678 (
4679 r#"{"bash":{"memory_limit_mib":null}}"#,
4680 "bash.memory_limit_mib",
4681 ),
4682 (
4683 r#"{"lsp":{"servers":{"rust":{"initialization_options":null}}}}"#,
4684 "lsp.servers.rust.initialization_options",
4685 ),
4686 (
4687 r#"{"inspect":{"duplicates":{"expected_mirrors":null}}}"#,
4688 "inspect.duplicates.expected_mirrors",
4689 ),
4690 (
4691 r#"{"harnesses":{"pi":{"format_on_edit":null}}}"#,
4692 "harnesses.pi.format_on_edit",
4693 ),
4694 ] {
4695 let candidate = tier("user", document);
4696 let expected = format!("invalid_config_null:{path}");
4697 assert_eq!(
4698 strict_tier_error(&candidate, Some(&Harness::Pi)),
4699 Some(expected.clone())
4700 );
4701 assert_eq!(
4702 resolve_config_for_harness(&[candidate], Some(&Harness::Pi)).errors,
4703 [expected]
4704 );
4705 }
4706 let opt_out = resolve_config(&[tier("user", r#"{"storage":{"cache_dir":null}}"#)]);
4707 assert!(opt_out.errors.is_empty());
4708 assert!(opt_out.config.cache_dir_opt_out);
4709 }
4710
4711 #[test]
4712 fn lsp_max_servers_defaults_and_project_can_only_lower() {
4713 assert_eq!(resolve_config(&[]).config.lsp_max_servers, 8);
4714 for (user, project, expected, refused) in [
4715 (8, 3, 3, false),
4716 (3, 8, 3, true),
4717 (8, 0, 0, false),
4718 (16, 12, 12, false),
4719 ] {
4720 let result = resolve_config(&[
4721 tier("user", &format!(r#"{{"lsp":{{"max_servers":{user}}}}}"#)),
4722 tier(
4723 "project",
4724 &format!(r#"{{"lsp":{{"max_servers":{project}}}}}"#),
4725 ),
4726 ]);
4727 assert!(result.errors.is_empty(), "{:?}", result.errors);
4728 assert_eq!(result.config.lsp_max_servers, expected);
4729 assert_eq!(result.config.lsp_user_max_servers, Some(user));
4730 assert_eq!(
4731 drop_keys(&result).contains(&"lsp.max_servers".to_string()),
4732 refused
4733 );
4734 }
4735 let result = resolve_config(&[tier("project", r#"{"lsp":{"max_servers":23}}"#)]);
4736 assert_eq!(result.config.lsp_max_servers, 8);
4737 assert!(drop_keys(&result).contains(&"lsp.max_servers".to_string()));
4738 }
4739
4740 #[test]
4741 fn inspect_categories_project_can_only_disable() {
4742 let result = resolve_config(&[
4743 tier(
4744 "user",
4745 r#"{"inspect":{"categories":{"dead_code":false,"todos":true}}}"#,
4746 ),
4747 tier(
4748 "project",
4749 r#"{"inspect":{"categories":{"dead_code":true,"todos":false}}}"#,
4750 ),
4751 ]);
4752 assert!(result.errors.is_empty(), "{:?}", result.errors);
4753 let config = serde_json::to_value(&result.config).unwrap();
4754 assert_eq!(config["inspect"]["categories"]["dead_code"], false);
4755 assert_eq!(config["inspect"]["categories"]["todos"], false);
4756 assert_eq!(config["inspect"]["categories"]["diagnostics"], true);
4757 assert!(drop_keys(&result).contains(&"inspect.categories.dead_code".to_string()));
4758 }
4759
4760 fn refused_retired_documents() -> Vec<(&'static str, Value)> {
4764 let mut documents = vec![
4765 (
4766 "sandbox.enabled",
4767 serde_json::json!({"sandbox": {"enabled": true}}),
4768 ),
4769 (
4770 "tool_surface",
4771 serde_json::json!({"tool_surface": "minimal"}),
4772 ),
4773 (
4774 "hoist_builtin_tools",
4775 serde_json::json!({"hoist_builtin_tools": false}),
4776 ),
4777 ("enabled", serde_json::json!({"enabled": false})),
4778 ("search_index", serde_json::json!({"search_index": false})),
4779 (
4780 "experimental_search_index",
4781 serde_json::json!({"experimental_search_index": false}),
4782 ),
4783 (
4784 "semantic_search",
4785 serde_json::json!({"semantic_search": false}),
4786 ),
4787 (
4788 "experimental_semantic_search",
4789 serde_json::json!({"experimental_semantic_search": false}),
4790 ),
4791 (
4792 "callgraph_store",
4793 serde_json::json!({"callgraph_store": false}),
4794 ),
4795 (
4796 "github.enabled",
4797 serde_json::json!({"github": {"enabled": false}}),
4798 ),
4799 ("gh_read", serde_json::json!({"gh_read": {"enabled": true}})),
4800 (
4801 "gh_shim.enabled",
4802 serde_json::json!({"gh_shim": {"enabled": false, "binary_path": "/opt/aft/bin/aft"}}),
4803 ),
4804 (
4805 "experimental_lsp_ty",
4806 serde_json::json!({"experimental_lsp_ty": true}),
4807 ),
4808 (
4809 "experimental_bash_rewrite",
4810 serde_json::json!({"experimental_bash_rewrite": true}),
4811 ),
4812 (
4813 "experimental_bash_compress",
4814 serde_json::json!({"experimental_bash_compress": true}),
4815 ),
4816 (
4817 "experimental_bash_background",
4818 serde_json::json!({"experimental_bash_background": true}),
4819 ),
4820 (
4821 "experimental.bash",
4822 serde_json::json!({"experimental": {"bash": {"background": true}}}),
4823 ),
4824 (
4825 "experimental.bash",
4826 serde_json::json!({"experimental": {"bash": {"long_running_reminder_interval_ms": 5000}}}),
4827 ),
4828 (
4829 "idle.lsp_ttl_minutes",
4830 serde_json::json!({"idle": {"lsp_ttl_minutes": 10}}),
4831 ),
4832 (
4833 "inspect.tier2_soft_deadline_ms",
4834 serde_json::json!({"inspect": {"tier2_soft_deadline_ms": 50}}),
4835 ),
4836 (
4837 "inspect.max_drill_down_items",
4838 serde_json::json!({"inspect": {"max_drill_down_items": 20}}),
4839 ),
4840 (
4841 "views.enabled",
4842 serde_json::json!({"views": {"enabled": true}}),
4843 ),
4844 (
4845 "views.callgraph_copies",
4846 serde_json::json!({"views": {"callgraph_copies": 2}}),
4847 ),
4848 (
4849 "worktree.ram_overlay",
4850 serde_json::json!({"worktree": {"ram_overlay": false}}),
4851 ),
4852 ];
4853 for (alias, _) in feature_config::LEGACY_TOOL_ALIASES {
4854 documents.push((alias, serde_json::json!({"disabled_tools": [alias]})));
4855 }
4856 documents
4857 }
4858
4859 #[test]
4865 fn refused_retired_user_keys_are_refused_and_doctor_fix_repairs_them() {
4866 let documents = refused_retired_documents();
4867 let listed: std::collections::BTreeSet<&str> =
4868 documents.iter().map(|(name, _)| *name).collect();
4869 for path in feature_config::REFUSED_RETIRED_PATHS {
4870 assert!(listed.contains(path), "{path} has no refusal case");
4871 }
4872 for (name, document) in documents {
4873 for (prefix, document) in [
4874 ("", document.clone()),
4875 (
4876 "harnesses.pi.",
4877 serde_json::json!({"harnesses": {"pi": document}}),
4878 ),
4879 ] {
4880 let text = document.to_string();
4881 for tier_name in ["user", "project"] {
4882 let resolved =
4883 resolve_config_for_harness(&[tier(tier_name, &text)], Some(&Harness::Pi));
4884 if tier_name == "user" {
4885 assert_eq!(
4886 resolved.errors,
4887 [format!(
4888 "removed_config_key:{prefix}{name}; run npx @cortexkit/aft doctor --fix"
4889 )],
4890 "{tier_name}: {text}"
4891 );
4892 assert!(
4893 strict_tier_error(&tier(tier_name, &text), Some(&Harness::Pi))
4894 .is_some_and(|error| error.contains("removed_config_key:")),
4895 "{tier_name}: {text}"
4896 );
4897 } else {
4898 assert!(
4899 resolved.errors.is_empty(),
4900 "a project config loads: {text}: {:?}",
4901 resolved.errors
4902 );
4903 assert_eq!(
4904 strict_tier_error(&tier(tier_name, &text), Some(&Harness::Pi)),
4905 None,
4906 "{tier_name}: {text}"
4907 );
4908 }
4909
4910 let fix_tier = if tier_name == "user" {
4911 crate::config_fix::FixTier::User
4912 } else {
4913 crate::config_fix::FixTier::Project
4914 };
4915 let fixed = crate::config_fix::migrate_config_text(&text, fix_tier)
4916 .expect("doctor --fix rewrites the file");
4917 assert!(fixed.changed, "{tier_name}: {text}");
4918 let repaired = resolve_config_for_harness(
4919 &[tier(tier_name, &fixed.text)],
4920 Some(&Harness::Pi),
4921 );
4922 assert!(
4923 repaired.errors.is_empty(),
4924 "{tier_name}: {text} -> {}: {:?}",
4925 fixed.text,
4926 repaired.errors
4927 );
4928 if tier_name == "project" {
4929 assert_eq!(
4932 serde_json::to_value(&resolved.config).unwrap(),
4933 serde_json::to_value(&repaired.config).unwrap(),
4934 "{text} -> {}",
4935 fixed.text
4936 );
4937 }
4938 }
4939 }
4940 }
4941 }
4942
4943 #[test]
4946 fn doctor_fix_carries_refused_values_to_their_replacements() {
4947 let fixed = |text: &str| {
4948 let text =
4949 crate::config_fix::migrate_config_text(text, crate::config_fix::FixTier::User)
4950 .unwrap()
4951 .text;
4952 let result = resolve_config(&[tier("user", &text)]);
4953 assert!(result.errors.is_empty(), "{text}: {:?}", result.errors);
4954 result.config
4955 };
4956 let minutes =
4957 |config: &Config| serde_json::to_value(config).unwrap()["lsp_idle_minutes"].clone();
4958 assert_eq!(minutes(&fixed(r#"{"idle":{"lsp_ttl_minutes":10}}"#)), 10);
4959 assert!(!fixed(r#"{"search_index":false}"#).indexes.trigram);
4960 let reminder =
4961 fixed(r#"{"experimental":{"bash":{"long_running_reminder_interval_ms":5000}}}"#);
4962 assert_eq!(reminder.bash_long_running_reminder_interval_ms, 5000);
4963 assert!(
4964 reminder.experimental_bash_rewrite,
4965 "the flags keep their defaults"
4966 );
4967 let background = fixed(r#"{"experimental":{"bash":{"background":true}}}"#);
4968 assert!(background.experimental_bash_background);
4969 assert!(!background.experimental_bash_rewrite);
4970 assert!(!background.experimental_bash_compress);
4971 let disabled = fixed(r#"{"disabled_tools":["aft_read"]}"#);
4972 assert_eq!(disabled.disabled_tools, ["read"]);
4973 }
4974
4975 #[test]
4978 fn names_retired_in_the_last_two_releases_still_translate() {
4979 let _release = feature_config::override_running_release_for_test((0, 64));
4980 for tier_name in ["user", "project"] {
4981 let hang = resolve_config(&[tier(tier_name, r#"{"bridge":{"hang_threshold":2}}"#)]);
4982 assert!(hang.errors.is_empty(), "{tier_name}: {:?}", hang.errors);
4983 let checkout =
4984 resolve_config(&[tier(tier_name, r#"{"views":{"idle_checkout_hours":72}}"#)]);
4985 assert!(
4986 checkout.errors.is_empty(),
4987 "{tier_name}: {:?}",
4988 checkout.errors
4989 );
4990 assert_eq!(checkout.config.idle.checkout_hours, 72);
4991 }
4992 }
4993
4994 fn tier(tier: &str, doc: &str) -> ConfigTier {
4995 ConfigTier {
4996 tier: tier.to_string(),
4997 source: format!("/tmp/{tier}/aft.jsonc"),
4998 doc: doc.to_string(),
4999 }
5000 }
5001
5002 fn drop_keys(result: &ResolveResult) -> Vec<String> {
5003 result
5004 .dropped
5005 .iter()
5006 .map(|dropped| dropped.key.clone())
5007 .collect()
5008 }
5009
5010 #[test]
5012 fn a_project_may_turn_rerank_off() {
5013 let result = resolve_config(&[
5014 tier(
5015 "user",
5016 r#"{"search": {"rerank": {"backend": "onnx", "model": "bge-reranker-base", "top_n": 15}}}"#,
5017 ),
5018 tier("project", r#"{"search": {"rerank": {"backend": "off"}}}"#),
5019 ]);
5020 assert!(result.errors.is_empty(), "{:?}", result.errors);
5021 assert!(drop_keys(&result).is_empty(), "{:?}", result.dropped);
5022 let rerank = result.config.search.rerank.expect("rerank block");
5023 assert_eq!(rerank.backend, Some(RerankBackendKind::Off));
5024 assert_eq!(rerank.model.as_deref(), Some("bge-reranker-base"));
5026 assert_eq!(rerank.top_n, Some(15));
5027 }
5028
5029 #[test]
5032 fn project_rerank_overrides_other_than_off_are_dropped_and_reported() {
5033 let project = r#"{"search": {"rerank": {
5034 "backend": "remote",
5035 "model": "evil-model",
5036 "endpoint": "https://evil.example.test/rerank",
5037 "api_key_env": "EVIL_KEY",
5038 "top_n": 200,
5039 "timeout_ms": 60000
5040 }}}"#;
5041 for user in [
5042 None,
5043 Some(r#"{"search": {"rerank": {"backend": "onnx", "timeout_ms": 800}}}"#),
5044 ] {
5045 let mut tiers = Vec::new();
5046 if let Some(user) = user {
5047 tiers.push(tier("user", user));
5048 }
5049 tiers.push(tier("project", project));
5050 let result = resolve_config(&tiers);
5051 assert!(result.errors.is_empty(), "{:?}", result.errors);
5052 assert_eq!(
5053 drop_keys(&result),
5054 [
5055 "search.rerank.backend",
5056 "search.rerank.model",
5057 "search.rerank.endpoint",
5058 "search.rerank.api_key_env",
5059 "search.rerank.top_n",
5060 "search.rerank.timeout_ms",
5061 ]
5062 );
5063 assert!(result.dropped.iter().all(
5064 |dropped| dropped.reason == RERANK_PROJECT_REASON && dropped.tier == "project"
5065 ));
5066 match user {
5067 None => assert_eq!(result.config.search, SearchConfig::default()),
5068 Some(_) => assert_eq!(
5069 result.config.search.rerank,
5070 Some(RerankConfig {
5071 backend: Some(RerankBackendKind::Onnx),
5072 timeout_ms: Some(800),
5073 ..RerankConfig::default()
5074 })
5075 ),
5076 }
5077 }
5078 }
5079
5080 #[test]
5082 fn a_project_harness_block_cannot_enable_rerank() {
5083 let result = resolve_config_for_harness(
5084 &[tier(
5085 "project",
5086 r#"{"harnesses": {"opencode": {"search": {"rerank": {"backend": "onnx"}}}}}"#,
5087 )],
5088 Some(&Harness::Opencode),
5089 );
5090 assert_eq!(drop_keys(&result), ["search.rerank.backend"]);
5091 assert_eq!(result.config.search, SearchConfig::default());
5092 }
5093
5094 #[test]
5095 fn a_superseded_legacy_note_is_logged_once_per_file_and_text() {
5096 let source = "/tmp/superseded-note-test/aft.jsonc";
5097 assert!(first_superseded_note(source, "base", "note"));
5098 assert!(!first_superseded_note(source, "base", "note"));
5099 assert!(first_superseded_note(source, "base", "changed note"));
5100 assert!(first_superseded_note(
5101 "/tmp/other/aft.jsonc",
5102 "base",
5103 "note"
5104 ));
5105 }
5106
5107 #[test]
5111 fn project_legacy_keys_do_not_reapply_the_default_disables() {
5112 for project in [r#"{"backup": {"enabled": false}}"#, r#"{"bash": false}"#] {
5113 let result = resolve_config_for_harness(
5114 &[
5115 tier("user", r#"{"disabled_tools": []}"#),
5116 tier("project", project),
5117 ],
5118 None,
5119 );
5120 assert!(result.errors.is_empty());
5121 for kept in ["aft_move", "aft_delete"] {
5122 assert!(
5123 !result.config.disabled_tools.iter().any(|name| name == kept),
5124 "{project}: {kept}"
5125 );
5126 }
5127 }
5128 }
5129
5130 #[test]
5137 fn nested_unknown_keys_are_stripped_but_top_level_privileged_keys_cannot_smuggle() {
5138 let nested = resolve_config(&[tier(
5142 "user",
5143 r#"{ "disabled_tools": [], "bash": { "unknown_key": true } }"#,
5144 )]);
5145 assert!(nested.config.experimental_bash_rewrite);
5146 assert!(nested.config.experimental_bash_compress);
5147 assert!(nested.config.experimental_bash_background);
5148
5149 let smuggle = resolve_config(&[
5153 tier("user", r#"{ "indexes": { "trigram": true } }"#),
5154 tier(
5155 "project",
5156 r#"{ "storage_dir": "/tmp/evil", "bash_permissions": true, "indexes": { "trigram": false } }"#,
5157 ),
5158 ]);
5159 assert!(!smuggle.config.indexes.trigram);
5161 assert!(smuggle.config.storage_dir.is_none());
5163 assert!(!smuggle.config.bash_permissions);
5164 }
5165
5166 #[test]
5167 fn config_resolve_empty_tiers_applies_bash_surface_default() {
5168 let result = resolve_config(&[]);
5173 let default_config = Config::default();
5174
5175 assert!(result.dropped.is_empty());
5176 assert_eq!(result.config.format_on_edit, default_config.format_on_edit);
5178 assert_eq!(result.config.indexes, default_config.indexes);
5179 assert_eq!(result.config.disabled_tools, ["aft_delete", "aft_move"]);
5180 assert_eq!(result.config.semantic, default_config.semantic);
5181 assert_eq!(
5182 result.config.inspect.enabled,
5183 default_config.inspect.enabled
5184 );
5185 assert_eq!(result.config.lsp_servers.len(), 0);
5186 assert!(result.config.experimental_bash_rewrite);
5188 assert!(result.config.experimental_bash_compress);
5189 assert!(result.config.experimental_bash_background);
5190 }
5191
5192 #[test]
5193 fn bash_watch_sync_max_defaults_clamps_and_warns() {
5194 let default_result = resolve_config(&[]);
5195 assert_eq!(
5196 default_result.config.bash.watch_sync_max_ms,
5197 DEFAULT_BASH_WATCH_SYNC_MAX_MS
5198 );
5199 assert!(default_result
5200 .warnings
5201 .iter()
5202 .all(|warning| warning.key != "bash.watch_sync_max_ms"));
5203
5204 let clamped = resolve_config(&[tier("user", r#"{ "bash": { "watch_sync_max_ms": 5 } }"#)]);
5205 assert_eq!(
5206 clamped.config.bash.watch_sync_max_ms,
5207 MIN_BASH_WATCH_SYNC_MAX_MS
5208 );
5209 assert!(clamped.warnings.iter().any(|warning| {
5210 warning.code == "clamped_bash_watch_sync_max_ms"
5211 && warning.key == "bash.watch_sync_max_ms"
5212 && warning.value == "5"
5213 }));
5214
5215 let project_override = resolve_config(&[
5216 tier("user", r#"{ "bash": { "watch_sync_max_ms": 120000 } }"#),
5217 tier("project", r#"{ "bash": { "watch_sync_max_ms": 1800000 } }"#),
5218 ]);
5219 assert_eq!(
5220 project_override.config.bash.watch_sync_max_ms,
5221 MAX_BASH_WATCH_SYNC_MAX_MS
5222 );
5223 }
5224
5225 #[test]
5231 fn bash_worker_wait_max_defaults_accepts_project_and_rejects_below_minimum() {
5232 assert_eq!(
5233 resolve_config(&[]).config.bash.worker_wait_max_ms,
5234 DEFAULT_BASH_WORKER_WAIT_MAX_MS
5235 );
5236
5237 let project_override = resolve_config(&[
5238 tier("user", r#"{ "bash": { "worker_wait_max_ms": 600000 } }"#),
5239 tier("project", r#"{ "bash": { "worker_wait_max_ms": 120000 } }"#),
5240 ]);
5241 assert!(project_override.errors.is_empty());
5242 assert_eq!(project_override.config.bash.worker_wait_max_ms, 120_000);
5243 assert!(project_override
5244 .dropped
5245 .iter()
5246 .all(|drop| !drop.key.contains("worker_wait_max_ms")));
5247
5248 let below = tier(
5249 "user",
5250 r#"{ "format_on_edit": false, "bash": { "compress": false, "worker_wait_max_ms": 59999 } }"#,
5251 );
5252 let error = strict_tier_error(&below, None).expect("below-minimum value is an error");
5253 assert!(
5254 error.contains("bash.worker_wait_max_ms must be at least 60000"),
5255 "{error}"
5256 );
5257 let resolved = resolve_config(&[below]);
5258 assert_eq!(resolved.errors, ["invalid_security_config:bash"]);
5259
5260 let minimum = resolve_config(&[tier(
5261 "user",
5262 &format!(r#"{{ "bash": {{ "worker_wait_max_ms": {MIN_BASH_WORKER_WAIT_MAX_MS} }} }}"#),
5263 )]);
5264 assert_eq!(
5265 minimum.config.bash.worker_wait_max_ms,
5266 MIN_BASH_WORKER_WAIT_MAX_MS
5267 );
5268 }
5269
5270 #[test]
5271 fn bash_env_keeps_user_and_project_maps_apart() {
5272 let result = resolve_config(&[
5276 tier(
5277 "user",
5278 r#"{"bash":{"env":{"TZ":"UTC","SOME_USER_ENV":"from-user"}}}"#,
5279 ),
5280 tier(
5281 "project",
5282 r#"{"bash":{"env":{"TZ":"Mars","SOME_PROJECT_ENV":"from-project"}}}"#,
5283 ),
5284 ]);
5285
5286 assert!(result.errors.is_empty(), "{:?}", result.errors);
5287 assert_eq!(
5288 result.config.bash.env.get("TZ").map(String::as_str),
5289 Some("UTC")
5290 );
5291 assert_eq!(
5292 result
5293 .config
5294 .bash
5295 .env
5296 .get("SOME_USER_ENV")
5297 .map(String::as_str),
5298 Some("from-user")
5299 );
5300 assert!(!result.config.bash.env.contains_key("SOME_PROJECT_ENV"));
5301 assert_eq!(
5302 result.config.bash.project_env.get("TZ").map(String::as_str),
5303 Some("Mars")
5304 );
5305 assert_eq!(
5306 result
5307 .config
5308 .bash
5309 .project_env
5310 .get("SOME_PROJECT_ENV")
5311 .map(String::as_str),
5312 Some("from-project")
5313 );
5314 assert!(!result.dropped.iter().any(|drop| drop.key == "bash.env"));
5315 }
5316
5317 #[test]
5318 fn bash_env_harness_block_merges_names_into_the_base_map() {
5319 let result = resolve_config_for_harness(
5322 &[tier(
5323 "user",
5324 r#"{
5325 "bash": { "env": { "BASE_NAME": "base", "SHARED_NAME": "base" } },
5326 "harnesses": { "opencode": { "bash": { "env": { "HARNESS_NAME": "harness", "SHARED_NAME": "harness" } } } }
5327 }"#,
5328 )],
5329 Some(&Harness::Opencode),
5330 );
5331 assert!(result.errors.is_empty(), "{:?}", result.errors);
5332 let env = &result.config.bash.env;
5333 assert_eq!(env.get("BASE_NAME").map(String::as_str), Some("base"));
5334 assert_eq!(env.get("HARNESS_NAME").map(String::as_str), Some("harness"));
5335 assert_eq!(env.get("SHARED_NAME").map(String::as_str), Some("harness"));
5336 }
5337
5338 #[test]
5339 fn bash_runon_env_is_user_only() {
5340 let result = resolve_config(&[
5341 tier(
5342 "user",
5343 r#"{"bash":{"env":{"TZ":"UTC"},"runon_env":["TZ"]}}"#,
5344 ),
5345 tier(
5346 "project",
5347 r#"{"bash":{"env":{"IBToolNeverDeque":"1"},"runon_env":["IBToolNeverDeque"]}}"#,
5348 ),
5349 ]);
5350 assert!(result.errors.is_empty(), "{:?}", result.errors);
5351 assert_eq!(result.config.bash.runon_env, ["TZ"]);
5352 assert!(
5353 result
5354 .dropped
5355 .iter()
5356 .any(|drop| drop.key == "bash.runon_env"),
5357 "{:?}",
5358 result.dropped
5359 );
5360 }
5361
5362 #[test]
5363 fn shell_env_provider_is_off_by_default_and_user_only() {
5364 assert!(resolve_config(&[]).config.shell.env_provider.is_none());
5365 let result = resolve_config(&[
5366 tier("user", r#"{"shell":{"env_provider":{"kind":"mise"}}}"#),
5367 tier(
5368 "project",
5369 r#"{"shell":{"env_provider":{"kind":"custom","command":["hostile"]}}}"#,
5370 ),
5371 ]);
5372 assert!(result.errors.is_empty(), "{:?}", result.errors);
5373 let provider = result.config.shell.env_provider.unwrap();
5374 assert_eq!(provider.kind, crate::config::ShellEnvProviderKind::Mise);
5375 assert_eq!(provider.timeout_ms, 2000);
5376 assert_eq!(provider.argv(), ["mise", "env", "--json"]);
5377 assert!(result
5378 .dropped
5379 .iter()
5380 .any(|drop| drop.key == "shell.env_provider"));
5381 let project = resolve_config(&[tier(
5382 "project",
5383 r#"{"shell":{"env_provider":{"kind":"mise"}}}"#,
5384 )]);
5385 assert!(project.config.shell.env_provider.is_none());
5386 }
5387
5388 #[test]
5389 fn shell_env_provider_validates_command_timeout_and_platform() {
5390 for kind in ["mise", "direnv"] {
5391 let result = resolve_config(&[tier(
5392 "user",
5393 &format!(
5394 r#"{{"shell":{{"env_provider":{{"kind":"{kind}","watch":["ignored.env"]}}}}}}"#
5395 ),
5396 )]);
5397 assert_eq!(
5398 result.errors,
5399 ["invalid_security_config:shell.env_provider.watch"]
5400 );
5401 }
5402 for provider in [
5403 r#"{"kind":"custom"}"#,
5404 r#"{"kind":"mise","timeout_ms":99}"#,
5405 r#"{"kind":"mise","timeout_ms":10001}"#,
5406 r#"{"kind":"custom","command":[]}"#,
5407 ] {
5408 let result = resolve_config(&[tier(
5409 "user",
5410 &format!(r#"{{"shell":{{"env_provider":{provider}}}}}"#),
5411 )]);
5412 assert!(!result.errors.is_empty(), "{provider}");
5413 }
5414 let direnv = resolve_config(&[tier(
5415 "user",
5416 r#"{"shell":{"env_provider":{"kind":"direnv"}}}"#,
5417 )]);
5418 if cfg!(windows) {
5419 assert!(direnv
5420 .errors
5421 .iter()
5422 .any(|error| error.contains("direnv is not supported on Windows")));
5423 } else {
5424 assert!(direnv.errors.is_empty(), "{:?}", direnv.errors);
5425 assert_eq!(
5426 direnv.config.shell.env_provider.unwrap().argv(),
5427 ["direnv", "export", "json"]
5428 );
5429 }
5430 }
5431
5432 #[test]
5433 fn bash_env_null_value_rejects_the_candidate() {
5434 let project = tier("project", r#"{"bash":{"env":{"TZ":null}}}"#);
5435 let result = resolve_config(std::slice::from_ref(&project));
5436 assert_eq!(result.errors, ["invalid_security_config:bash"]);
5437 let strict = strict_tier_error(&project, None).unwrap_or_default();
5438 assert_eq!(strict, "invalid_config_null:bash.env.TZ");
5439 }
5440
5441 #[test]
5445 fn refused_bash_env_names_reject_the_candidate_at_every_tier() {
5446 let cases: &[(&str, bool, bool)] = &[
5448 ("PATH", true, true),
5449 ("LD_PRELOAD", true, true),
5450 ("path", true, true),
5451 ("HOME", true, true),
5452 ("XDG_CONFIG_HOME", true, true),
5453 ("NODE_PATH", true, true),
5454 ("Git_Config_Count", true, true),
5455 ("GIT_DIR", true, true),
5456 ("aft_x", true, true),
5457 ("SUBC_X", true, true),
5458 ("SCCACHE_DIR", true, true),
5459 ("RUST_TEST_THREADS", true, true),
5460 ("NEXTEST_TEST_THREADS", true, true),
5461 ("RUSTC_WRAPPER", true, true),
5462 ("AFT_INTERNAL_LINUX_SCOPE", true, true),
5463 ("API_KEY", false, true),
5465 ("NPM_TOKEN", false, true),
5466 ("AWS_PROFILE", false, true),
5467 ("GH_HOST", false, true),
5468 ("SSH_AUTH_SOCK", false, true),
5469 ("HTTPS_PROXY", false, true),
5470 ("NODE_EXTRA_CA_CERTS", false, true),
5471 ];
5472
5473 for (name, refused_user, refused_project) in cases {
5474 for in_harness in [false, true] {
5475 let doc = |name: &str| {
5476 let env = format!(r#""env": {{ "{name}": "value" }}"#);
5477 if in_harness {
5478 format!(r#"{{ "harnesses": {{ "opencode": {{ "bash": {{ {env} }} }} }} }}"#)
5479 } else {
5480 format!(r#"{{ "bash": {{ {env} }} }}"#)
5481 }
5482 };
5483 for (tier_name, refused) in [("user", *refused_user), ("project", *refused_project)]
5484 {
5485 let config_tier = tier(tier_name, &doc(name));
5486 let result = resolve_config_for_harness(
5487 std::slice::from_ref(&config_tier),
5488 Some(&Harness::Opencode),
5489 );
5490 let where_set = if in_harness {
5491 " in harnesses.opencode"
5492 } else {
5493 ""
5494 };
5495 if refused {
5496 assert_eq!(
5497 result.errors.len(),
5498 1,
5499 "{tier_name} {name}{where_set}: {:?}",
5500 result.errors
5501 );
5502 let error = &result.errors[0];
5503 assert!(
5505 error.contains(&format!("key {name}")),
5506 "{tier_name} {name}{where_set}: {error}"
5507 );
5508 let strict = strict_tier_error(&config_tier, Some(&Harness::Opencode))
5509 .unwrap_or_default();
5510 if in_harness {
5511 assert!(strict.contains("in harnesses.opencode"), "{strict}");
5512 } else {
5513 assert!(strict.contains(&format!("key {name}")), "{strict}");
5514 }
5515 } else {
5516 assert!(
5517 result.errors.is_empty(),
5518 "{tier_name} {name}{where_set} must be accepted: {:?}",
5519 result.errors
5520 );
5521 let kept = match tier_name {
5522 "user" => result.config.bash.env.contains_key(*name),
5523 _ => result.config.bash.project_env.contains_key(*name),
5524 };
5525 assert!(kept, "{tier_name} {name}{where_set} must be kept");
5526 }
5527 }
5528 }
5529 }
5530 }
5531
5532 #[test]
5533 fn refused_project_bash_env_name_rejects_even_though_the_project_is_untrusted() {
5534 let result = resolve_config(&[
5537 tier("user", "{}"),
5538 tier("project", r#"{"bash":{"env":{"API_KEY":"x"}}}"#),
5539 ]);
5540 assert_eq!(result.errors.len(), 1, "{:?}", result.errors);
5541 assert!(result.errors[0].contains("API_KEY"), "{:?}", result.errors);
5542 }
5543
5544 #[test]
5545 fn bash_env_names_differing_only_by_case_in_one_tier_are_not_tested_here() {
5546 let result = resolve_config(&[tier("user", r#"{"bash":{"env":{"TZ":"UTC"}}}"#)]);
5550 assert_eq!(result.config.bash.env.len(), 1);
5551 assert!(result.config.bash.project_env.is_empty());
5552 }
5553
5554 #[test]
5555 fn bash_env_rejects_preexec_hijack_keys_at_config_load() {
5556 let user = tier(
5557 "user",
5558 r#"{"bash":{"env":{"NODE_OPTIONS":"--require evil"}}}"#,
5559 );
5560 let result = resolve_config(std::slice::from_ref(&user));
5561 let error = result.errors.join(" ");
5562 assert!(error.contains("bash.env"), "{error}");
5563 assert!(error.contains("NODE_OPTIONS"), "{error}");
5564 assert!(error.contains("blocked"), "{error}");
5565 let strict_error = strict_tier_error(&user, None).unwrap_or_default();
5566 assert!(strict_error.contains("NODE_OPTIONS"), "{strict_error}");
5567 }
5568
5569 #[test]
5570 fn config_resolve_user_only_config_applies_fields() {
5571 let result = resolve_config(&[tier(
5572 "user",
5573 r#"{
5574 "$schema": "https://example.test/aft.schema.json",
5575 "format_on_edit": false,
5576 "formatter_timeout_secs": 42,
5577 "type_checker_timeout_secs": 43,
5578 "validate_on_edit": "full",
5579 "formatter": { "rust": "rustfmt", "typescript": "prettier" },
5580 "checker": { "rust": "cargo", "typescript": "tsc" },
5581 "restrict_to_project_root": true,
5582 "indexes": { "trigram": true, "semantic": true, "callgraph": false },
5583 "memory": "balanced",
5584 "url_fetch_allow_private": true,
5585 "semantic": {
5586 "backend": "openai_compatible",
5587 "model": " user-model ",
5588 "base_url": "https://semantic.example.test",
5589 "api_key_env": "AFT_API_KEY",
5590 "timeout_ms": 12345,
5591 "query_timeout_ms": 2345,
5592 "max_batch_size": 12,
5593 "max_input_tokens": 2048,
5594 "max_files": 3456
5595 },
5596 "inspect": { "enabled": false, "diagnostics_timeout_ms": 15000 },
5597 "experimental": { "lsp_ty": true },
5598 "lsp": {
5599 "servers": {
5600 "rust": { "extensions": [".rs"], "binary": "rust-analyzer" }
5601 },
5602 "disabled": ["Python"],
5603 "python": "pyright"
5604 },
5605 "bash": { "rewrite": false, "compress": true, "background": false,
5606 "long_running_reminder_enabled": false,
5607 "long_running_reminder_interval_ms": 123000 }
5608 }"#,
5609 )]);
5610
5611 assert!(result.dropped.is_empty());
5612 assert!(!result.config.format_on_edit);
5613 assert_eq!(result.config.formatter_timeout_secs, 42);
5614 assert_eq!(result.config.type_checker_timeout_secs, 43);
5615 assert_eq!(result.config.validate_on_edit.as_deref(), Some("full"));
5616 assert_eq!(
5617 result.config.formatter.get("rust").map(String::as_str),
5618 Some("rustfmt")
5619 );
5620 assert_eq!(
5621 result.config.checker.get("typescript").map(String::as_str),
5622 Some("tsc")
5623 );
5624 assert!(result.config.restrict_to_project_root);
5625 assert!(result.config.indexes.trigram);
5626 assert!(result.config.indexes.semantic);
5627 assert!(!result.config.indexes.callgraph);
5628 assert_eq!(
5629 result.config.memory,
5630 Some(crate::memory_profile::MemoryMode::Balanced)
5631 );
5632 assert!(result.config.url_fetch_allow_private);
5633 assert_eq!(
5634 result.config.semantic.backend,
5635 SemanticBackend::OpenAiCompatible
5636 );
5637 assert_eq!(result.config.semantic.model, "user-model");
5638 assert_eq!(
5639 result.config.semantic.base_url.as_deref(),
5640 Some("https://semantic.example.test")
5641 );
5642 assert_eq!(
5643 result.config.semantic.api_key_env.as_deref(),
5644 Some("AFT_API_KEY")
5645 );
5646 assert_eq!(result.config.semantic.timeout_ms, 12345);
5647 assert_eq!(result.config.semantic.query_timeout_ms, 2345);
5648 assert_eq!(result.config.semantic.max_batch_size, 12);
5649 assert_eq!(result.config.semantic.max_input_tokens, Some(2048));
5650 assert_eq!(result.config.semantic.max_files, 3456);
5651 assert!(!result.config.inspect.enabled);
5652 assert_eq!(result.config.inspect.diagnostics_timeout_ms, 15_000);
5653 assert!(!result.config.experimental_lsp_ty);
5654 assert!(result.config.disabled_lsp.contains("ty"));
5655 assert_eq!(result.config.lsp_servers.len(), 1);
5656 assert_eq!(result.config.lsp_servers[0].id, "rust");
5657 assert_eq!(
5658 result.config.lsp_servers[0].extensions,
5659 vec!["rs".to_string()]
5660 );
5661 assert_eq!(result.config.lsp_servers[0].binary, "rust-analyzer");
5662 assert_eq!(result.config.lsp_servers[0].args, Vec::<String>::new());
5663 assert_eq!(
5664 result.config.lsp_servers[0].root_markers,
5665 vec![".git".to_string()]
5666 );
5667 assert!(!result.config.experimental_bash_rewrite);
5668 assert!(result.config.experimental_bash_compress);
5669 assert!(!result.config.experimental_bash_background);
5670 assert!(!result.config.bash_long_running_reminder_enabled);
5671 assert_eq!(result.config.bash_long_running_reminder_interval_ms, 123000);
5672 }
5673
5674 #[test]
5675 fn edit_mode_resolves_at_user_and_project_tiers_with_project_precedence() {
5676 let hashline = resolve_config(&[
5677 tier("user", r#"{"edit_mode":"default"}"#),
5678 tier("project", r#"{"edit_mode":"hashline"}"#),
5679 ]);
5680 assert!(hashline.config.hashline_enabled);
5681 assert!(hashline.dropped.is_empty());
5682
5683 let default = resolve_config(&[
5684 tier("user", r#"{"edit_mode":"hashline"}"#),
5685 tier("project", r#"{"edit_mode":"default"}"#),
5686 ]);
5687 assert!(!default.config.hashline_enabled);
5688 assert!(default.dropped.is_empty());
5689 }
5690
5691 #[test]
5692 fn harness_overrides_select_the_active_harness_and_preserve_tier_order() {
5693 let tiers = [
5694 tier(
5695 "user",
5696 r#"{
5697 "disabled_tools": ["aft_delete", "aft_move", "apply_patch", "bash", "edit", "glob", "grep", "read", "write"],
5698 "harnesses": {
5699 "opencode": { "disabled_tools": [] },
5700 "pi": { "disabled_tools": ["apply_patch", "bash", "edit", "glob", "grep", "read", "write"] }
5701 }
5702 }"#,
5703 ),
5704 tier(
5705 "project",
5706 r#"{
5707 "disabled_tools": ["apply_patch", "bash", "edit", "glob", "grep", "read", "write"],
5708 "harnesses": { "opencode": { "disabled_tools": [] } }
5709 }"#,
5710 ),
5711 ];
5712
5713 let opencode = resolve_config_for_harness(&tiers, Some(&Harness::Opencode));
5714 let pi = resolve_config_for_harness(&tiers, Some(&Harness::Pi));
5715
5716 let hosts_and_default = [
5721 "aft_delete",
5722 "aft_move",
5723 "apply_patch",
5724 "bash",
5725 "edit",
5726 "glob",
5727 "grep",
5728 "read",
5729 "write",
5730 ];
5731 assert_eq!(opencode.config.disabled_tools, hosts_and_default);
5732 assert_eq!(pi.config.disabled_tools, hosts_and_default);
5733
5734 let harness_only = [tier(
5735 "user",
5736 r#"{ "harnesses": { "pi": { "disabled_tools": ["apply_patch", "bash", "edit", "glob", "grep", "read", "write"] } } }"#,
5737 )];
5738 assert_eq!(
5739 resolve_config_for_harness(&harness_only, Some(&Harness::Opencode),)
5740 .config
5741 .disabled_tools,
5742 ["aft_delete", "aft_move"]
5743 );
5744 assert_eq!(
5745 resolve_config_for_harness(&harness_only, Some(&Harness::Pi),)
5746 .config
5747 .disabled_tools,
5748 hosts_and_default
5749 );
5750 }
5751
5752 #[test]
5753 fn project_harness_overrides_are_filtered_at_the_existing_trust_boundary() {
5754 let result = resolve_config_for_harness(
5755 &[
5756 tier(
5757 "user",
5758 r#"{
5759 "restrict_to_project_root": true,
5760 "semantic": {
5761 "backend": "ollama",
5762 "base_url": "http://localhost:11434",
5763 "api_key_env": "USER_KEY"
5764 },
5765 "sandbox": { "profile": { "worker": "strict", "head": "strict" }, "write_allow": ["/user/write"] }
5766 }"#,
5767 ),
5768 tier(
5769 "project",
5770 r#"{
5771 "harnesses": {
5772 "opencode": {
5773 "edit_mode": "hashline",
5774 "restrict_to_project_root": false,
5775 "semantic": {
5776 "backend": "openai_compatible",
5777 "base_url": "https://evil.example.test",
5778 "api_key_env": "EVIL_KEY"
5779 },
5780 "subc": { "connection_file": "/tmp/evil-subc.json" },
5781 "sandbox": { "profile": { "worker": "relaxed", "head": "off" }, "write_allow": ["/project/write"] }
5782 }
5783 }
5784 }"#,
5785 ),
5786 ],
5787 Some(&Harness::Opencode),
5788 );
5789
5790 assert!(result.config.hashline_enabled);
5791 assert!(result.config.restrict_to_project_root);
5792 assert_eq!(result.config.semantic.backend, SemanticBackend::Ollama);
5793 assert_eq!(
5794 result.config.semantic.api_key_env.as_deref(),
5795 Some("USER_KEY")
5796 );
5797 assert!(result.config.sandbox.head_enabled());
5798 assert_eq!(
5799 result.config.sandbox.write_allow,
5800 vec![PathBuf::from("/user/write")]
5801 );
5802 let keys = drop_keys(&result);
5803 for key in [
5804 "restrict_to_project_root",
5805 "semantic.backend",
5806 "semantic.base_url",
5807 "semantic.api_key_env",
5808 "subc",
5809 "sandbox.profile.head",
5810 "sandbox.write_allow",
5811 ] {
5812 assert!(keys.contains(&key.to_string()), "missing dropped key {key}");
5813 }
5814 }
5815
5816 #[test]
5817 fn github_is_user_only_and_records_project_drops() {
5818 let remains_disabled = resolve_config(&[
5819 tier(
5820 "user",
5821 r#"{"github":{"shim":false,"read":false,"write":false}}"#,
5822 ),
5823 tier(
5824 "project",
5825 r#"{"github":{"shim":true,"read":true,"write":true}}"#,
5826 ),
5827 ]);
5828 assert!(!remains_disabled.config.github.shim);
5829 assert!(!remains_disabled.config.github.read);
5830 assert!(!remains_disabled.config.github.write);
5831 assert_eq!(drop_keys(&remains_disabled), vec!["github"]);
5832 assert_eq!(remains_disabled.dropped[0].tier, "project");
5833 assert_eq!(remains_disabled.dropped[0].reason, USER_ONLY_REASON);
5834 }
5835
5836 #[test]
5837 fn removed_opencode_prompt_keys_refuse_every_tier_and_harness() {
5838 for tier_name in ["user", "project"] {
5839 for doc in [
5840 r#"{"opencode":{"server_url":"http://127.0.0.1:4096","server_password_env":"PW"}}"#,
5841 r#"{"harnesses":{"opencode":{"opencode":{"server_url":"http://127.0.0.1:4096"}}}}"#,
5842 ] {
5843 let input = tier(tier_name, doc);
5844 let result = resolve_config_for_harness(&[input.clone()], Some(&Harness::Opencode));
5845 assert!(!result.errors.is_empty());
5846 assert!(result
5847 .errors
5848 .iter()
5849 .all(|error| error.starts_with("removed_config_key:")));
5850 assert!(strict_tier_error(&input, Some(&Harness::Opencode))
5851 .unwrap()
5852 .contains("removed_config_key:"));
5853 }
5854 }
5855 }
5856
5857 #[test]
5858 fn removed_opencode_keys_in_ignored_deeper_harnesses_load() {
5859 for tier_name in ["user", "project"] {
5860 let input = tier(
5861 tier_name,
5862 r#"{"harnesses":{"opencode":{"harnesses":{"pi":{"opencode":{"server_url":"http://127.0.0.1:4096","server_password_env":"PW"}}}}}}"#,
5863 );
5864 let result = resolve_config_for_harness(&[input.clone()], Some(&Harness::Opencode));
5865 assert!(result.errors.is_empty(), "{:?}", result.errors);
5866 let strict = strict_tier_error(&input, Some(&Harness::Opencode));
5867 assert!(
5868 strict.is_none(),
5869 "strict loader rejected ignored data: {strict:?}"
5870 );
5871 }
5872 }
5873
5874 #[test]
5875 fn github_write_forces_read_and_records_a_warning_naming_both_keys() {
5876 let result = resolve_config(&[tier("user", r#"{"github":{"write":true,"read":false}}"#)]);
5877
5878 assert!(result.config.github.write);
5879 assert!(result.config.github.read);
5880 let warning = result
5881 .warnings
5882 .iter()
5883 .find(|warning| warning.code == "github_write_requires_read")
5884 .expect("write-implies-read warning");
5885 assert_eq!(warning.key, "github.write");
5886 assert!(warning.message.contains("github.write"));
5887 assert!(warning.message.contains("github.read"));
5888 }
5889
5890 #[test]
5893 fn gh_shim_binary_path_alone_still_loads() {
5894 let binary = resolve_config(&[tier(
5895 "user",
5896 r#"{"gh_shim":{"binary_path":"/opt/aft/bin/aft"}}"#,
5897 )]);
5898 assert!(binary.errors.is_empty(), "{:?}", binary.errors);
5899 assert_eq!(
5900 binary.config.gh_shim.binary_path,
5901 Some(PathBuf::from("/opt/aft/bin/aft"))
5902 );
5903 }
5904
5905 #[test]
5906 fn git_co_author_accepts_project_precedence_and_rejects_invalid_identities() {
5907 let resolved = resolve_config(&[
5908 tier("user", r#"{"git":{"co_author":"auto"}}"#),
5909 tier(
5910 "project",
5911 r#"{"git":{"co_author":"Pair Agent <pair@example.test>"}}"#,
5912 ),
5913 ]);
5914 assert_eq!(
5915 resolved.config.git.co_author,
5916 "Pair Agent <pair@example.test>"
5917 );
5918 assert!(resolved.dropped.is_empty());
5919
5920 let invalid = resolve_config(&[tier(
5921 "user",
5922 r#"{"git":{"co_author":"not-an-identity"},"indexes":{"trigram":true}}"#,
5923 )]);
5924 assert_eq!(invalid.config.git.co_author, "off");
5925 assert!(invalid.config.indexes.trigram);
5926 }
5927
5928 #[test]
5929 fn unknown_edit_mode_warns_and_falls_back_without_dropping_valid_keys() {
5930 let result = resolve_config(&[tier(
5931 "project",
5932 r#"{"edit_mode":"future","format_on_edit":true}"#,
5933 )]);
5934
5935 assert!(!result.config.hashline_enabled);
5936 assert!(result.config.format_on_edit);
5937 assert_eq!(result.warnings.len(), 1);
5938 assert_eq!(result.warnings[0].code, "invalid_edit_mode");
5939 assert_eq!(result.warnings[0].key, "edit_mode");
5940 assert_eq!(result.warnings[0].tier, "project");
5941 assert_eq!(result.warnings[0].value, "future");
5942 }
5943
5944 #[test]
5945 fn synapse_requires_explicit_model_and_receives_user_subc_connection_file() {
5946 let without_model = resolve_config(&[tier(
5947 "user",
5948 r#"{
5949 "semantic": { "backend": "synapse" },
5950 "subc": { "connection_file": "/tmp/subc-connection.json" }
5951 }"#,
5952 )]);
5953 assert_eq!(
5954 without_model.config.semantic.backend,
5955 SemanticBackend::Synapse
5956 );
5957 assert!(without_model.config.semantic.model.is_empty());
5958 assert_eq!(
5959 without_model.config.semantic.subc_connection_file,
5960 Some(PathBuf::from("/tmp/subc-connection.json"))
5961 );
5962
5963 let with_model = resolve_config(&[tier(
5964 "user",
5965 r#"{
5966 "semantic": { "backend": "synapse", "model": "configured-model" },
5967 "subc": { "connection_file": "/tmp/subc-connection.json" }
5968 }"#,
5969 )]);
5970 assert_eq!(with_model.config.semantic.model, "configured-model");
5971 }
5972
5973 #[test]
5974 fn semantic_query_instruction_resolves_at_user_and_project_tiers() {
5975 let result = resolve_config(&[
5976 tier(
5977 "user",
5978 r#"{"semantic":{"query_instruction":"user retrieval task"}}"#,
5979 ),
5980 tier(
5981 "project",
5982 r#"{"semantic":{"query_instruction":"project retrieval task"}}"#,
5983 ),
5984 ]);
5985
5986 assert_eq!(
5987 result.config.semantic.query_instruction,
5988 "project retrieval task"
5989 );
5990 assert_eq!(
5991 resolve_config(&[]).config.semantic.query_instruction,
5992 crate::config::DEFAULT_SEMANTIC_QUERY_INSTRUCTION
5993 );
5994 }
5995
5996 #[test]
5997 fn semantic_query_timeout_clamps_to_interactive_budget_range() {
5998 let below_min =
5999 resolve_config(&[tier("user", r#"{ "semantic": { "query_timeout_ms": 1 } }"#)]);
6000 assert_eq!(
6001 below_min.config.semantic.query_timeout_ms,
6002 MIN_SEMANTIC_QUERY_TIMEOUT_MS
6003 );
6004
6005 let above_max = resolve_config(&[tier(
6006 "user",
6007 r#"{ "semantic": { "query_timeout_ms": 50000 } }"#,
6008 )]);
6009 assert_eq!(
6010 above_max.config.semantic.query_timeout_ms,
6011 MAX_SEMANTIC_QUERY_TIMEOUT_MS
6012 );
6013 }
6014
6015 #[test]
6016 fn inspect_diagnostics_timeout_clamps_to_blocking_phase_range() {
6017 let below_min = resolve_config(&[tier(
6018 "user",
6019 r#"{ "inspect": { "diagnostics_timeout_ms": 1 } }"#,
6020 )]);
6021 assert_eq!(
6022 below_min.config.inspect.diagnostics_timeout_ms,
6023 MIN_INSPECT_DIAGNOSTICS_TIMEOUT_MS
6024 );
6025
6026 let above_max = resolve_config(&[tier(
6027 "user",
6028 r#"{ "inspect": { "diagnostics_timeout_ms": 700000 } }"#,
6029 )]);
6030 assert_eq!(
6031 above_max.config.inspect.diagnostics_timeout_ms,
6032 MAX_INSPECT_DIAGNOSTICS_TIMEOUT_MS
6033 );
6034 }
6035
6036 #[test]
6037 fn idle_root_ttl_clamps_to_five_through_thirty() {
6038 let below = resolve_config(&[tier("user", r#"{ "idle": { "root_ttl_minutes": 1 } }"#)]);
6039 assert_eq!(
6040 below.config.idle.root_ttl_minutes,
6041 MIN_IDLE_ROOT_TTL_MINUTES
6042 );
6043 assert!(below
6044 .warnings
6045 .iter()
6046 .any(|warning| warning.code == "clamped_idle_ttl"
6047 && warning.key == "idle.root_ttl_minutes"));
6048
6049 let above = resolve_config(&[tier("user", r#"{ "idle": { "root_ttl_minutes": 60 } }"#)]);
6050 assert_eq!(
6051 above.config.idle.root_ttl_minutes,
6052 MAX_IDLE_ROOT_TTL_MINUTES
6053 );
6054 assert!(above
6055 .warnings
6056 .iter()
6057 .any(|warning| warning.code == "clamped_idle_ttl"
6058 && warning.key == "idle.root_ttl_minutes"));
6059
6060 let at_min = resolve_config(&[tier("user", r#"{ "idle": { "root_ttl_minutes": 5 } }"#)]);
6061 assert_eq!(at_min.config.idle.root_ttl_minutes, 5);
6062 assert!(at_min.warnings.is_empty());
6063
6064 let at_max = resolve_config(&[tier("user", r#"{ "idle": { "root_ttl_minutes": 30 } }"#)]);
6065 assert_eq!(at_max.config.idle.root_ttl_minutes, 30);
6066 assert!(at_max.warnings.is_empty());
6067 }
6068
6069 #[test]
6070 fn removed_views_enabled_refused_for_user_and_noticed_for_project() {
6071 let doc = r#"{"views":{"enabled":true}}"#;
6072 let user = resolve_config(&[tier("user", doc)]);
6073 assert_eq!(
6074 user.errors,
6075 vec!["removed_config_key:views.enabled; run npx @cortexkit/aft doctor --fix"]
6076 );
6077 let project = resolve_config(&[tier("project", doc)]);
6078 assert!(project.errors.is_empty(), "{:?}", project.errors);
6079 assert!(project.warnings.is_empty(), "{:?}", project.warnings);
6080 assert_eq!(
6081 serde_json::to_value(project.config).unwrap(),
6082 serde_json::to_value(resolve_config(&[]).config).unwrap()
6083 );
6084 let mut map = serde_json::from_str::<Value>(doc)
6085 .unwrap()
6086 .as_object()
6087 .unwrap()
6088 .clone();
6089 let translation =
6090 feature_config::translate_document(&mut map, feature_config::DocumentTier::Project);
6091 let notice =
6092 feature_config::project_retired_keys_notice("/project/aft.jsonc", &translation);
6093 let expected = feature_config::REMOVED_DATA_LAYER_NOTES
6094 .iter()
6095 .find(|(path, _)| *path == "views.enabled")
6096 .unwrap()
6097 .1;
6098 assert_eq!(notice, expected);
6099 }
6100
6101 #[test]
6102 fn removed_views_callgraph_copies_refused_for_user_and_noticed_for_project() {
6103 let doc = r#"{"views":{"callgraph_copies":2}}"#;
6104 let user = resolve_config(&[tier("user", doc)]);
6105 assert_eq!(
6106 user.errors,
6107 vec!["removed_config_key:views.callgraph_copies; run npx @cortexkit/aft doctor --fix"]
6108 );
6109 let project = resolve_config(&[tier("project", doc)]);
6110 assert!(project.errors.is_empty(), "{:?}", project.errors);
6111 assert!(project.warnings.is_empty(), "{:?}", project.warnings);
6112 assert_eq!(
6113 serde_json::to_value(project.config).unwrap(),
6114 serde_json::to_value(resolve_config(&[]).config).unwrap()
6115 );
6116 let mut map = serde_json::from_str::<Value>(doc)
6117 .unwrap()
6118 .as_object()
6119 .unwrap()
6120 .clone();
6121 let translation =
6122 feature_config::translate_document(&mut map, feature_config::DocumentTier::Project);
6123 let notice =
6124 feature_config::project_retired_keys_notice("/project/aft.jsonc", &translation);
6125 let expected = feature_config::REMOVED_DATA_LAYER_NOTES
6126 .iter()
6127 .find(|(path, _)| *path == "views.callgraph_copies")
6128 .unwrap()
6129 .1;
6130 assert_eq!(notice, expected);
6131 }
6132
6133 #[test]
6134 fn removed_worktree_ram_overlay_refused_for_user_and_noticed_for_project() {
6135 let doc = r#"{"worktree":{"ram_overlay":false}}"#;
6136 let user = resolve_config(&[tier("user", doc)]);
6137 assert_eq!(
6138 user.errors,
6139 vec!["removed_config_key:worktree.ram_overlay; run npx @cortexkit/aft doctor --fix"]
6140 );
6141 let project = resolve_config(&[tier("project", doc)]);
6142 assert!(project.errors.is_empty(), "{:?}", project.errors);
6143 assert!(project.warnings.is_empty(), "{:?}", project.warnings);
6144 assert_eq!(
6145 serde_json::to_value(project.config).unwrap(),
6146 serde_json::to_value(resolve_config(&[]).config).unwrap()
6147 );
6148 let mut map = serde_json::from_str::<Value>(doc)
6149 .unwrap()
6150 .as_object()
6151 .unwrap()
6152 .clone();
6153 let translation =
6154 feature_config::translate_document(&mut map, feature_config::DocumentTier::Project);
6155 let notice =
6156 feature_config::project_retired_keys_notice("/project/aft.jsonc", &translation);
6157 let expected = feature_config::REMOVED_DATA_LAYER_NOTES
6158 .iter()
6159 .find(|(path, _)| *path == "worktree.ram_overlay")
6160 .unwrap()
6161 .1;
6162 assert_eq!(notice, expected);
6163 }
6164
6165 #[test]
6169 fn idle_checkout_hours_defaults_clamps_and_merges_per_key() {
6170 let default = resolve_config(&[tier("user", r#"{}"#)]);
6171 assert_eq!(default.config.idle.checkout_hours, 168);
6172
6173 let merged = resolve_config(&[
6174 tier(
6175 "user",
6176 r#"{"idle":{"checkout_hours":2,"root_ttl_minutes":20}}"#,
6177 ),
6178 tier("project", r#"{"idle":{"root_ttl_minutes":15}}"#),
6179 ]);
6180 assert_eq!(merged.config.idle.checkout_hours, 2);
6181 assert_eq!(merged.config.idle.root_ttl_minutes, 15);
6182 let project = resolve_config(&[
6183 tier("user", r#"{"idle":{"checkout_hours":2}}"#),
6184 tier("project", r#"{"idle":{"checkout_hours":48}}"#),
6185 ]);
6186 assert_eq!(project.config.idle.checkout_hours, 48);
6187
6188 for (doc, want) in [
6189 (r#"{"idle":{"checkout_hours":0}}"#, 1),
6190 (r#"{"idle":{"checkout_hours":9000}}"#, 8760),
6191 ] {
6192 let clamped = resolve_config(&[tier("user", doc)]);
6193 assert_eq!(clamped.config.idle.checkout_hours, want, "{doc}");
6194 assert!(
6195 clamped
6196 .warnings
6197 .iter()
6198 .any(|warning| warning.code == "clamped_idle_ttl"
6199 && warning.key == "idle.checkout_hours"),
6200 "{doc}: {:?}",
6201 clamped.warnings
6202 );
6203 }
6204 let fractional = resolve_config(&[tier("user", r#"{"idle":{"checkout_hours":1.5}}"#)]);
6205 assert_eq!(fractional.config.idle.checkout_hours, 168);
6206 assert!(fractional
6207 .warnings
6208 .iter()
6209 .any(|warning| warning.code == "invalid_idle_ttl"
6210 && warning.key == "idle.checkout_hours"));
6211 }
6212
6213 #[test]
6217 fn retired_views_idle_checkout_hours_becomes_idle_checkout_hours() {
6218 let _release = feature_config::override_running_release_for_test((0, 64));
6219 let user = resolve_config(&[tier("user", r#"{"views":{"idle_checkout_hours":2}}"#)]);
6220 assert!(user.errors.is_empty(), "{:?}", user.errors);
6221 assert_eq!(user.config.idle.checkout_hours, 2);
6222
6223 let project = resolve_config(&[
6224 tier("user", r#"{"idle":{"checkout_hours":2}}"#),
6225 tier(
6226 "project",
6227 r#"{"views":{"idle_checkout_hours":72,"enabled":true}}"#,
6228 ),
6229 ]);
6230 assert_eq!(project.config.idle.checkout_hours, 72);
6231
6232 let clamped = resolve_config(&[tier("user", r#"{"views":{"idle_checkout_hours":0}}"#)]);
6233 assert_eq!(clamped.config.idle.checkout_hours, 1);
6234
6235 let canonical = resolve_config(&[tier(
6236 "user",
6237 r#"{"views":{"idle_checkout_hours":2},"idle":{"checkout_hours":5}}"#,
6238 )]);
6239 assert_eq!(canonical.config.idle.checkout_hours, 5);
6240 }
6241
6242 #[test]
6243 fn config_0_65_idle_rename_refuses_user_but_project_loads_with_notice() {
6244 let _release = feature_config::override_running_release_for_test((0, 65));
6245 for (doc, key) in [
6246 (
6247 r#"{"views":{"idle_checkout_hours":72}}"#,
6248 "views.idle_checkout_hours",
6249 ),
6250 (
6251 r#"{"harnesses":{"pi":{"views":{"idle_checkout_hours":72}}}}"#,
6252 "harnesses.pi.views.idle_checkout_hours",
6253 ),
6254 ] {
6255 let user = tier("user", doc);
6256 let rejected = resolve_config_for_harness(&[user.clone()], Some(&Harness::Pi));
6257 assert_eq!(
6258 rejected.errors,
6259 [format!(
6260 "removed_config_key:{key}; run npx @cortexkit/aft doctor --fix"
6261 )]
6262 );
6263 assert!(strict_tier_error(&user, Some(&Harness::Pi)).is_some());
6264
6265 let project = tier("project", doc);
6266 assert!(strict_tier_error(&project, Some(&Harness::Pi)).is_none());
6267 let loaded = resolve_config_for_harness(&[project], Some(&Harness::Pi));
6268 assert!(loaded.errors.is_empty(), "{:?}", loaded.errors);
6269 assert_eq!(loaded.config.idle.checkout_hours, 72);
6270 assert!(loaded.warnings.is_empty(), "{:?}", loaded.warnings);
6271 let mut map = serde_json::from_str::<Value>(doc)
6272 .unwrap()
6273 .as_object()
6274 .unwrap()
6275 .clone();
6276 let translation =
6277 feature_config::translate_document(&mut map, feature_config::DocumentTier::Project);
6278 let notice =
6279 feature_config::project_retired_keys_notice("/project/aft.jsonc", &translation);
6280 assert!(
6281 notice.contains(&format!("uses retired keys ({key})")),
6282 "{notice}"
6283 );
6284 assert!(
6285 notice.contains("views.idle_checkout_hours is now idle.checkout_hours"),
6286 "{notice}"
6287 );
6288 }
6289 }
6290
6291 #[test]
6292 fn lsp_idle_clamps_to_five_through_1440() {
6293 for (raw, expected) in [(0, 5), (5, 5), (1440, 1440), (2000, 1440)] {
6294 let result = resolve_config(&[tier(
6295 "user",
6296 &format!(r#"{{"lsp":{{"idle_minutes":{raw}}}}}"#),
6297 )]);
6298 assert!(result.errors.is_empty());
6299 assert_eq!(result.config.lsp_idle_minutes, expected);
6300 }
6301 }
6302
6303 #[test]
6304 fn idle_non_integer_ttl_is_dropped_with_warning() {
6305 let result = resolve_config(&[tier("user", r#"{ "idle": { "root_ttl_minutes": 12.5 } }"#)]);
6306 assert_eq!(
6307 result.config.idle.root_ttl_minutes,
6308 DEFAULT_IDLE_ROOT_TTL_MINUTES
6309 );
6310 assert!(result
6311 .warnings
6312 .iter()
6313 .any(|warning| warning.code == "invalid_idle_ttl"
6314 && warning.key == "idle.root_ttl_minutes"));
6315 }
6316
6317 #[test]
6318 fn idle_project_tier_overrides_user_root_ttl() {
6319 let result = resolve_config(&[
6320 tier("user", r#"{"idle":{"root_ttl_minutes":20}}"#),
6321 tier("project", r#"{"idle":{"root_ttl_minutes":15}}"#),
6322 ]);
6323 assert_eq!(result.config.idle.root_ttl_minutes, 15);
6324 }
6325
6326 #[test]
6327 fn project_inspect_diagnostics_timeout_can_raise_but_never_lower_user_value() {
6328 let lower = resolve_config(&[
6329 tier(
6330 "user",
6331 r#"{ "inspect": { "diagnostics_timeout_ms": 180000 } }"#,
6332 ),
6333 tier(
6334 "project",
6335 r#"{ "inspect": { "diagnostics_timeout_ms": 90000 } }"#,
6336 ),
6337 ]);
6338 assert_eq!(lower.config.inspect.diagnostics_timeout_ms, 180_000);
6339
6340 let higher = resolve_config(&[
6341 tier(
6342 "user",
6343 r#"{ "inspect": { "diagnostics_timeout_ms": 180000 } }"#,
6344 ),
6345 tier(
6346 "project",
6347 r#"{ "inspect": { "diagnostics_timeout_ms": 240000 } }"#,
6348 ),
6349 ]);
6350 assert_eq!(higher.config.inspect.diagnostics_timeout_ms, 240_000);
6351 }
6352
6353 #[test]
6354 fn project_indexes_can_only_turn_an_index_off() {
6355 let result = resolve_config_for_harness(
6358 &[
6359 tier("user", r#"{ "indexes": { "trigram": false } }"#),
6360 tier("project", r#"{ "indexes": { "trigram": true } }"#),
6361 ],
6362 None,
6363 );
6364 assert!(!result.config.indexes.trigram);
6365 assert!(result.dropped.is_empty());
6366
6367 let project_off = resolve_config(&[
6368 tier("user", r#"{}"#),
6369 tier(
6370 "project",
6371 r#"{ "indexes": { "semantic": false }, "harnesses": { "opencode": { "indexes": { "callgraph": false, "semantic": true } } } }"#,
6372 ),
6373 ]);
6374 assert!(project_off.config.indexes.trigram);
6375 let opencode = resolve_config_for_harness(
6376 &[
6377 tier("user", r#"{}"#),
6378 tier(
6379 "project",
6380 r#"{ "indexes": { "semantic": false }, "harnesses": { "opencode": { "indexes": { "callgraph": false, "semantic": true } } } }"#,
6381 ),
6382 ],
6383 Some(&Harness::Opencode),
6384 );
6385 assert!(!opencode.config.indexes.semantic);
6386 assert!(!opencode.config.indexes.callgraph);
6387 assert!(!project_off.config.indexes.semantic);
6388 assert!(project_off.config.indexes.callgraph);
6389
6390 let user_harness = resolve_config_for_harness(
6392 &[tier(
6393 "user",
6394 r#"{ "indexes": { "trigram": false }, "harnesses": { "pi": { "indexes": { "trigram": true } } } }"#,
6395 )],
6396 Some(&Harness::Pi),
6397 );
6398 assert!(user_harness.config.indexes.trigram);
6399 }
6400
6401 #[test]
6402 fn sandbox_profiles_default_by_role_and_project_cannot_loosen() {
6403 let defaults = resolve_config(&[tier("user", "{}")]);
6404 let sandbox = serde_json::to_value(&defaults.config.sandbox).unwrap();
6405 assert_eq!(sandbox["profile"]["worker"], "relaxed");
6406 assert_eq!(sandbox["profile"]["head"], "off");
6407 let result = resolve_config(&[
6408 tier(
6409 "user",
6410 r#"{"sandbox":{"profile":{"worker":"strict","head":"relaxed"}}}"#,
6411 ),
6412 tier(
6413 "project",
6414 r#"{"sandbox":{"profile":{"worker":"off","head":"off"}}}"#,
6415 ),
6416 ]);
6417 let sandbox = serde_json::to_value(&result.config.sandbox).unwrap();
6418 assert_eq!(sandbox["profile"]["worker"], "strict");
6419 assert_eq!(sandbox["profile"]["head"], "relaxed");
6420 assert!(drop_keys(&result).contains(&"sandbox.profile.worker".to_string()));
6421 assert!(drop_keys(&result).contains(&"sandbox.profile.head".to_string()));
6422 for role in ["worker", "head"] {
6423 for (floor_rank, floor) in ["off", "relaxed", "strict"].into_iter().enumerate() {
6424 for (next_rank, next) in ["off", "relaxed", "strict"].into_iter().enumerate() {
6425 let user =
6426 serde_json::json!({"sandbox":{"profile":{(role):floor}}}).to_string();
6427 let project =
6428 serde_json::json!({"sandbox":{"profile":{(role):next}}}).to_string();
6429 let result = resolve_config(&[tier("user", &user), tier("project", &project)]);
6430 let sandbox = serde_json::to_value(&result.config.sandbox).unwrap();
6431 assert_eq!(
6432 sandbox["profile"][role],
6433 if next_rank >= floor_rank { next } else { floor },
6434 "{role}: {floor} -> {next}"
6435 );
6436 }
6437 }
6438 }
6439 }
6440
6441 #[test]
6442 fn project_sandbox_can_add_read_denies_but_not_enable_or_add_writes() {
6443 let result = resolve_config(&[
6444 tier(
6445 "user",
6446 r#"{
6447 "sandbox": {
6448 "profile": { "worker": "strict", "head": "strict" },
6449 "write_allow": ["/user/write"],
6450 "read_deny": ["/user/secret"]
6451 }
6452 }"#,
6453 ),
6454 tier(
6455 "project",
6456 r#"{
6457 "sandbox": {
6458 "profile": { "worker": "relaxed", "head": "off" },
6459 "write_allow": ["/project/write"],
6460 "read_deny": ["/project/secret", "/user/secret"]
6461 }
6462 }"#,
6463 ),
6464 ]);
6465
6466 assert!(result.config.sandbox.head_enabled());
6467 assert_eq!(
6468 result.config.sandbox.write_allow,
6469 vec![PathBuf::from("/user/write")]
6470 );
6471 assert_eq!(
6472 result.config.sandbox.read_deny,
6473 vec![
6474 PathBuf::from("/user/secret"),
6475 PathBuf::from("/project/secret")
6476 ]
6477 );
6478 assert_eq!(
6479 drop_keys(&result),
6480 vec![
6481 "sandbox.write_allow".to_string(),
6482 "sandbox.profile.worker".to_string(),
6483 "sandbox.profile.head".to_string()
6484 ]
6485 );
6486 }
6487
6488 #[test]
6489 fn project_can_enable_sandbox_but_never_disable_it() {
6490 let opt_in = resolve_config(&[
6492 tier("user", r#"{}"#),
6493 tier(
6494 "project",
6495 r#"{ "sandbox": { "profile": { "worker": "strict", "head": "strict" } } }"#,
6496 ),
6497 ]);
6498 assert!(opt_in.config.sandbox.head_enabled());
6499 assert!(
6500 !drop_keys(&opt_in).contains(&"sandbox.profile.head".to_string()),
6501 "a stricter project profile is an accepted opt-in, not a dropped key"
6502 );
6503
6504 let opt_out = resolve_config(&[
6507 tier(
6508 "user",
6509 r#"{ "sandbox": { "profile": { "worker": "strict", "head": "strict" } } }"#,
6510 ),
6511 tier(
6512 "project",
6513 r#"{ "sandbox": { "profile": { "worker": "relaxed", "head": "off" } } }"#,
6514 ),
6515 ]);
6516 assert!(opt_out.config.sandbox.head_enabled());
6517 assert!(drop_keys(&opt_out).contains(&"sandbox.profile.head".to_string()));
6518 }
6519
6520 #[test]
6521 fn config_resolve_project_user_only_keys_are_dropped_and_user_values_win() {
6522 let result = resolve_config(&[
6523 tier(
6524 "user",
6525 r#"{
6526 "restrict_to_project_root": true,
6527 "url_fetch_allow_private": true,
6528 "formatter_timeout_secs": 11,
6529 "type_checker_timeout_secs": 33,
6530 "auto_update": true,
6531 "bridge": { "request_timeout_ms": 3000 },
6532 "semantic": {
6533 "backend": "openai_compatible",
6534 "base_url": "https://user.example.test",
6535 "api_key_env": "USER_KEY",
6536 "model": "user-model",
6537 "query_timeout_ms": 900,
6538 "max_input_tokens": 512
6539 },
6540 "lsp": {
6541 "servers": {
6542 "rust": { "extensions": [".rs"], "binary": "rust-analyzer" }
6543 },
6544 "disabled": ["user-disabled"],
6545 "versions": { "typescript-language-server": "1.0.0" },
6546 "auto_install": true,
6547 "grace_days": 7
6548 }
6549 }"#,
6550 ),
6551 tier(
6552 "project",
6553 r#"{
6554 "restrict_to_project_root": false,
6555 "url_fetch_allow_private": false,
6556 "formatter_timeout_secs": 22,
6557 "type_checker_timeout_secs": 44,
6558 "auto_update": false,
6559 "bridge": { "request_timeout_ms": 4000 },
6560 "semantic": {
6561 "backend": "ollama",
6562 "base_url": "https://project.example.test",
6563 "api_key_env": "PROJECT_KEY",
6564 "model": "project-model",
6565 "timeout_ms": 2222,
6566 "query_timeout_ms": 2222,
6567 "max_input_tokens": 960
6568 },
6569 "lsp": {
6570 "servers": {
6571 "rust": { "extensions": [".evil"], "binary": "evil-lsp" }
6572 },
6573 "disabled": ["project-disabled"],
6574 "versions": { "evil-lsp": "9.9.9" },
6575 "auto_install": false,
6576 "grace_days": 1,
6577 "python": "ty"
6578 }
6579 }"#,
6580 ),
6581 ]);
6582
6583 assert!(result.config.restrict_to_project_root);
6584 assert!(result.config.url_fetch_allow_private);
6585 assert_eq!(result.config.formatter_timeout_secs, 11);
6586 assert_eq!(result.config.type_checker_timeout_secs, 33);
6587 assert_eq!(
6588 result.config.semantic.backend,
6589 SemanticBackend::OpenAiCompatible
6590 );
6591 assert_eq!(
6592 result.config.semantic.base_url.as_deref(),
6593 Some("https://user.example.test")
6594 );
6595 assert_eq!(
6596 result.config.semantic.api_key_env.as_deref(),
6597 Some("USER_KEY")
6598 );
6599 assert_eq!(result.config.semantic.model, "project-model");
6600 assert_eq!(result.config.semantic.timeout_ms, 2222);
6601 assert_eq!(result.config.semantic.query_timeout_ms, 900);
6602 assert_eq!(result.config.semantic.max_input_tokens, Some(960));
6603 assert_eq!(result.config.lsp_servers.len(), 1);
6604 assert_eq!(result.config.lsp_servers[0].binary, "rust-analyzer");
6605 assert!(result.config.disabled_lsp.contains("user-disabled"));
6606 assert!(!result.config.disabled_lsp.contains("project-disabled"));
6607 assert!(result.config.disabled_lsp.contains("python"));
6608 assert!(result.config.experimental_lsp_ty);
6609
6610 let keys = drop_keys(&result);
6611 let expected = [
6612 "restrict_to_project_root",
6613 "url_fetch_allow_private",
6614 "formatter_timeout_secs",
6615 "type_checker_timeout_secs",
6616 "auto_update",
6617 "bridge",
6618 "semantic.backend",
6619 "semantic.base_url",
6620 "semantic.api_key_env",
6621 "semantic.query_timeout_ms",
6622 "lsp.servers",
6623 "lsp.versions",
6624 "lsp.auto_install",
6625 "lsp.grace_days",
6626 "lsp.disabled",
6627 ];
6628 for key in expected {
6629 assert!(keys.contains(&key.to_string()), "missing dropped key {key}");
6630 }
6631 assert_eq!(keys.len(), expected.len());
6632 assert!(result
6633 .dropped
6634 .iter()
6635 .all(|dropped| dropped.tier == "project"));
6636 }
6637
6638 #[test]
6639 fn disabled_tools_resolve_into_runtime_config() {
6640 let result = resolve_config(&[tier(
6641 "user",
6642 r#"{ "disabled_tools": ["aft_zoom", "aft_search"] }"#,
6643 )]);
6644 assert!(result
6645 .config
6646 .disabled_tools
6647 .iter()
6648 .any(|tool| tool == "aft_zoom"));
6649 assert!(result
6650 .config
6651 .disabled_tools
6652 .iter()
6653 .any(|tool| tool == "aft_search"));
6654 }
6655
6656 #[test]
6657 fn project_empty_disabled_list_preserves_explicit_presence() {
6658 let result = resolve_config(&[
6659 tier("user", r#"{ "disabled_tools": [] }"#),
6660 tier("project", r#"{ "disabled_tools": [] }"#),
6661 ]);
6662 assert!(result.config.disabled_tools.is_empty());
6663
6664 let project_only = resolve_config(&[tier("project", r#"{ "disabled_tools": [] }"#)]);
6667 assert_eq!(
6668 project_only.config.disabled_tools,
6669 ["aft_delete", "aft_move"]
6670 );
6671
6672 let user_empty_project_zoom = resolve_config(&[
6673 tier("user", r#"{ "disabled_tools": [] }"#),
6674 tier("project", r#"{ "disabled_tools": ["aft_zoom"] }"#),
6675 ]);
6676 assert_eq!(user_empty_project_zoom.config.disabled_tools, ["aft_zoom"]);
6677
6678 for doc in [None, Some("{}")] {
6679 let tiers: Vec<ConfigTier> = doc.map(|doc| tier("user", doc)).into_iter().collect();
6680 assert_eq!(
6681 resolve_config(&tiers).config.disabled_tools,
6682 ["aft_delete", "aft_move"]
6683 );
6684 }
6685 let search_only =
6686 resolve_config(&[tier("user", r#"{ "disabled_tools": ["aft_search"] }"#)]);
6687 assert_eq!(search_only.config.disabled_tools, ["aft_search"]);
6688 assert!(!search_only.config.aft_search_registered);
6689 }
6690
6691 #[test]
6692 fn project_disabled_tools_cannot_remove_host_slots() {
6693 let result = resolve_config(&[
6694 tier("user", r#"{ "disabled_tools": ["write"] }"#),
6695 tier(
6696 "project",
6697 r#"{ "disabled_tools": ["read", "bash", "aft_safety", "aft_zoom"] }"#,
6698 ),
6699 ]);
6700 assert_eq!(result.config.disabled_tools, ["aft_zoom", "write"]);
6701 let dropped = drop_keys(&result);
6702 for key in [
6703 "disabled_tools.aft_safety",
6704 "disabled_tools.bash",
6705 "disabled_tools.read",
6706 ] {
6707 assert!(dropped.contains(&key.to_string()), "{key}");
6708 }
6709 }
6710
6711 #[test]
6712 fn remote_exec_is_user_only_and_a_project_may_only_turn_it_off() {
6713 assert_eq!(
6714 resolve_config(&[]).config.remote_exec,
6715 RemoteExecConfig::default()
6716 );
6717 let user = r#"{ "remote_exec": { "enabled": true, "default_demand": "linux" } }"#;
6718 let on = resolve_config(&[tier("user", user)]).config.remote_exec;
6719 assert!(on.enabled && !on.project_off);
6720 assert_eq!(on.default_demand.as_deref(), Some("linux"));
6721
6722 let project_on = resolve_config(&[tier(
6724 "project",
6725 r#"{ "remote_exec": { "enabled": true, "default_demand": "linux" } }"#,
6726 )]);
6727 assert_eq!(project_on.config.remote_exec, RemoteExecConfig::default());
6728 let dropped = drop_keys(&project_on);
6729 assert!(dropped.contains(&"remote_exec.enabled".to_string()));
6730 assert!(dropped.contains(&"remote_exec.default_demand".to_string()));
6731
6732 let off = resolve_config(&[
6734 tier("user", user),
6735 tier("project", r#"{ "remote_exec": { "enabled": false } }"#),
6736 ]);
6737 assert!(!off.config.remote_exec.enabled);
6738 assert!(off.config.remote_exec.project_off);
6739 assert!(drop_keys(&off).is_empty());
6740 }
6741
6742 #[test]
6743 fn bash_linux_scope_is_user_only_and_defaults_on() {
6744 assert!(resolve_config(&[]).config.bash.linux_scope);
6745
6746 let result = resolve_config(&[
6747 tier("user", r#"{ "bash": { "linux_scope": true } }"#),
6748 tier("project", r#"{ "bash": { "linux_scope": false } }"#),
6749 ]);
6750 assert!(result.config.bash.linux_scope);
6751 assert!(drop_keys(&result).contains(&"bash.linux_scope".to_string()));
6752 }
6753
6754 #[test]
6755 fn task_scope_config_contract() {
6756 let direct = crate::config::BashConfig::default();
6757 assert!(direct.linux_scope);
6758 assert_eq!(direct.linux_scope_max_runtime_secs, 86_400);
6759 let defaults = resolve_config(&[]).config.bash;
6760 assert!(defaults.linux_scope);
6761 assert_eq!(defaults.linux_scope_max_runtime_secs, 86_400);
6762 let result = resolve_config(&[
6763 tier(
6764 "user",
6765 r#"{"bash":{"linux_scope":false,"linux_scope_max_runtime_secs":7200}}"#,
6766 ),
6767 tier(
6768 "project",
6769 r#"{"bash":{"linux_scope":true,"linux_scope_max_runtime_secs":1}}"#,
6770 ),
6771 ]);
6772 assert!(!result.config.bash.linux_scope);
6773 assert_eq!(result.config.bash.linux_scope_max_runtime_secs, 7200);
6774 assert!(drop_keys(&result).contains(&"bash.linux_scope_max_runtime_secs".into()));
6775 for value in ["0", "-1", "1.5", "4294967296", "true", "\"86400\""] {
6776 let text = format!("{{\"linux_scope_max_runtime_secs\":{value}}}");
6777 let error = serde_json::from_str::<RawBashFeatures>(&text).unwrap_err();
6778 assert!(error.to_string().contains("linux_scope_max_runtime_secs"));
6779 }
6780 }
6781
6782 #[test]
6783 fn privacy_disclaim_project_only_tightens_and_reports_weakening() {
6784 assert!(!resolve_config(&[]).config.bash.disclaim_privacy);
6785 for user in [false, true] {
6786 for project in [false, true] {
6787 let result = resolve_config(&[
6788 tier(
6789 "user",
6790 &format!(r#"{{"bash":{{"disclaim_privacy":{user}}}}}"#),
6791 ),
6792 tier(
6793 "project",
6794 &format!(r#"{{"bash":{{"disclaim_privacy":{project}}}}}"#),
6795 ),
6796 ]);
6797 assert_eq!(result.config.bash.disclaim_privacy, user || project);
6798 assert_eq!(
6799 drop_keys(&result).contains(&"bash.disclaim_privacy".to_string()),
6800 !project
6801 );
6802 }
6803 }
6804 }
6805
6806 #[test]
6807 fn config_resolve_bash_ladder_and_merge_parity() {
6808 let true_result = resolve_config(&[tier("user", r#"{ "bash": true }"#)]);
6809 assert!(true_result.config.experimental_bash_rewrite);
6810 assert!(true_result.config.experimental_bash_compress);
6811 assert!(true_result.config.experimental_bash_background);
6812
6813 let false_result = resolve_config(&[tier("user", r#"{ "bash": false }"#)]);
6814 assert!(!false_result.config.bash.enabled);
6815 assert!(!false_result.config.experimental_bash_rewrite);
6816 assert!(!false_result.config.experimental_bash_compress);
6817 assert!(!false_result.config.experimental_bash_background);
6818
6819 let object_default_result = resolve_config(&[tier("user", r#"{ "bash": {} }"#)]);
6820 assert!(object_default_result.config.experimental_bash_rewrite);
6821 assert!(object_default_result.config.experimental_bash_compress);
6822 assert!(object_default_result.config.experimental_bash_background);
6823
6824 let object_partial_result =
6825 resolve_config(&[tier("user", r#"{ "bash": { "compress": false } }"#)]);
6826 assert!(object_partial_result.config.experimental_bash_rewrite);
6827 assert!(!object_partial_result.config.experimental_bash_compress);
6828 assert!(object_partial_result.config.experimental_bash_background);
6829
6830 let surface_default_result = resolve_config(&[tier("user", r#"{}"#)]);
6831 assert!(surface_default_result.config.experimental_bash_rewrite);
6832 assert!(surface_default_result.config.experimental_bash_compress);
6833 assert!(surface_default_result.config.experimental_bash_background);
6834 assert!(!false_result.config.bash.enabled);
6835 assert!(true_result.config.bash.enabled);
6836 assert!(object_default_result.config.bash.enabled);
6837 let explicit_off = resolve_config(&[tier("user", r#"{ "bash": { "enabled": false } }"#)]);
6838 assert!(!explicit_off.config.bash.enabled);
6839 assert!(explicit_off.config.experimental_bash_rewrite);
6840 assert_eq!(false_result.config.bash, explicit_off.config.bash);
6841
6842 let merged_result = resolve_config(&[
6843 tier("user", r#"{ "bash": true }"#),
6844 tier("project", r#"{ "bash": { "compress": false } }"#),
6845 ]);
6846 assert!(merged_result.config.experimental_bash_rewrite);
6847 assert!(!merged_result.config.experimental_bash_compress);
6848 assert!(merged_result.config.experimental_bash_background);
6849
6850 let false_then_object_result = resolve_config(&[
6851 tier("user", r#"{ "bash": false }"#),
6852 tier("project", r#"{ "bash": { "compress": true } }"#),
6853 ]);
6854 assert!(!false_then_object_result.config.bash.enabled);
6855 assert!(!false_then_object_result.config.experimental_bash_rewrite);
6856 assert!(false_then_object_result.config.experimental_bash_compress);
6857 assert!(!false_then_object_result.config.experimental_bash_background);
6858 }
6859
6860 #[test]
6861 fn settings_shapes_project_bash_true_cannot_reenable_user_gate() {
6862 let result = resolve_config(&[
6863 tier(
6864 "user",
6865 r#"{"bash":{"enabled":false,"rewrite":false,"compress":false,"background":false}}"#,
6866 ),
6867 tier("project", r#"{"bash":true}"#),
6868 ]);
6869 assert!(result.errors.is_empty());
6870 assert!(!result.config.bash.enabled);
6871 assert!(result.config.experimental_bash_rewrite);
6872 assert!(result.config.experimental_bash_compress);
6873 assert!(result.config.experimental_bash_background);
6874 }
6875
6876 #[test]
6877 fn config_resolve_bash_foreground_wait_clamps_to_floor() {
6878 let Ok((raw, _)) = parse_tier(
6879 &tier(
6880 "user",
6881 r#"{ "bash": { "foreground_wait_window_ms": 1, "subagent_background": true } }"#,
6882 ),
6883 None,
6884 &mut Vec::new(),
6885 &mut Vec::new(),
6886 ) else {
6887 panic!("test tier should parse");
6888 };
6889 let mut warnings = Vec::new();
6890 let bash = resolve_bash_config(&raw, &mut warnings);
6891
6892 assert_eq!(
6893 bash.foreground_wait_window_ms,
6894 FOREGROUND_WAIT_WINDOW_MIN_MS
6895 );
6896 assert!(bash.subagent_background);
6897
6898 let result = resolve_config(&[tier(
6899 "user",
6900 r#"{ "bash": { "foreground_wait_window_ms": 1 } }"#,
6901 )]);
6902 assert_eq!(
6903 result.config.foreground_wait_window_ms,
6904 FOREGROUND_WAIT_WINDOW_MIN_MS
6905 );
6906
6907 let defaulted = resolve_config(&[tier("user", r#"{ "bash": true }"#)]);
6912 assert_eq!(
6913 defaulted.config.foreground_wait_window_ms,
6914 FOREGROUND_WAIT_WINDOW_DEFAULT_MS
6915 );
6916 assert_eq!(FOREGROUND_WAIT_WINDOW_DEFAULT_MS, 15_000);
6917 }
6918
6919 #[test]
6920 fn config_resolve_partial_parse_drops_invalid_section_and_keeps_valid_sections() {
6921 let result = resolve_config(&[tier(
6922 "user",
6923 r#"{
6924 "semantic": { "timeout_ms": 0 },
6925 "indexes": { "trigram": true },
6926 "format_on_edit": false
6927 }"#,
6928 )]);
6929
6930 assert!(result.config.indexes.trigram);
6931 assert!(!result.config.format_on_edit);
6932 assert_eq!(result.config.semantic, SemanticBackendConfig::default());
6933 assert!(result.dropped.is_empty());
6934 }
6935
6936 #[test]
6937 fn config_resolve_unrelated_unknown_user_key_keeps_lenient_defaults() {
6938 let result = resolve_config(&[tier(
6939 "user",
6940 r#"{ "not_a_real_key": true, "indexes": { "trigram": true } }"#,
6941 )]);
6942
6943 assert!(result.config.indexes.trigram);
6944 assert!(result.dropped.is_empty());
6945 assert!(result.errors.is_empty(), "{result:?}");
6946 assert!(result.config.cache_config_unknown.is_none());
6947 }
6948
6949 #[test]
6950 fn resolve_config_onto_resets_core_fields_no_cross_bind_inheritance() {
6951 let mut config = Config::default();
6957
6958 let dropped1 = resolve_config_onto(
6961 &[tier(
6962 "user",
6963 r#"{
6964 "url_fetch_allow_private": true,
6965 "restrict_to_project_root": true,
6966 "lsp": { "servers": { "rust": { "extensions": [".rs"], "binary": "rust-analyzer" } } }
6967 }"#,
6968 )],
6969 &mut config,
6970 );
6971 assert!(dropped1.is_empty());
6972 assert!(config.url_fetch_allow_private);
6973 assert!(config.restrict_to_project_root);
6974 assert_eq!(config.lsp_servers.len(), 1);
6975
6976 let _ = resolve_config_onto(
6979 &[tier("user", r#"{ "indexes": { "trigram": true } }"#)],
6980 &mut config,
6981 );
6982 assert!(
6983 !config.url_fetch_allow_private,
6984 "url_fetch_allow_private must reset to default, not inherit prior bind"
6985 );
6986 assert!(
6987 !config.restrict_to_project_root,
6988 "restrict_to_project_root must reset to default"
6989 );
6990 assert!(
6991 config.lsp_servers.is_empty(),
6992 "lsp_servers must reset to default, not inherit prior bind's custom server"
6993 );
6994 assert!(
6995 config.indexes.trigram,
6996 "this bind's own field still applies"
6997 );
6998 }
6999
7000 #[test]
7001 fn resolve_config_onto_empty_tiers_resets_to_default() {
7002 let mut config = Config::default();
7006 let _ = resolve_config_onto(
7007 &[tier("user", r#"{ "url_fetch_allow_private": true }"#)],
7008 &mut config,
7009 );
7010 assert!(config.url_fetch_allow_private);
7011
7012 let _ = resolve_config_onto(&[], &mut config);
7013 assert!(
7014 !config.url_fetch_allow_private,
7015 "empty-tier bind must reset core config to default"
7016 );
7017 }
7018
7019 #[test]
7020 fn resolve_config_onto_preserves_process_state_fields() {
7021 let mut config = Config {
7025 storage_dir: Some(std::path::PathBuf::from("/tmp/aft-store")),
7026 lsp_paths_extra: vec![std::path::PathBuf::from("/tmp/lsp-bin")],
7027 bash_permissions: true,
7028 project_root: Some(std::path::PathBuf::from("/tmp/proj")),
7029 ..Default::default()
7030 };
7031
7032 let _ = resolve_config_onto(
7033 &[tier("user", r#"{ "indexes": { "trigram": true } }"#)],
7034 &mut config,
7035 );
7036
7037 assert_eq!(
7038 config.storage_dir,
7039 Some(std::path::PathBuf::from("/tmp/aft-store"))
7040 );
7041 assert_eq!(
7042 config.lsp_paths_extra,
7043 vec![std::path::PathBuf::from("/tmp/lsp-bin")]
7044 );
7045 assert!(config.bash_permissions);
7046 assert_eq!(
7047 config.project_root,
7048 Some(std::path::PathBuf::from("/tmp/proj"))
7049 );
7050 assert!(config.indexes.trigram);
7051 }
7052
7053 #[test]
7054 fn index_roots_are_user_only_normalized_and_validate_before_resolution() {
7055 let result = resolve_config(&[tier(
7056 "user",
7057 r#"{
7058 "index": {
7059 "roots": [{
7060 "path": "~/.aft-standing-root",
7061 "indexes": ["semantic", "callgraph"],
7062 "future_field": true
7063 }]
7064 }
7065 }"#,
7066 )]);
7067 assert_eq!(result.config.index.roots.len(), 1);
7068 assert_eq!(result.config.index.roots[0].path, "~/.aft-standing-root");
7069 assert_eq!(
7070 result.config.index.roots[0].indexes,
7071 vec![IndexKind::Search, IndexKind::Semantic, IndexKind::Callgraph]
7072 );
7073 assert!(result
7074 .warnings
7075 .iter()
7076 .any(|warning| warning.code == "index_dependency_closure"));
7077 assert!(result
7078 .warnings
7079 .iter()
7080 .any(|warning| warning.code == "unknown_index_root_field"));
7081
7082 for invalid in [
7083 r#"{ "index": { "roots": [{ "path": "relative", "indexes": ["search"] }] } }"#,
7084 r#"{ "index": { "roots": [{ "path": "~/a", "indexes": [] }] } }"#,
7085 r#"{ "index": { "roots": [{ "path": "~/a", "indexes": ["search", "search"] }] } }"#,
7086 r#"{ "index": { "roots": [{ "path": "~/a", "indexes": ["unknown"] }] } }"#,
7087 ] {
7088 let invalid = resolve_config(&[tier("user", invalid)]);
7089 assert!(invalid.config.index.roots.is_empty());
7090 let warning = invalid
7091 .warnings
7092 .iter()
7093 .find(|warning| warning.code == "invalid_index_roots")
7094 .expect("invalid standing roots must be named");
7095 assert!(warning.message.contains("index.roots"));
7096 }
7097 }
7098
7099 #[test]
7100 fn index_roots_project_and_mcp_tiers_are_rejected_at_the_trust_boundary() {
7101 let result = resolve_config(&[
7102 tier(
7103 "user",
7104 r#"{ "index": { "roots": [{ "path": "~/user", "indexes": ["search"] }] } }"#,
7105 ),
7106 tier(
7107 "project",
7108 r#"{ "index": { "roots": [{ "path": "~/project", "indexes": ["semantic"] }] } }"#,
7109 ),
7110 tier(
7111 "mcp:untrusted",
7112 r#"{ "index": { "roots": [{ "path": "~/mcp", "indexes": ["callgraph"] }] } }"#,
7113 ),
7114 ]);
7115 assert_eq!(result.config.index.roots[0].path, "~/user");
7116 assert_eq!(
7117 result
7118 .dropped
7119 .iter()
7120 .filter(|dropped| dropped.key == "index.roots")
7121 .map(|dropped| dropped.tier.as_str())
7122 .collect::<Vec<_>>(),
7123 vec!["project", "mcp:untrusted"]
7124 );
7125 }
7126
7127 #[test]
7128 fn config_resolve_jsonc_comments_and_trailing_commas_parse() {
7129 let result = resolve_config(&[tier(
7130 "user",
7131 r#"{
7132 // line comment
7133 "indexes": { "trigram": true },
7134 "formatter": {
7135 "rust": "rustfmt", /* block comment */
7136 },
7137 }"#,
7138 )]);
7139
7140 assert!(result.config.indexes.trigram);
7141 assert_eq!(
7142 result.config.formatter.get("rust").map(String::as_str),
7143 Some("rustfmt")
7144 );
7145 }
7146
7147 fn external_access_ask(user: Option<bool>, project: Option<bool>) -> Option<bool> {
7148 let block = |value: Option<bool>| {
7149 value.map(|ask| RawPi {
7150 external_access_ask: Some(ask),
7151 ..RawPi::default()
7152 })
7153 };
7154 merge_pi_config(block(user), block(project)).and_then(|pi| pi.external_access_ask)
7155 }
7156
7157 #[test]
7160 fn project_tier_may_only_turn_the_outside_access_prompt_on() {
7161 assert_eq!(external_access_ask(Some(true), Some(false)), Some(true));
7162 assert_eq!(external_access_ask(None, Some(false)), None);
7163 assert_eq!(external_access_ask(Some(false), Some(true)), Some(true));
7164 assert_eq!(external_access_ask(Some(false), None), Some(false));
7165
7166 let result = resolve_config(&[
7167 tier("user", r#"{ "pi": { "external_access_ask": true } }"#),
7168 tier("project", r#"{ "pi": { "external_access_ask": false } }"#),
7169 ]);
7170 assert!(result.errors.is_empty(), "{:?}", result.errors);
7171 assert_eq!(drop_keys(&result), vec!["pi.external_access_ask"]);
7172
7173 let result = resolve_config(&[
7174 tier("user", r#"{ "pi": { "external_access_ask": false } }"#),
7175 tier("project", r#"{ "pi": { "external_access_ask": true } }"#),
7176 ]);
7177 assert!(drop_keys(&result).is_empty(), "{:?}", result.dropped);
7178 }
7179}