Skip to main content

aft_base/
config_resolve.rs

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