//! Pure aft.jsonc tier resolver.
//!
//! This module mirrors the TypeScript config pipeline for the core-consumed
//! slice: raw JSONC tiers -> strict raw schema -> user/project trust merge ->
//! flat [`Config`]. It intentionally performs no IO; callers supply the already
//! read config documents.
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::PathBuf;
use serde::de;
use serde::{Deserialize, Deserializer};
use serde_json::{Map, Value};
use crate::config::{
expand_index_root_path, normalize_git_co_author, BackupConfig, Config, GhShimConfig, GitConfig,
GithubConfig, IdleConfig, IndexConfig, IndexKind, IndexRootConfig, IndexesConfig,
InspectCategories, InspectConfig, RemoteExecConfig, RerankBackendKind, RerankConfig,
SandboxConfig, SearchConfig, SemanticBackend, SemanticBackendConfig, UserServerDef,
DEFAULT_BASH_WATCH_SYNC_MAX_MS, DEFAULT_BASH_WORKER_WAIT_MAX_MS, DEFAULT_IDLE_ROOT_TTL_MINUTES,
DEFAULT_INSPECT_DIAGNOSTICS_TIMEOUT_MS, MAX_BASH_WATCH_SYNC_MAX_MS, MAX_IDLE_ROOT_TTL_MINUTES,
MAX_INSPECT_DIAGNOSTICS_TIMEOUT_MS, MAX_SEMANTIC_QUERY_TIMEOUT_MS, MIN_BASH_WATCH_SYNC_MAX_MS,
MIN_BASH_WORKER_WAIT_MAX_MS, MIN_IDLE_ROOT_TTL_MINUTES, MIN_INSPECT_DIAGNOSTICS_TIMEOUT_MS,
MIN_SEMANTIC_QUERY_TIMEOUT_MS,
};
use crate::feature_config;
use crate::harness::Harness;
use crate::jsonc::strip_jsonc;
pub mod schema;
const FOREGROUND_WAIT_WINDOW_DEFAULT_MS: u64 = 15_000;
const FOREGROUND_WAIT_WINDOW_MIN_MS: u64 = 5_000;
// Semantic budget clamps — restored from the deleted configure-time
// parse_semantic_config so the tier-resolved Config matches the historical
// clamping (zero-behavior-change relocation, not a new policy).
const MAX_SEMANTIC_TIMEOUT_MS: u64 = 120_000;
const MAX_SEMANTIC_BATCH_SIZE: usize = 1_024;
const USER_ONLY_REASON: &str =
"security: this setting only honors user-level config and project values are ignored";
const SEMANTIC_SECRET_REASON: &str =
"security: semantic backend credentials and endpoints must come from user-level config";
const PROTECTED_TOOL_REASON: &str =
"security: a project config cannot disable aft_safety or a host tool slot (read, write, edit, apply_patch, grep, glob, bash)";
const LSP_USER_ONLY_REASON: &str =
"security: LSP executable-origin and diagnostic-suppression settings must come from user-level config";
const REMOTE_EXEC_PROJECT_REASON: &str =
"security: a project config may only turn remote_exec off; enabling remote runs and choosing their runner must come from user-level config";
const RERANK_PROJECT_REASON: &str =
"security: a project config may only turn search.rerank off; every other rerank setting must come from user-level config";
/// One raw config document supplied by the host plugin.
///
/// `tier` is trusted process metadata stamped by the caller. The document body is
/// never allowed to relabel itself.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigTier {
pub tier: String,
pub source: String,
pub doc: String,
}
/// A project-tier key that was intentionally ignored at the user/project trust boundary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DroppedKey {
pub key: String,
pub tier: String,
pub reason: String,
}
/// A non-fatal config issue reported back to the caller during configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigWarning {
pub code: &'static str,
pub key: &'static str,
pub tier: String,
pub value: String,
pub message: String,
}
/// Diagnostics produced while resetting an existing runtime config.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ResolveDiagnostics {
pub dropped: Vec<DroppedKey>,
pub warnings: Vec<ConfigWarning>,
/// Rejection diagnostics. When non-empty the candidate was rejected as a
/// whole and the base config was left untouched.
pub errors: Vec<String>,
}
/// Fully resolved core config plus trust-boundary diagnostics.
#[derive(Debug, Clone)]
pub struct ResolveResult {
pub config: Config,
pub dropped: Vec<DroppedKey>,
pub warnings: Vec<ConfigWarning>,
/// Rejection diagnostics: a resolved configuration that is missing its
/// registration list or an index switch (`invalid_resolved_config:...`).
/// When non-empty `config` must not be used: the whole candidate load is
/// rejected rather than continuing with defaults.
pub errors: Vec<String>,
}
/// Strict raw shape for aft.jsonc. This mirrors the TypeScript Zod schema, not
/// the flat runtime [`Config`]. Privileged process-state fields are deliberately
/// absent and therefore rejected by `deny_unknown_fields`.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
#[schemars(
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/."
)]
pub struct RawAftConfig {
#[schemars(
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."
)]
pub memory: Option<crate::memory_profile::MemoryMode>,
#[schemars(
description = "Process-wide file flush policy from the user config base only. Project values and all harness overrides have no effect."
)]
pub durability: Option<RawDurability>,
#[schemars(
description = "Storage-wide settings from the user config base only. Project values and every harness override are ignored."
)]
pub storage: Option<RawStorage>,
#[serde(rename = "$schema")]
pub schema: Option<String>,
#[schemars(
description = "Select the edit/read surface. Hashline mode renders tagged reads and changes edit arguments to exactly { patch }."
)]
pub edit_mode: Option<RawEditMode>,
#[schemars(
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."
)]
pub format_on_edit: Option<bool>,
#[schemars(
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."
)]
pub revision_reads: Option<bool>,
#[serde(deserialize_with = "deserialize_opt_timeout_secs")]
#[schemars(range(min = 1, max = 600))]
#[schemars(
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."
)]
pub formatter_timeout_secs: Option<u32>,
#[serde(deserialize_with = "deserialize_opt_timeout_secs")]
#[schemars(range(min = 1, max = 600))]
#[schemars(
description = "Maximum time in seconds for an external type checker to run. The default is 30 seconds."
)]
pub type_checker_timeout_secs: Option<u32>,
#[schemars(
description = "Auto-validate after edits: 'syntax' (tree-sitter parse check) or 'full' (also runs type checker)."
)]
pub validate_on_edit: Option<RawValidateOnEdit>,
#[schemars(
description = "Per-language formatter overrides keyed by language (e.g. 'typescript', 'python', 'rust', 'go')."
)]
pub formatter: Option<HashMap<String, RawFormatter>>,
#[schemars(
description = "Per-language type checker overrides keyed by language (e.g. 'typescript', 'python', 'rust', 'go')."
)]
pub checker: Option<HashMap<String, RawChecker>>,
#[schemars(
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."
)]
pub configure_warnings_delivery: Option<RawConfigureWarningsDelivery>,
/// Raw presence is preserved: `None` (absent) and `Some([])` (explicit
/// empty choice) mean different things until user-base resolution.
#[schemars(
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."
)]
pub disabled_tools: Option<Vec<String>>,
#[schemars(
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)."
)]
pub restrict_to_project_root: Option<bool>,
#[schemars(
description = "Background indexes. Each defaults on and builds independently of which tools are registered. Project config can only turn an index off."
)]
pub indexes: Option<RawIndexes>,
#[schemars(
description = "Configure indexes for folders even when no session is open in them. By default, no folders are configured for standing indexing."
)]
pub index: Option<RawIndex>,
#[schemars(
description = "Codebase health inspection config. Enabled by default; set inspect.enabled=false to hide aft_inspect."
)]
pub inspect: Option<RawInspect>,
#[schemars(
description = "Idle windows: when an unbound root's indexes are evicted, and when an unused checkout drops its in-memory index state."
)]
pub idle: Option<RawIdle>,
pub backup: Option<RawBackup>,
#[schemars(
description = "User-scoped GitHub integration gates. Project config cannot change capabilities or host-wide tool descriptions."
)]
pub github: Option<RawGithub>,
#[schemars(
description = "Managed gh shim binary override. Whether the shim is used is github.shim; binary_path is the advanced AFT-image override."
)]
pub gh_shim: Option<RawGhShim>,
#[schemars(
description = "Agent-child Git attribution injected through environment-scoped core.hooksPath configuration."
)]
pub git: Option<RawGit>,
#[schemars(description = "Pi and OMP harness-specific configuration.")]
pub pi: Option<RawPi>,
#[schemars(
description = "Shell sandbox profiles: stamped workers default to relaxed, all other sessions to off; untrusted routes always use strict."
)]
pub sandbox: Option<RawSandbox>,
#[schemars(
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.*`."
)]
pub bash: Option<RawBashFeatures>,
#[schemars(
description = "User-only shell environment settings. Project configuration cannot select an environment provider."
)]
pub shell: Option<crate::config::ShellConfig>,
#[schemars(description = "Experimental opt-in features. May change between releases.")]
pub experimental: Option<RawExperimental>,
#[schemars(description = "User-defined and built-in LSP server configuration.")]
pub lsp: Option<RawLsp>,
#[schemars(
description = "Allow `aft_outline`/`aft_zoom` URL fetches to request private/link-local hosts. Default: false (rejects RFC1918, loopback, and link-local)."
)]
pub url_fetch_allow_private: Option<bool>,
#[schemars(
description = "External semantic backend configuration for embedding and retrieval."
)]
pub semantic: Option<RawSemantic>,
#[schemars(description = "aft_search settings.")]
pub search: Option<RawSearch>,
#[schemars(
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."
)]
pub auto_update: Option<bool>,
#[schemars(
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)."
)]
pub bridge: Option<RawBridge>,
#[schemars(
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."
)]
pub subc: Option<RawSubc>,
#[schemars(
description = "Remote runs requested per bash call with runon. See docs/tools.md (bash: running on the remote build server)."
)]
pub remote_exec: Option<RawRemoteExec>,
/// Set by the resolver, never read from a file: a project tier turned
/// `remote_exec.enabled` off.
#[serde(skip)]
pub remote_exec_project_off: bool,
/// Raw per-harness objects stay opaque until the resolver knows the active
/// configure harness. Unknown harness names are intentionally ignored.
#[schemars(
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."
)]
pub harnesses: Option<BTreeMap<String, Value>>,
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct RawDurability {
#[schemars(
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."
)]
pub macos_full_sync: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RawEditMode {
Default,
Hashline,
Unknown(String),
}
impl<'de> Deserialize<'de> for RawEditMode {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Ok(match value.as_str() {
"default" => Self::Default,
"hashline" => Self::Hashline,
_ => Self::Unknown(value),
})
}
}
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RawValidateOnEdit {
Syntax,
Full,
}
impl RawValidateOnEdit {
const fn as_str(self) -> &'static str {
match self {
Self::Syntax => "syntax",
Self::Full => "full",
}
}
}
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RawFormatter {
Biome,
Oxfmt,
Prettier,
Deno,
Ruff,
Black,
Rustfmt,
Goimports,
Gofmt,
None,
}
impl RawFormatter {
const fn as_str(self) -> &'static str {
match self {
Self::Biome => "biome",
Self::Oxfmt => "oxfmt",
Self::Prettier => "prettier",
Self::Deno => "deno",
Self::Ruff => "ruff",
Self::Black => "black",
Self::Rustfmt => "rustfmt",
Self::Goimports => "goimports",
Self::Gofmt => "gofmt",
Self::None => "none",
}
}
}
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RawChecker {
Tsc,
Tsgo,
Biome,
Pyright,
Ruff,
Cargo,
Go,
Staticcheck,
None,
}
impl RawChecker {
const fn as_str(self) -> &'static str {
match self {
Self::Tsc => "tsc",
Self::Tsgo => "tsgo",
Self::Biome => "biome",
Self::Pyright => "pyright",
Self::Ruff => "ruff",
Self::Cargo => "cargo",
Self::Go => "go",
Self::Staticcheck => "staticcheck",
Self::None => "none",
}
}
}
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RawConfigureWarningsDelivery {
Toast,
Log,
Chat,
}
/// Raw `indexes` block; each switch keeps its presence until resolution.
#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawIndexes {
#[schemars(
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."
)]
pub trigram: Option<bool>,
#[schemars(
description = "Semantic (embedding) index for the semantic aft_search lane. The default local backend may download an ONNX runtime and model and use CPU."
)]
pub semantic: Option<bool>,
#[schemars(description = "Persisted call-graph store used by aft_callgraph and enrichment.")]
pub callgraph: Option<bool>,
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawStorage {
#[schemars(
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.",
with = "RawCacheDir"
)]
pub cache_dir: Option<RawCacheDir>,
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum RawCacheDir {
Default {},
MainDisk {},
Dir { path: String },
}
#[derive(Debug, Clone, Deserialize, PartialEq, schemars::JsonSchema)]
// Nested objects mirror TS sub-schemas, which are non-strict z.object (unknown
// keys are silently stripped, the object survives). Only the TOP-LEVEL
// RawAftConfig is strict (matches AftConfigSchema.strict()). Privileged denylist
// fields are all top-level, so nested unknowns are harmlessly ignored.
pub struct RawSemantic {
#[schemars(
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."
)]
pub backend: Option<SemanticBackend>,
#[serde(default, deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
#[schemars(
description = "Model identifier passed to the backend. Required for synapse; fastembed defaults to all-MiniLM-L6-v2."
)]
pub model: Option<String>,
#[serde(default, deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
#[schemars(
description = "Base URL of the backend API endpoint. Required for openai_compatible. Default for ollama: http://localhost:11434."
)]
pub base_url: Option<String>,
#[serde(default, deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
#[schemars(
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."
)]
pub api_key_env: Option<String>,
/// Background embedding request floor in milliseconds. HTTP batch deadlines
/// scale above it using measured per-item latency.
#[serde(default, deserialize_with = "deserialize_opt_positive_u64")]
#[schemars(description = "Background build embedding request timeout in milliseconds.")]
pub timeout_ms: Option<u64>,
#[serde(default, deserialize_with = "deserialize_opt_positive_u64")]
#[schemars(
description = "Interactive query embedding deadline in milliseconds. Project-scoped configs cannot set this field; values are clamped to 500..30000."
)]
pub query_timeout_ms: Option<u64>,
#[serde(default, deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
#[schemars(
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."
)]
pub query_instruction: Option<String>,
#[serde(default, deserialize_with = "deserialize_opt_positive_usize")]
#[schemars(description = "Maximum batch size used by the semantic embedding pipeline.")]
pub max_batch_size: Option<usize>,
#[serde(default, deserialize_with = "deserialize_opt_positive_usize")]
#[schemars(
description = "Whole-row input token budget for remote embedding backends. Absent keeps the MiniLM-era chunk caps. Fingerprinted: changing it rebuilds the semantic index."
)]
pub max_input_tokens: Option<usize>,
#[serde(default, deserialize_with = "deserialize_opt_positive_usize")]
#[schemars(
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."
)]
pub max_files: Option<usize>,
}
impl RawSemantic {
fn is_empty(&self) -> bool {
self.backend.is_none()
&& self.model.is_none()
&& self.base_url.is_none()
&& self.api_key_env.is_none()
&& self.timeout_ms.is_none()
&& self.query_timeout_ms.is_none()
&& self.query_instruction.is_none()
&& self.max_batch_size.is_none()
&& self.max_input_tokens.is_none()
&& self.max_files.is_none()
}
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawSearch {
#[schemars(
description = "Optional cross-encoder reranking of aft_search results. Default off."
)]
pub rerank: Option<RawRerank>,
}
/// Raw `search.rerank`. Parsing only: defaults and clamps belong to the search
/// engine, which owns every setting that can change result order.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawRerank {
#[schemars(
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'."
)]
pub backend: Option<RerankBackendKind>,
#[serde(deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
#[schemars(
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."
)]
pub model: Option<String>,
#[serde(deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
#[schemars(
description = "Base URL of the remote rerank endpoint; AFT appends /rerank. Prefix with tei+ for a TEI server. User config only."
)]
pub endpoint: Option<String>,
#[serde(deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
#[schemars(
description = "Environment variable holding the remote rerank endpoint's API key. User config only."
)]
pub api_key_env: Option<String>,
#[serde(deserialize_with = "deserialize_opt_positive_u64")]
#[schemars(
description = "How many leading results are reranked (default 20, at most 200). User config only."
)]
pub top_n: Option<u64>,
#[serde(deserialize_with = "deserialize_opt_positive_u64")]
#[schemars(
description = "Reranking budget per search in milliseconds (default 1500, clamped to 50..15000). On timeout the fused order is kept. User config only."
)]
pub timeout_ms: Option<u64>,
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
pub struct RawLsp {
#[schemars(
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."
)]
pub idle_minutes: Option<i64>,
#[schemars(
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."
)]
pub idle_shutdown: Option<bool>,
#[schemars(
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."
)]
pub max_servers: Option<usize>,
#[serde(default, deserialize_with = "deserialize_opt_lsp_servers")]
#[schemars(
description = "User-defined LSP server map keyed by server id (e.g. { 'terraform-ls': { ... } })."
)]
pub servers: Option<BTreeMap<String, RawLspServerEntry>>,
#[serde(
default,
deserialize_with = "deserialize_opt_trimmed_non_empty_string_vec"
)]
#[schemars(
description = "Built-in LSP server ids to disable (e.g. ['python', 'biome']). See README for the full list."
)]
pub disabled: Option<Vec<String>>,
#[schemars(
description = "Which Python LSP to use. 'auto' stays on Pyright while ty is experimental; select 'ty' explicitly to opt in without fallback."
)]
pub python: Option<RawPythonLsp>,
#[schemars(
description = "Wait for inline LSP diagnostics on every edit/write/apply_patch call. Default: false."
)]
pub diagnostics_on_edit: Option<bool>,
#[schemars(
description = "Auto-install npm-distributed and GitHub-release LSP servers when the project needs them. Set false to require manual install on PATH."
)]
pub auto_install: Option<bool>,
#[serde(default, deserialize_with = "deserialize_opt_positive_u64")]
#[schemars(
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."
)]
pub grace_days: Option<u64>,
#[serde(default, deserialize_with = "deserialize_opt_versions_map")]
#[schemars(
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' })."
)]
pub versions: Option<HashMap<String, String>>,
}
impl RawLsp {
fn is_empty(&self) -> bool {
self.idle_minutes.is_none()
&& self.idle_shutdown.is_none()
&& self.max_servers.is_none()
&& self.servers.is_none()
&& self.disabled.is_none()
&& self.python.is_none()
&& self.diagnostics_on_edit.is_none()
&& self.auto_install.is_none()
&& self.grace_days.is_none()
&& self.versions.is_none()
}
}
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RawPythonLsp {
Pyright,
Ty,
Auto,
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawLspServerEntry {
#[serde(deserialize_with = "deserialize_opt_lsp_extensions")]
#[schemars(
description = "File extensions this server handles (e.g. ['.tf', '.tfvars']). Optional when overriding a built-in server — the built-in's extensions are inherited."
)]
pub extensions: Option<Vec<String>>,
#[serde(deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
#[schemars(
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."
)]
pub binary: Option<String>,
#[schemars(description = "Extra command-line arguments passed to the LSP binary.")]
pub args: Option<Vec<String>>,
#[serde(deserialize_with = "deserialize_opt_trimmed_non_empty_string_vec")]
#[schemars(
description = "Workspace root marker files. AFT walks up from each opened file looking for any of these."
)]
pub root_markers: Option<Vec<String>>,
#[schemars(description = "Disable this server entirely without removing the config block.")]
pub disabled: Option<bool>,
#[schemars(
description = "Extra environment variables passed to the LSP server child process."
)]
pub env: Option<HashMap<String, String>>,
#[schemars(
description = "JSON text passed as `initializationOptions` in the LSP `initialize` request. Invalid JSON prevents this server from starting."
)]
pub initialization_options: Option<String>,
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawBashFeatures {
#[schemars(
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."
)]
pub changed_files: Option<crate::config::BashChangedFiles>,
/// Runtime gate for bash execution. Absent means on.
#[schemars(
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."
)]
pub enabled: Option<bool>,
#[schemars(
description = "Rewrite common bash commands (cat, grep, find, sed, ls) into AFT tool calls for faster, formatted output."
)]
pub rewrite: Option<bool>,
#[schemars(
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."
)]
pub compress: Option<bool>,
#[schemars(
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."
)]
pub background: Option<bool>,
#[schemars(
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."
)]
pub host_fallback: Option<bool>,
#[schemars(
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."
)]
pub subagent_background: Option<bool>,
#[schemars(
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."
)]
pub detach_on_user_message: Option<bool>,
#[schemars(
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."
)]
pub db_schema_hints: Option<bool>,
#[schemars(
description = "Periodically remind the agent that a background bash task is still running. When false, completion is delivered but mid-flight reminders are suppressed."
)]
pub long_running_reminder_enabled: Option<bool>,
#[serde(deserialize_with = "deserialize_opt_positive_u64")]
#[schemars(
description = "Interval in milliseconds between mid-flight reminders for a still-running background bash task."
)]
pub long_running_reminder_interval_ms: Option<u64>,
#[serde(deserialize_with = "deserialize_opt_positive_u64")]
#[schemars(
description = "How long foreground bash blocks before auto-promoting the task to background, in milliseconds. Minimum 5000; values below the floor are clamped up."
)]
pub foreground_wait_window_ms: Option<u64>,
#[serde(deserialize_with = "deserialize_opt_positive_u64")]
#[schemars(
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."
)]
pub watch_sync_max_ms: Option<u64>,
#[serde(deserialize_with = "deserialize_opt_worker_wait_max_ms")]
#[schemars(
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."
)]
pub worker_wait_max_ms: Option<u64>,
#[schemars(
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."
)]
pub linux_scope: Option<bool>,
#[serde(deserialize_with = "deserialize_opt_linux_scope_max_runtime_secs")]
#[schemars(range(min = 1, max = 4294967295_u64))]
#[schemars(
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."
)]
pub linux_scope_max_runtime_secs: Option<u64>,
#[serde(deserialize_with = "deserialize_opt_memory_limit_mib")]
#[schemars(range(min = 1, max = 4294967295_u64))]
#[schemars(
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."
)]
pub memory_limit_mib: Option<u64>,
#[schemars(
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."
)]
pub disclaim_privacy: Option<bool>,
#[schemars(
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."
)]
pub powershell_tool: Option<bool>,
#[schemars(
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."
)]
pub env: Option<BTreeMap<String, String>>,
/// Project-tier `bash.env` values, carried separately so the user-tier map
/// stays user-only. Only `project_safe_bash` fills this field.
#[serde(skip)]
pub project_env: Option<BTreeMap<String, String>>,
/// User-only: `bash.env` names that are also sent to a `runon` job.
#[schemars(
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."
)]
pub runon_env: Option<Vec<String>>,
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawExperimental {
#[schemars(
description = "Run the experimental Python `ty` type checker alongside Pyright. Use lsp.python = 'ty' to select ty exclusively."
)]
pub lsp_ty: Option<bool>,
}
impl RawExperimental {
fn is_empty(&self) -> bool {
self.lsp_ty.is_none()
}
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawInspect {
#[schemars(
description = "Runtime switch for aft_inspect. Defaults to true. When false the registered tool reports inspect_disabled; use disabled_tools to unregister it."
)]
pub enabled: Option<bool>,
#[serde(default, deserialize_with = "deserialize_opt_positive_u64")]
#[schemars(
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."
)]
pub diagnostics_timeout_ms: Option<u64>,
#[serde(default, deserialize_with = "deserialize_opt_positive_u64")]
#[schemars(
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."
)]
pub tier2_pass_timeout_ms: Option<u64>,
#[serde(deserialize_with = "deserialize_opt_inspect_categories")]
#[schemars(with = "Option<InspectCategories>")]
#[schemars(
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."
)]
pub categories: Option<BTreeMap<String, bool>>,
#[schemars(description = "Duplicate suppression config for the duplicates inspect category.")]
pub duplicates: Option<RawInspectDuplicates>,
}
impl RawInspect {
fn is_empty(&self) -> bool {
self.enabled.is_none()
&& self.diagnostics_timeout_ms.is_none()
&& self.tier2_pass_timeout_ms.is_none()
&& self.categories.is_none()
&& self.duplicates.is_none()
}
}
/// Only `expected_mirrors` survives here: `lower_bound`, `discard_cost`, and
/// `anonymize` were accepted-but-never-read knobs (the scanner hardcodes its
/// cost bounds and anonymization rules), so they were removed from the schema
/// rather than wired up.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawInspectDuplicates {
#[schemars(
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."
)]
pub expected_mirrors: Option<Vec<RawExpectedMirror>>,
}
#[derive(Debug, Clone, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RawExpectedMirror {
pub source: String,
pub mirror: String,
}
impl RawInspectDuplicates {
fn is_empty(&self) -> bool {
self.expected_mirrors.is_none()
}
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawIdle {
#[schemars(
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."
)]
pub root_ttl_minutes: Option<Value>,
#[schemars(
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."
)]
pub checkout_hours: Option<Value>,
}
impl RawIdle {
fn is_empty(&self) -> bool {
self.root_ttl_minutes.is_none() && self.checkout_hours.is_none()
}
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawBridge {
#[serde(deserialize_with = "deserialize_opt_bridge_request_timeout_ms")]
#[schemars(
description = "Per-request bridge transport timeout in milliseconds. Default 30000. Raise on slow filesystems (WSL/DrvFs/NFS) where cold aft operations exceed the default."
)]
pub request_timeout_ms: Option<u64>,
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawSubc {
#[schemars(
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."
)]
pub connection_file: Option<String>,
#[schemars(
description = "Close the plugin's Subconscious routes to a checkout after two consecutive checks find the folder missing. Off by default."
)]
pub client_reaper: Option<bool>,
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawGithub {
#[schemars(description = "Interpose the governed gh shim in agent child PATHs.")]
pub shim: Option<bool>,
#[schemars(
description = "Enable structured issue:// and pr:// reads. github.write=true also enables this to keep comment ordinals visible."
)]
pub read: Option<bool>,
#[schemars(
description = "Enable creating and editing issue and pull-request conversation comments. Implies github.read."
)]
pub write: Option<bool>,
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawGhShim {
#[serde(deserialize_with = "deserialize_opt_trimmed_non_empty_string")]
#[schemars(
description = "Absolute deployed or development AFT binary used by the managed gh entry. Defaults to the running AFT image. User-scoped only."
)]
pub binary_path: Option<String>,
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawGit {
#[serde(deserialize_with = "deserialize_opt_git_co_author")]
#[schemars(
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."
)]
pub co_author: Option<String>,
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawPi {
#[schemars(
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."
)]
pub tool_presentation: Option<RawPiToolPresentation>,
/// Plain Pi asks before outside-project access (default on). A project
/// tier may turn it on, never off; see `merge_pi_config`.
#[schemars(
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."
)]
pub external_access_ask: Option<bool>,
}
impl RawPi {
fn is_empty(&self) -> bool {
self.tool_presentation.is_none() && self.external_access_ask.is_none()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RawPiToolPresentation {
TopLevel,
HostDefault,
Unknown(String),
}
impl<'de> Deserialize<'de> for RawPiToolPresentation {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
match s.as_str() {
"top_level" => Ok(Self::TopLevel),
"host_default" => Ok(Self::HostDefault),
other => Ok(Self::Unknown(other.to_string())),
}
}
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawBackup {
#[schemars(
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."
)]
pub enabled: Option<bool>,
#[serde(default, deserialize_with = "deserialize_opt_positive_usize")]
#[schemars(description = "Per-file undo stack depth. User-only; project config is ignored.")]
pub max_depth: Option<usize>,
#[schemars(
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."
)]
pub max_file_size: Option<u64>,
}
/// `remote_exec`: whether bash calls may ask to run on the remote build server
/// with `runon`. User tier only, except that a project may turn it off.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawRemoteExec {
#[schemars(
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."
)]
pub enabled: Option<bool>,
#[schemars(
description = "The runner demand a runon call without specifics runs under (today only \"linux\"). Never makes a call remote by itself. User-scoped only."
)]
pub default_demand: Option<String>,
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawSandbox {
#[schemars(
description = "User-selected sandbox profiles by role. Projects may only select a stricter profile (off < relaxed < strict)."
)]
pub profile: Option<RawSandboxRoles>,
#[schemars(
description = "Additional absolute writable directories. User-scoped only; project config cannot add write access."
)]
pub write_allow: Option<Vec<PathBuf>>,
#[schemars(
description = "Additional absolute paths sandboxed commands may not read. Project config may add deny entries but cannot remove user or built-in entries."
)]
pub read_deny: Option<Vec<PathBuf>>,
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawSandboxRoles {
pub worker: Option<crate::config::SandboxMode>,
pub head: Option<crate::config::SandboxMode>,
}
/// Raw user-tier standing index configuration. Unlike normally stripped nested
/// fields, unknown entry fields are retained only long enough to emit an
/// explicit warn-and-ignore notice.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawIndex {
#[schemars(
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."
)]
pub roots: Option<Vec<RawIndexRoot>>,
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, schemars::JsonSchema)]
#[serde(default)]
pub struct RawIndexRoot {
pub path: Option<String>,
pub indexes: Option<Vec<String>>,
#[serde(flatten)]
pub unknown: BTreeMap<String, Value>,
}
/// Resolve raw user/project config tiers into the flat core [`Config`].
///
/// Empty input is NOT special-cased: no config file is equivalent to an empty
/// config object, so it still flows through the resolver and picks up the bash
/// surface default (recommended ⇒ bash on), matching the TypeScript pipeline
/// which always runs `resolveProjectOverridesForConfigure` even on `{}`.
pub fn resolve_config(tiers: &[ConfigTier]) -> ResolveResult {
resolve_config_for_harness(tiers, None)
}
/// Resolve tiers for one active harness. Each tier applies its matching harness
/// object before crossing the user/project trust boundary.
pub fn resolve_config_for_harness(
tiers: &[ConfigTier],
harness: Option<&Harness>,
) -> ResolveResult {
let mut merged = RawAftConfig::default();
let mut lsp_user_max_servers = 8;
let mut dropped = Vec::new();
let mut warnings = Vec::new();
// A name retired two or more releases ago refuses only the user config,
// which AFT rewrites itself; a project config's old names are translated
// below with a notice (see `removed_config_key_errors_for_file`).
let errors: Vec<String> = tiers
.iter()
.map(|tier| {
serde_json::from_str::<Value>(&strip_jsonc(&tier.doc))
.ok()
.and_then(|value| {
value.as_object().map(|map| {
feature_config::removed_config_key_errors_for_file(map, tier.tier == "user")
})
})
.unwrap_or_default()
})
.find(|errors| !errors.is_empty())
.unwrap_or_default();
if !errors.is_empty() {
return ResolveResult {
config: rejected_cache_config(tiers, Config::default(), &errors),
dropped,
warnings,
errors,
};
}
let mut parsed = Vec::with_capacity(tiers.len());
for tier in tiers {
let outcome = match parse_tier(tier, harness, &mut warnings, &mut dropped) {
Ok(outcome) => outcome,
Err(errors) => {
// A rejected candidate still records where caches belong, or
// that the user file leaves it unknown, so caches stay off
// rather than falling back to the storage root.
let config = cache_location_checked_config(tiers, &mut warnings);
return ResolveResult {
config: rejected_cache_config(tiers, config, &errors),
dropped,
warnings,
errors,
};
}
};
let (raw, translation) = outcome;
if translation.legacy_input {
log_retired_keys_once(tier, &translation);
}
for warning in translation.warnings {
// Migration notices are delivered once per identity by the host
// plugin or CLI; the engine only records them in its log so the
// same notice is not re-delivered on every configure. A
// superseded-legacy note describes a file that is already fixed
// (it only keeps a runtime gate), so it is logged once per process
// for the same file and text instead of on every configure.
if warning.code == "superseded_legacy_config"
&& !first_superseded_note(&tier.source, &warning.key, &warning.message)
{
continue;
}
crate::slog_info!(
"config {} [{}]: {} ({})",
tier.tier,
warning.key,
warning.message,
warning.code
);
}
parsed.push((tier, raw));
}
// The absent-base default applies exactly once, to the user base, before
// any harness override or tier merge. No user file behaves like `{}`.
let default_disabled = || {
feature_config::DEFAULT_DISABLED_TOOLS
.iter()
.map(|name| (*name).to_string())
.collect::<Vec<_>>()
};
if !parsed.iter().any(|(tier, _)| tier.tier == "user") {
merged.disabled_tools = Some(default_disabled());
}
for (tier, mut raw) in parsed {
let is_user = tier.tier == "user";
if is_user && raw.disabled_tools.is_none() {
raw.disabled_tools = Some(default_disabled());
}
let tier_kind = if is_user {
crate::bash_env::BashEnvTier::User
} else {
crate::bash_env::BashEnvTier::Project
};
let harness_refusal = apply_harness_override(
&mut raw,
harness,
tier,
is_user,
tier_kind,
&mut warnings,
&mut dropped,
);
if let Some(error) =
harness_refusal.or_else(|| raw_bash_env_refusal(&raw, tier, tier_kind, None))
{
let errors = vec![error];
return ResolveResult {
config: rejected_cache_config(tiers, Config::default(), &errors),
dropped,
warnings,
errors,
};
}
if let Some(RawEditMode::Unknown(value)) = raw.edit_mode.as_ref() {
warnings.push(ConfigWarning {
code: "invalid_edit_mode",
key: "edit_mode",
tier: tier.tier.clone(),
value: value.clone(),
message: format!("Unknown edit_mode value {value:?}; falling back to \"default\""),
});
}
if is_user {
merge_trusted_config(&mut merged, raw);
lsp_user_max_servers = merged
.lsp
.as_ref()
.and_then(|lsp| lsp.max_servers)
.unwrap_or(8);
} else {
record_project_drops(&raw, &tier.tier, &mut dropped);
record_resource_loosening(&merged, &raw, &tier.tier, &mut dropped);
merge_project_config(&mut merged, raw);
}
}
let mut config = cache_location_checked_config(tiers, &mut warnings);
if let Err(missing) = apply_resolved_config(&merged, &mut config, &mut warnings) {
return ResolveResult {
config: rejected_cache_config(tiers, config, &missing),
dropped,
warnings,
errors: missing,
};
}
config.index = resolve_index_config(merged.index.as_ref(), &mut warnings);
config.lsp_user_max_servers = Some(lsp_user_max_servers);
let cache_dir = merged.storage.and_then(|storage| storage.cache_dir);
if let Some(RawCacheDir::Dir { path: raw }) = cache_dir.as_ref() {
let home = std::env::var_os("HOME")
.or_else(|| std::env::var_os("USERPROFILE"))
.map(std::path::PathBuf::from);
match crate::config::expand_cache_dir_path(raw, home.as_deref()) {
Ok(path) => config.cache_dir = Some(path),
Err(error) => {
let path = std::path::PathBuf::from(raw);
config.cache_dir = Some(path.clone());
config.cache_unavailable = Some(error.clone());
warnings.push(crate::cache_location::unavailable_warning(&path, &error));
}
}
}
config.cache_dir_opt_out = matches!(cache_dir, Some(RawCacheDir::MainDisk {}));
config.idle = resolve_idle_config(merged.idle.as_ref(), &mut warnings);
let resolved = serde_json::to_value(&config).unwrap_or(Value::Null);
if let Err(invalid) = feature_config::validate_resolved_config(&resolved) {
return ResolveResult {
config: rejected_cache_config(tiers, config, &invalid),
dropped,
warnings,
errors: invalid,
};
}
let errors = config
.cache_config_unknown
.as_ref()
.filter(|reason| reason.contains("unknown field"))
.and_then(|reason| {
// The warning retains the source and section. Keep rejection codes
// independent of file paths so every config loader agrees on them.
let (_, detail) = reason.split_once("unknown field `")?;
let key = detail.split('`').next().unwrap_or_default();
Some(vec![format!("invalid_cache_config: unknown field `{key}`")])
})
.unwrap_or_default();
ResolveResult {
config,
dropped,
warnings,
errors,
}
}
/// A default config carrying the user tier's cache-location verdict: when the
/// user file is unreadable or its storage section invalid, the cache location
/// is unknown and a `cache_dir_config_unknown` warning says so.
fn cache_location_checked_config(
tiers: &[ConfigTier],
warnings: &mut Vec<ConfigWarning>,
) -> Config {
let mut config = Config::default();
config.cache_config_unknown = tiers
.iter()
.filter(|tier| tier.tier == "user")
.find_map(cache_location_config_error);
if let Some(reason) = &config.cache_config_unknown {
warnings.push(ConfigWarning {
code: "cache_dir_config_unknown", key: "storage.cache_dir", tier: "user".into(),
value: "unknown".into(),
message: format!("User configuration is unreadable or invalid ({reason}); AFT is running without its caches until the configuration is valid."),
});
}
config
}
fn rejected_cache_config(tiers: &[ConfigTier], mut config: Config, errors: &[String]) -> Config {
if config.cache_dir.is_none() {
// Read only `storage.cache_dir` from the user document itself: the
// candidate was rejected, possibly for another section, so the tier
// as a whole may not parse.
let mut choice = None;
for tier in tiers.iter().filter(|tier| tier.tier == "user") {
if let Some(next) = serde_json::from_str::<Value>(&strip_jsonc(&tier.doc))
.ok()
.and_then(|doc| {
parse_cache_dir(doc.get("storage")?.get("cache_dir").cloned()?).ok()
})
{
merge_cache_dir(&mut choice, next);
}
}
match choice {
Some(RawCacheDir::Dir { path: raw }) => {
let home = std::env::var_os("HOME")
.or_else(|| std::env::var_os("USERPROFILE"))
.map(std::path::PathBuf::from);
config.cache_dir = Some(
crate::config::expand_cache_dir_path(&raw, home.as_deref())
.unwrap_or_else(|_| std::path::PathBuf::from(raw)),
);
}
Some(RawCacheDir::MainDisk {}) => config.cache_dir_opt_out = true,
Some(RawCacheDir::Default {}) | None => {}
}
}
config
.cache_config_unknown
.get_or_insert_with(|| format!("configuration rejected: {}", errors.join(", ")));
config
}
/// Resolve raw config tiers into the core-domain config and RESET it onto an
/// existing `base`, preserving only `base`'s process-state fields (storage_dir,
/// harness, lsp_paths_extra, bash_permissions, …). This is the configure-path
/// entry.
///
/// RESET, not overlay: the core-domain config is rebuilt from DEFAULT + the
/// supplied tiers, so a field absent from the tiers returns to its default —
/// it NEVER keeps `base`'s prior value. This closes a cross-bind privilege
/// escalation: under the subc daemon a single `AppContext` per project root is
/// shared across harness identities, and `configure` seeds `base` from the
/// previous bind's config. With the old overlay semantics, a later low-trust
/// bind (e.g. `mcp:*` or `fed:*`) that omitted a field inherited an earlier high-trust
/// bind's capability for it (confirmed on the wire: `url_fetch_allow_private`
/// SSRF, and `lsp_servers` arbitrary-binary). Reset-onto-default makes the
/// resolved core config a pure function of this bind's own tiers and harness.
///
/// Parity-safe by construction: this routes through [`resolve_config_for_harness`]
/// (the same harness-aware path the cross-language parity gate validates), which builds onto
/// `Config::default()` — so reset-onto-default == overlay-onto-default there and
/// no parity/unit fixture changes. Only this configure path, seeded from a prior
/// config, changes behavior — which is exactly the leak site.
///
/// Process-state fields are not part of `RawAftConfig`; they are carried from
/// `base` here and re-applied by `handle_configure`'s flat-param parsing
/// afterwards, so plugin-mode behavior is unchanged (the plugin re-sends them on
/// every configure). They are also unreachable as a subc escalation vector: a
/// subc RouteBind sends only `config:[tiers]`, never the flat process-state
/// params, so they stay at default for every subc bind regardless.
pub fn resolve_config_onto(tiers: &[ConfigTier], base: &mut Config) -> Vec<DroppedKey> {
resolve_config_onto_with_diagnostics(tiers, base).dropped
}
/// Resolve configuration for the active harness into `base`, replacing
/// configurable fields while retaining fields that describe the running process.
pub fn resolve_config_onto_for_harness(
tiers: &[ConfigTier],
harness: &Harness,
base: &mut Config,
) -> Vec<DroppedKey> {
resolve_config_onto_with_diagnostics_for_harness(tiers, Some(harness), base).dropped
}
/// Reset a runtime config while retaining both trust-boundary drops and
/// non-fatal value warnings for the configure response.
pub fn resolve_config_onto_with_diagnostics(
tiers: &[ConfigTier],
base: &mut Config,
) -> ResolveDiagnostics {
resolve_config_onto_with_diagnostics_for_harness(tiers, None, base)
}
/// Harness-aware variant of [`resolve_config_onto_with_diagnostics`].
pub fn resolve_config_onto_with_diagnostics_for_harness(
tiers: &[ConfigTier],
harness: Option<&Harness>,
base: &mut Config,
) -> ResolveDiagnostics {
let ResolveResult {
mut config,
dropped,
warnings,
errors,
} = resolve_config_for_harness(tiers, harness);
if !errors.is_empty() {
// A rejected candidate never publishes: the caller keeps its last-good
// configuration.
return ResolveDiagnostics {
dropped,
warnings,
errors,
};
}
carry_process_state(base, &mut config);
*base = config;
ResolveDiagnostics {
dropped,
warnings,
errors,
}
}
/// Carry the process-state (non-`RawAftConfig`) fields from `base` onto a
/// freshly-resolved core config. EVERY `Config` field not copied here is
/// core-domain and intentionally comes from the resolved tiers (reset). Keeping
/// this list complete is load-bearing: a core field accidentally copied here
/// would re-introduce cross-bind inheritance for it.
fn carry_process_state(base: &Config, resolved: &mut Config) {
resolved.project_root = base.project_root.clone();
resolved.harness = base.harness.clone();
resolved.validation_depth = base.validation_depth;
resolved.checkpoint_ttl_hours = base.checkpoint_ttl_hours;
resolved.max_symbol_depth = base.max_symbol_depth;
resolved.diagnostic_cache_size = base.diagnostic_cache_size;
resolved.max_background_bash_tasks = base.max_background_bash_tasks;
resolved.bash_permissions = base.bash_permissions;
resolved.search_index_max_file_size = base.search_index_max_file_size;
resolved.storage_dir = base.storage_dir.clone();
resolved.storage_lease = base.storage_lease.clone();
resolved.lsp_paths_extra = base.lsp_paths_extra.clone();
resolved.lsp_auto_install_binaries = base.lsp_auto_install_binaries.clone();
resolved.lsp_inflight_installs = base.lsp_inflight_installs.clone();
}
/// Log, once per config file and set of retired and removed keys in this
/// process, that a tier's retired keys were translated in memory and which
/// removed keys it still sets. Reloads and repeated binds of the same root
/// therefore do not repeat it. The host plugin delivers the user-facing
/// notice; the user file's automatic rewrite reports its own.
fn log_retired_keys_once(tier: &ConfigTier, translation: &feature_config::DocumentTranslation) {
let keys = translation
.retired_keys
.iter()
.cloned()
.collect::<Vec<_>>()
.join(", ");
if !first_superseded_note(&tier.source, "retired_keys", &keys) {
return;
}
let notice = if tier.tier == "user" {
let mut parts = Vec::new();
if translation.legacy_input {
parts.push(format!(
"{} uses retired keys ({}); AFT applied their current equivalents in memory",
tier.source,
translation.retired_keys.join(", ")
));
}
parts.retain(|part| !part.is_empty());
parts.join(". ")
} else {
feature_config::project_retired_keys_notice(&tier.source, translation)
};
crate::slog_warn!("config {}: {}", tier.tier, notice);
}
/// Whether this note (keyed by file, key and text) is new to this process.
fn first_superseded_note(source: &str, key: &str, message: &str) -> bool {
static SEEN: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> =
std::sync::OnceLock::new();
SEEN.get_or_init(Default::default)
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(format!("{source}\u{0}{key}\u{0}{message}"))
}
fn parse_tier(
tier: &ConfigTier,
harness: Option<&Harness>,
warnings: &mut Vec<ConfigWarning>,
dropped: &mut Vec<DroppedKey>,
) -> Result<(RawAftConfig, feature_config::DocumentTranslation), Vec<String>> {
let stripped = strip_jsonc(&tier.doc);
let value = serde_json::from_str::<Value>(&stripped)
.map_err(|_| vec!["invalid_config_document".to_string()])?;
let Value::Object(mut map) = value else {
return Err(vec!["invalid_config_document".to_string()]);
};
// Retired keys are translated on the raw document, before the strict
// schema sees it, so they never reach `RawAftConfig`; the names retired in
// 0.62 or earlier were already refused by `removed_config_key_errors`. Only the user
// tier's base block may receive the absent-base default disables.
let document_tier = if tier.tier == "user" {
feature_config::DocumentTier::User
} else {
feature_config::DocumentTier::Project
};
let translation = feature_config::translate_document(&mut map, document_tier);
// Machine limits cannot be selected by repositories or harness blocks.
// Drop even malformed values before validating neighbouring security keys.
if tier.tier != "user" && map.remove("memory").is_some() {
push_drop(dropped, "memory", &tier.tier, USER_ONLY_REASON);
}
if let Some(blocks) = map.get_mut("harnesses").and_then(Value::as_object_mut) {
for block in blocks.values_mut().filter_map(Value::as_object_mut) {
if block.remove("memory").is_some() {
push_drop(dropped, "memory", &tier.tier, USER_ONLY_REASON);
}
}
}
normalize_config_for_harness(&mut map, harness);
let security_errors = malformed_security_config_errors(&map, harness);
if !security_errors.is_empty() {
return Err(security_errors);
}
if let Some(path) = feature_config::settings_shape::null_path(&map) {
return Err(vec![format!("invalid_config_null:{path}")]);
}
if tier.tier == "user" {
let malformed_choice = |block: &Map<String, Value>| {
block
.get("storage")
.and_then(|storage| storage.get("cache_dir"))
.filter(|choice| choice.is_object())
.is_some_and(|choice| {
serde_json::from_value::<RawCacheDir>(choice.clone()).is_err()
})
};
if malformed_choice(&map)
|| map
.get("harnesses")
.and_then(Value::as_object)
.is_some_and(|blocks| {
blocks
.values()
.filter_map(Value::as_object)
.any(malformed_choice)
})
{
return Err(vec!["invalid_cache_config: storage.cache_dir".into()]);
}
}
let raw = match serde_json::from_value::<RawAftConfig>(Value::Object(map.clone())) {
Ok(config) => config,
Err(_) => parse_config_partially(map, tier, warnings),
};
Ok((raw, translation))
}
// Mirror the host-owned lists in packages/aft-bridge/src/config-keys.ts.
const OPENCODE_ONLY_CONFIG_KEYS: &[&str] = &["auto_update"];
const PI_ONLY_CONFIG_KEYS: &[&str] = &[];
fn harness_ignored_config_keys(harness: Option<&Harness>) -> &'static [&'static str] {
match harness {
Some(Harness::Pi) => OPENCODE_ONLY_CONFIG_KEYS,
Some(Harness::Opencode) => PI_ONLY_CONFIG_KEYS,
_ => &[],
}
}
fn normalize_config_for_harness(map: &mut Map<String, Value>, harness: Option<&Harness>) {
let ignored = harness_ignored_config_keys(harness);
for key in ignored {
map.remove(*key);
}
let Some(harness) = harness else { return };
let Some(block) = map
.get_mut("harnesses")
.and_then(Value::as_object_mut)
.and_then(|blocks| blocks.get_mut(&harness.wire_label()))
.and_then(Value::as_object_mut)
else {
return;
};
// Remove ignored fields before validation so valid security settings in the
// same active harness block are preserved.
// Other harness blocks remain opaque, just as they do in the host plugins.
for key in ignored {
block.remove(*key);
}
}
// `storage` is deliberately not listed: a malformed `storage.cache_dir` weakens
// no protection; it turns caches off (`cache_config_unknown`) and warns.
fn security_config_section(key: &str, harness: Option<&Harness>) -> bool {
if harness_ignored_config_keys(harness).contains(&key) {
return false;
}
matches!(
key,
"restrict_to_project_root"
| "url_fetch_allow_private"
| "sandbox"
| "indexes"
| "index"
| "remote_exec"
| "disabled_tools"
| "bash"
| "lsp"
| "semantic"
| "search"
| "subc"
| "opencode"
| "github"
| "gh_shim"
| "auto_update"
)
}
fn malformed_security_config_errors(
map: &Map<String, Value>,
harness: Option<&Harness>,
) -> Vec<String> {
let mut errors = Vec::new();
for (key, value) in map {
if !security_config_section(key, harness) {
continue;
}
let mut field = Map::new();
field.insert(key.clone(), value.clone());
if value.is_null() || serde_json::from_value::<RawAftConfig>(Value::Object(field)).is_err()
{
errors.push(format!("invalid_security_config:{key}"));
}
}
if let Some(harness) = harness {
let label = harness.wire_label();
if let Some(blocks) = map.get("harnesses") {
match blocks.as_object() {
None => errors.push("invalid_security_config:harnesses".into()),
Some(blocks) => {
if let Some(block) = blocks.get(&label) {
if let Some(block) = block.as_object() {
let mut block = block.clone();
block.remove("harnesses");
let invalid: Vec<_> = block
.iter()
.filter_map(|(key, value)| {
let mut field = Map::new();
field.insert(key.clone(), value.clone());
(value.is_null()
|| serde_json::from_value::<RawAftConfig>(Value::Object(
field,
))
.is_err())
.then_some(key)
})
.collect();
let invalid_security: Vec<_> = invalid
.iter()
.filter(|key| security_config_section(key, Some(harness)))
.collect();
if !invalid_security.is_empty() {
errors.extend(invalid_security.into_iter().map(|key| {
format!("invalid_security_config:harnesses.{label}.{key}")
}));
} else if !invalid.is_empty()
&& block
.keys()
.any(|key| security_config_section(key, Some(harness)))
{
// A strict harness parse would discard the whole block,
// including its otherwise-valid explicit hardening.
errors.push(format!("invalid_security_config:harnesses.{label}"));
}
} else {
errors.push(format!("invalid_security_config:harnesses.{label}"));
}
}
}
}
}
}
errors.sort();
errors.dedup();
errors
}
fn parse_cache_dir(value: Value) -> serde_json::Result<RawCacheDir> {
let canonical = feature_config::settings_shape::cache_dir_replacement(&value)
.map_or(value, |(replacement, _)| replacement);
serde_json::from_value(canonical)
}
fn merge_cache_dir(base: &mut Option<RawCacheDir>, next: RawCacheDir) {
// When multiple user tiers are supplied, a path used to take precedence
// over a null opt-out, and an omitted setting never hid either choice.
if base.is_none()
|| matches!(next, RawCacheDir::Dir { .. })
|| (matches!(next, RawCacheDir::MainDisk {})
&& !matches!(base, Some(RawCacheDir::Dir { .. })))
{
*base = Some(next);
}
}
/// Recognize storage-section typos without making unrelated user keys strict.
pub(crate) fn storage_like_key(key: &str, value: Option<&Value>) -> bool {
// This is a distinct process-state field, not a misspelled cache selector.
if key == "storage_dir" {
return false;
}
let normalized: String = key
.chars()
.filter(char::is_ascii_alphanumeric)
.map(|c| c.to_ascii_lowercase())
.collect();
if normalized.starts_with("storage") || matches!(normalized.as_str(), "cachedir" | "cacheroot")
{
return true;
}
if value
.and_then(Value::as_object)
.is_some_and(|fields| fields.contains_key("cache_dir"))
{
return true;
}
let target = b"storage";
if normalized.len().abs_diff(target.len()) > 2 {
return false;
}
let mut row: Vec<usize> = (0..=target.len()).collect();
for (i, byte) in normalized.bytes().enumerate() {
let mut next = vec![i + 1];
for (j, expected) in target.iter().enumerate() {
next.push(
(row[j] + usize::from(byte != *expected))
.min(row[j + 1] + 1)
.min(next[j] + 1),
);
}
row = next;
}
row[target.len()] <= 2
}
/// Why a user tier leaves its cache location unknown. Storage sections and
/// storage-like typos fail closed; unrelated unknown keys retain partial parsing.
pub fn cache_location_config_error(tier: &ConfigTier) -> Option<String> {
let stripped = strip_jsonc(&tier.doc);
let value = match serde_json::from_str::<Value>(&stripped) {
Ok(value) => value,
Err(error) => return Some(format!("{} does not parse: {error}", tier.source)),
};
let Value::Object(map) = value else {
return Some(format!("{} is not a JSON object", tier.source));
};
if let Some(error) = feature_config::removed_config_key_errors(&map)
.into_iter()
.find(|error| error.contains("storage"))
{
return Some(format!(
"{} has a removed storage setting: {error}",
tier.source
));
}
let unknown_key = |map: &Map<String, Value>| -> Option<String> {
let mut map = map.clone();
feature_config::translate_document(&mut map, feature_config::DocumentTier::User);
map.keys().find_map(|key| {
// Validate the name independently of its value: an invalid known
// setting must not hide a misspelled storage key later in the file.
let field = Map::from_iter([(key.clone(), Value::Null)]);
serde_json::from_value::<RawAftConfig>(Value::Object(field))
.err()
.map(|error| error.to_string())
.filter(|error| {
error.starts_with("unknown field") && storage_like_key(key, map.get(key))
})
})
};
if let Some(error) = unknown_key(&map) {
return Some(format!("{} has an invalid setting: {error}", tier.source));
}
// Stricter than the resolver's RawStorage: a misspelled key inside
// storage (for example `cachedir`) would otherwise leave cache_dir unset
// and quietly put caches back on the storage root.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(dead_code)]
struct StrictStorage {
cache_dir: Option<RawCacheDir>,
}
let invalid_storage = |section: &Value| -> Option<String> {
if section.is_null() {
return None;
}
if let Some(key) = section
.as_object()
.and_then(|fields| fields.keys().find(|key| key.as_str() != "cache_dir"))
{
return Some(format!("unknown field `{key}`, expected `cache_dir`"));
}
let mut section = section.clone();
if let Some(cache_dir) = section.get_mut("cache_dir") {
if let Some((replacement, _)) =
feature_config::settings_shape::cache_dir_replacement(cache_dir)
{
*cache_dir = replacement;
}
}
serde_json::from_value::<StrictStorage>(section)
.err()
.map(|error| error.to_string())
};
if let Some(error) = map.get("storage").and_then(invalid_storage) {
return Some(format!(
"{} has an invalid storage section: {error}",
tier.source
));
}
if let Some(Value::Object(harnesses)) = map.get("harnesses") {
for (name, block) in harnesses {
if let Some(error) = block.as_object().and_then(unknown_key) {
return Some(format!(
"{} has an invalid harnesses.{name} setting: {error}",
tier.source
));
}
if let Some(error) = block.get("storage").and_then(invalid_storage) {
return Some(format!(
"{} has an invalid harnesses.{name}.storage section: {error}",
tier.source
));
}
}
}
None
}
/// Return why a tier would be accepted only by the lenient resolver, or
/// `None` when it passes strict validation.
///
/// Initial configuration rejects malformed security-sensitive settings and
/// reports discarded nonsecurity settings. A live reload rejects every schema
/// error: a typo must not reset
/// a key (possibly a security key the harness block set) to its default while
/// the root stays bound, so the reload calls this first and keeps the last
/// valid configuration instead. Names retired in 0.62 or earlier are refused,
/// and the more recently retired keys are translated first, exactly as the
/// resolver translates them, so they never count as invalid here.
pub fn strict_tier_error(tier: &ConfigTier, harness: Option<&Harness>) -> Option<String> {
let stripped = strip_jsonc(&tier.doc);
let value = match serde_json::from_str::<Value>(&stripped) {
Ok(value) => value,
Err(error) => return Some(format!("{} does not parse: {error}", tier.source)),
};
let Value::Object(mut map) = value else {
return Some(format!("{} is not a JSON object", tier.source));
};
// As in resolution, a long-retired name refuses only the user config.
let removed = feature_config::removed_config_key_errors_for_file(&map, tier.tier == "user");
if !removed.is_empty() {
return Some(removed.join(", "));
}
let document_tier = if tier.tier == "user" {
feature_config::DocumentTier::User
} else {
feature_config::DocumentTier::Project
};
feature_config::translate_document(&mut map, document_tier);
normalize_config_for_harness(&mut map, harness);
if let Some(path) = feature_config::settings_shape::null_path(&map) {
return Some(format!("invalid_config_null:{path}"));
}
let raw = match serde_json::from_value::<RawAftConfig>(Value::Object(map)) {
Ok(raw) => raw,
Err(error) => {
return Some(format!("{} has an invalid setting: {error}", tier.source));
}
};
// A refused name rejects the candidate at either tier, whether or not a
// project is trusted: a silently dropped variable is exactly the failure
// mode this list exists to prevent.
let tier_kind = if tier.tier == "user" {
crate::bash_env::BashEnvTier::User
} else {
crate::bash_env::BashEnvTier::Project
};
// The block for the active harness is applied on top of this tier, so it
// must be as valid as the tier itself. Blocks for other harnesses are
// never applied here and stay unchecked, as at connect.
let harness_context = harness.map(|harness| {
let label = harness.wire_label();
let block = raw
.harnesses
.as_ref()
.and_then(|blocks| blocks.get(&label))
.cloned();
(label, block)
});
// A refusal written in the applied harness block is the one to report: it
// names the block that actually carries the name.
let harness_refusal = match harness_context.as_ref() {
Some((label, Some(Value::Object(block)))) => {
let mut block = block.clone();
// A nested `harnesses` key is ignored with a warning at connect.
block.remove("harnesses");
match serde_json::from_value::<RawAftConfig>(Value::Object(block)) {
Ok(parsed) => raw_bash_env_refusal(&parsed, tier, tier_kind, Some(label)),
Err(_) => None,
}
}
_ => None,
};
let base_refusal = raw_bash_env_refusal(&raw, tier, tier_kind, None);
harness_refusal.or(base_refusal)
}
/// The refusal for a `bash.env` name the tier may not set. The message names
/// the key so the author can fix the file: this check runs for every tier and
/// whether or not the project is trusted.
fn refused_bash_env_error(
tier: &ConfigTier,
tier_kind: crate::bash_env::BashEnvTier,
key: &str,
harness_label: Option<&str>,
) -> String {
let where_set = match harness_label {
Some(label) => format!(" in harnesses.{label}"),
None => String::new(),
};
let scope = match tier_kind {
crate::bash_env::BashEnvTier::User => "cannot be configured",
crate::bash_env::BashEnvTier::Project => {
"cannot be configured by a project; set it in user config if you need it"
}
};
format!(
"{} has blocked bash.env key {key}{where_set}; environment startup hooks, lookup roots, interpreter injectors, Git redirection, AFT controls, sandbox controls and credentials {scope}",
tier.source
)
}
/// Refuse a `bash.env` name of the given tier (base block or active harness
/// block). Project values are validated even when the project is untrusted, so
/// a bad commit fails for its author at once rather than on the first machine
/// that trusts it.
fn raw_bash_env_refusal(
raw: &RawAftConfig,
tier: &ConfigTier,
tier_kind: crate::bash_env::BashEnvTier,
harness_label: Option<&str>,
) -> Option<String> {
let env = match raw.bash.as_ref() {
Some(features) => features.env.as_ref(),
_ => None,
};
let found = crate::bash_env::first_refused_env_key(env?, tier_kind);
let key = found?;
Some(refused_bash_env_error(tier, tier_kind, key, harness_label))
}
fn parse_config_partially(
raw_config: Map<String, Value>,
tier: &ConfigTier,
warnings: &mut Vec<ConfigWarning>,
) -> RawAftConfig {
let mut partial = RawAftConfig::default();
for (key, value) in raw_config {
let mut one_field = Map::new();
one_field.insert(key.clone(), value);
if let Ok(section) = serde_json::from_value::<RawAftConfig>(Value::Object(one_field)) {
merge_trusted_config(&mut partial, section);
} else {
warnings.push(ConfigWarning {
code: "invalid_config_section",
key: "config",
tier: tier.tier.clone(),
value: "[discarded]".into(),
message: format!("Discarded invalid configuration section: {key}"),
});
}
}
partial
}
/// Apply one tier's harness block on top of its base and return the refusal
/// for a `bash.env` name the tier may not set in that block.
///
/// The block is checked before the project trust boundary strips its map: a
/// refused name must reject the candidate at the tier it was written at, and a
/// project harness block must not borrow the user tier's strength.
fn apply_harness_override(
raw: &mut RawAftConfig,
harness: Option<&Harness>,
tier: &ConfigTier,
trusted: bool,
tier_kind: crate::bash_env::BashEnvTier,
warnings: &mut Vec<ConfigWarning>,
dropped: &mut Vec<DroppedKey>,
) -> Option<String> {
let Some(overrides) = raw.harnesses.take() else {
return None;
};
let Some(harness) = harness else {
return None;
};
let key = harness.wire_label();
let Some(value) = overrides.get(&key) else {
return None;
};
let Value::Object(mut override_map) = value.clone() else {
warnings.push(ConfigWarning {
code: "invalid_harness_override",
key: "harnesses",
tier: tier.tier.clone(),
value: key,
message: "Ignoring non-object harness override; overrides must be config objects"
.to_string(),
});
return None;
};
if override_map.remove("harnesses").is_some() {
warnings.push(ConfigWarning {
code: "nested_harnesses_ignored",
key: "harnesses",
tier: tier.tier.clone(),
value: key.clone(),
message: format!(
"Ignoring nested harnesses in harnesses.{key}; harness overrides cannot recurse"
),
});
}
normalize_config_for_harness(&mut override_map, Some(harness));
// The block is refused at the tier it was written at, whether or not the
// project is trusted, and before the trust boundary below strips the map.
let refusal = serde_json::from_value::<RawAftConfig>(Value::Object(override_map.clone()))
.ok()
.and_then(|parsed| raw_bash_env_refusal(&parsed, tier, tier_kind, Some(&key)));
match serde_json::from_value::<RawAftConfig>(Value::Object(override_map)) {
Ok(mut override_config) => {
if override_config
.durability
.take()
.is_some_and(|durability| durability.macos_full_sync.is_some())
{
push_drop(
dropped,
"durability.macos_full_sync",
&tier.tier,
"sync policy is process-wide; only the user-tier base may set it",
);
}
if override_config
.storage
.take()
.is_some_and(|storage| storage.cache_dir.is_some())
{
push_drop(
dropped,
"storage.cache_dir",
&tier.tier,
"cache location is storage-wide; only the user-tier base may set it",
);
}
// A project harness block, like the project base, may only turn an
// index off; a user harness block overrides the user base.
let override_indexes = override_config.indexes.take();
merge_trusted_config(raw, override_config);
raw.indexes = merge_indexes(raw.indexes, override_indexes, !trusted);
}
Err(_) => warnings.push(ConfigWarning {
code: "invalid_harness_override",
key: "harnesses",
tier: tier.tier.clone(),
value: key,
message: "Ignoring invalid harness override; it must use the root config shape"
.to_string(),
}),
}
refusal
}
fn merge_trusted_config(base: &mut RawAftConfig, override_config: RawAftConfig) {
if override_config.shell.is_some() {
base.shell = override_config.shell.clone();
}
if let Some(value) = override_config
.durability
.and_then(|durability| durability.macos_full_sync)
{
base.durability
.get_or_insert_with(RawDurability::default)
.macos_full_sync = Some(value);
}
if let Some(choice) = override_config
.storage
.and_then(|storage| storage.cache_dir)
{
merge_cache_dir(
&mut base
.storage
.get_or_insert_with(RawStorage::default)
.cache_dir,
choice,
);
}
if override_config.harnesses.is_some() {
base.harnesses = override_config.harnesses.clone();
}
if override_config.schema.is_some() {
base.schema = override_config.schema;
}
if override_config.edit_mode.is_some() {
base.edit_mode = override_config.edit_mode;
}
if override_config.format_on_edit.is_some() {
base.format_on_edit = override_config.format_on_edit;
}
if override_config.revision_reads.is_some() {
base.revision_reads = override_config.revision_reads;
}
if override_config.formatter_timeout_secs.is_some() {
base.formatter_timeout_secs = override_config.formatter_timeout_secs;
}
if override_config.type_checker_timeout_secs.is_some() {
base.type_checker_timeout_secs = override_config.type_checker_timeout_secs;
}
if override_config.validate_on_edit.is_some() {
base.validate_on_edit = override_config.validate_on_edit;
}
if override_config.formatter.is_some() {
base.formatter = override_config.formatter;
}
if override_config.checker.is_some() {
base.checker = override_config.checker;
}
if override_config.configure_warnings_delivery.is_some() {
base.configure_warnings_delivery = override_config.configure_warnings_delivery;
}
// Disables only accumulate: a harness block adds to its base list and can
// never re-enable a base disable.
union_disabled_tools(&mut base.disabled_tools, override_config.disabled_tools);
if override_config.restrict_to_project_root.is_some() {
base.restrict_to_project_root = override_config.restrict_to_project_root;
}
base.indexes = merge_indexes(base.indexes, override_config.indexes, false);
if override_config.index.is_some() {
base.index = override_config.index;
}
if override_config.memory.is_some() {
base.memory = override_config.memory;
}
if override_config.inspect.is_some() {
base.inspect = override_config.inspect;
}
if override_config.idle.is_some() {
// Per key, so a harness block that sets one idle window keeps the
// other window from the file's base block.
base.idle = merge_idle_config(base.idle.take(), override_config.idle);
}
if override_config.backup.is_some() {
base.backup = override_config.backup;
}
if override_config.github.is_some() {
base.github = override_config.github;
}
if override_config.gh_shim.is_some() {
base.gh_shim = override_config.gh_shim;
}
if override_config.git.is_some() {
base.git = override_config.git;
}
if override_config.pi.is_some() {
base.pi = override_config.pi;
}
if let Some(next) = override_config.sandbox {
let sandbox = base.sandbox.get_or_insert_with(RawSandbox::default);
if let Some(next) = next.profile {
let profile = sandbox.profile.get_or_insert_with(RawSandboxRoles::default);
if next.worker.is_some() {
profile.worker = next.worker;
}
if next.head.is_some() {
profile.head = next.head;
}
}
if next.write_allow.is_some() {
sandbox.write_allow = next.write_allow;
}
if next.read_deny.is_some() {
sandbox.read_deny = next.read_deny;
}
}
if override_config.bash.is_some() {
// A harness block merges its `bash.env` names into the base block
// instead of replacing it, so adding one name under
// `harnesses.<name>` cannot silently drop every base name. A project
// harness block is only looked at after this tier's own trust boundary,
// so a strength reserved for the user tier cannot be borrowed through
// `harnesses`. A name the boundary strips is still refused by
// `raw_bash_env_refusal` before this merge.
base.bash = merge_bash_config(base.bash.take(), override_config.bash);
}
if override_config.experimental.is_some() {
base.experimental = override_config.experimental;
}
if override_config.lsp.is_some() {
base.lsp = override_config.lsp;
}
if override_config.url_fetch_allow_private.is_some() {
base.url_fetch_allow_private = override_config.url_fetch_allow_private;
}
if override_config.semantic.is_some() {
base.semantic = override_config.semantic;
}
if override_config.search.is_some() {
base.search = override_config.search;
}
if override_config.auto_update.is_some() {
base.auto_update = override_config.auto_update;
}
if override_config.bridge.is_some() {
base.bridge = override_config.bridge;
}
if override_config.subc.is_some() {
base.subc = override_config.subc;
}
if let Some(remote_exec) = override_config.remote_exec {
let merged = base.remote_exec.get_or_insert_with(RawRemoteExec::default);
if remote_exec.enabled.is_some() {
merged.enabled = remote_exec.enabled;
}
if remote_exec.default_demand.is_some() {
merged.default_demand = remote_exec.default_demand;
}
}
}
fn merge_project_config(base: &mut RawAftConfig, project: RawAftConfig) {
// Project-safe shallow top-level fields.
if project.edit_mode.is_some() {
base.edit_mode = project.edit_mode;
}
if project.format_on_edit.is_some() {
base.format_on_edit = project.format_on_edit;
}
// Reading git objects of the session's own repository grants nothing the
// read permission rules do not already allow, so a project may opt in.
if project.revision_reads.is_some() {
base.revision_reads = project.revision_reads;
}
if project.validate_on_edit.is_some() {
base.validate_on_edit = project.validate_on_edit;
}
if project.configure_warnings_delivery.is_some() {
base.configure_warnings_delivery = project.configure_warnings_delivery;
}
// A project may switch an index off but never back on.
base.indexes = merge_indexes(base.indexes, project.indexes, true);
merge_formatter_map(&mut base.formatter, project.formatter);
merge_checker_map(&mut base.checker, project.checker);
merge_disabled_tools(&mut base.disabled_tools, project.disabled_tools);
base.semantic = merge_semantic_config(base.semantic.take(), project.semantic);
base.search = merge_project_search(base.search.take(), project.search);
base.lsp = merge_lsp_config(base.lsp.take(), project.lsp);
base.experimental = merge_experimental_config(base.experimental.take(), project.experimental);
let ceiling = base.bash.as_ref().and_then(|bash| bash.memory_limit_mib);
let mut project_bash = project_safe_bash(project.bash);
if let Some(features) = &mut project_bash {
features.memory_limit_mib = match (ceiling, features.memory_limit_mib) {
(Some(user), Some(project)) => Some(user.min(project)),
(_, value) => value,
};
}
base.bash = merge_bash_config(base.bash.take(), project_bash);
base.inspect = merge_inspect_config(base.inspect.take(), project.inspect);
base.idle = merge_idle_config(base.idle.take(), project.idle);
base.backup = merge_project_backup_config(base.backup.take(), project.backup);
if project.git.is_some() {
base.git = project.git;
}
base.pi = merge_pi_config(base.pi.take(), project.pi);
base.sandbox = merge_project_sandbox(base.sandbox.take(), project.sandbox);
// A project may turn remote runs off for itself, never on: running a
// repository's commands on a shared build server is the user's decision.
if project
.remote_exec
.as_ref()
.is_some_and(|remote| remote.enabled == Some(false))
{
base.remote_exec_project_off = true;
}
}
/// A project may set `search.rerank.backend` to `"off"` and nothing else;
/// `record_project_drops` reports every other value it supplied.
fn merge_project_search(base: Option<RawSearch>, project: Option<RawSearch>) -> Option<RawSearch> {
let disables = project
.and_then(|search| search.rerank)
.is_some_and(|rerank| rerank.backend == Some(RerankBackendKind::Off));
if !disables {
return base;
}
let mut search = base.unwrap_or_default();
search.rerank.get_or_insert_with(RawRerank::default).backend = Some(RerankBackendKind::Off);
Some(search)
}
/// Carry the parsed `search` block into the runtime config unchanged. An
/// all-empty `rerank` object is kept as absent so it serializes the same as no
/// block at all.
fn resolve_search_config(raw: Option<&RawSearch>) -> SearchConfig {
let rerank = raw
.and_then(|search| search.rerank.as_ref())
.map(|rerank| RerankConfig {
backend: rerank.backend,
model: rerank.model.clone(),
endpoint: rerank.endpoint.clone(),
api_key_env: rerank.api_key_env.clone(),
top_n: rerank.top_n,
timeout_ms: rerank.timeout_ms,
});
SearchConfig {
rerank: rerank.filter(|rerank| *rerank != RerankConfig::default()),
}
}
fn merge_project_backup_config(
base: Option<RawBackup>,
project: Option<RawBackup>,
) -> Option<RawBackup> {
let Some(project_max_file_size) = project.and_then(|backup| backup.max_file_size) else {
return base;
};
let mut backup = base.unwrap_or_default();
backup.max_file_size = Some(project_max_file_size);
Some(backup)
}
fn merge_project_sandbox(
base: Option<RawSandbox>,
project: Option<RawSandbox>,
) -> Option<RawSandbox> {
let Some(project) = project else {
return base;
};
let mut sandbox = base.unwrap_or_default();
if let Some(project_denies) = project.read_deny {
let denies = sandbox.read_deny.get_or_insert_with(Vec::new);
for path in project_denies {
if !denies.contains(&path) {
denies.push(path);
}
}
}
if let Some(next) = project.profile {
let floor = resolve_sandbox_config(Some(&sandbox)).profile;
let profile = sandbox.profile.get_or_insert_with(RawSandboxRoles::default);
if let Some(worker) = next.worker.filter(|value| *value >= floor.worker) {
profile.worker = Some(worker);
}
if let Some(head) = next.head.filter(|value| *value >= floor.head) {
profile.head = Some(head);
}
}
(sandbox.profile.is_some() || sandbox.write_allow.is_some() || sandbox.read_deny.is_some())
.then_some(sandbox)
}
fn merge_formatter_map(
base: &mut Option<HashMap<String, RawFormatter>>,
override_map: Option<HashMap<String, RawFormatter>>,
) {
let Some(override_map) = override_map else {
return;
};
if override_map.is_empty() && base.as_ref().is_none_or(HashMap::is_empty) {
return;
}
let target = base.get_or_insert_with(HashMap::new);
target.extend(override_map);
}
fn merge_checker_map(
base: &mut Option<HashMap<String, RawChecker>>,
override_map: Option<HashMap<String, RawChecker>>,
) {
let Some(override_map) = override_map else {
return;
};
if override_map.is_empty() && base.as_ref().is_none_or(HashMap::is_empty) {
return;
}
let target = base.get_or_insert_with(HashMap::new);
target.extend(override_map);
}
fn merge_disabled_tools(base: &mut Option<Vec<String>>, override_tools: Option<Vec<String>>) {
// Project disables of protected slots (aft_safety and the seven host tool
// names) are ignored; `record_project_drops` reports them.
union_disabled_tools(
base,
override_tools.map(|tools| {
tools
.into_iter()
.filter(|tool| !feature_config::is_project_protected_tool(tool))
.collect()
}),
);
}
/// Union two raw disabled lists, preserving presence: an explicit empty list
/// on either side yields an explicit (possibly empty) result.
fn union_disabled_tools(base: &mut Option<Vec<String>>, override_tools: Option<Vec<String>>) {
let Some(override_tools) = override_tools else {
return;
};
let mut merged = base.take().unwrap_or_default();
merged.extend(override_tools);
*base = Some(feature_config::normalize_tool_list(merged));
}
/// Merge index switches. Trusted overrides replace each supplied leaf;
/// restricted (project) overrides can only turn a leaf off.
fn merge_indexes(
base: Option<RawIndexes>,
override_indexes: Option<RawIndexes>,
restricted: bool,
) -> Option<RawIndexes> {
let Some(override_indexes) = override_indexes else {
return base;
};
let mut merged = base.unwrap_or_default();
let apply = |slot: &mut Option<bool>, value: Option<bool>| match value {
Some(false) => *slot = Some(false),
Some(true) if !restricted => *slot = Some(true),
_ => {}
};
apply(&mut merged.trigram, override_indexes.trigram);
apply(&mut merged.semantic, override_indexes.semantic);
apply(&mut merged.callgraph, override_indexes.callgraph);
Some(merged)
}
fn merge_semantic_config(
base: Option<RawSemantic>,
override_semantic: Option<RawSemantic>,
) -> Option<RawSemantic> {
let mut semantic = base.unwrap_or(RawSemantic {
backend: None,
model: None,
base_url: None,
api_key_env: None,
timeout_ms: None,
query_timeout_ms: None,
query_instruction: None,
max_batch_size: None,
max_input_tokens: None,
max_files: None,
});
if let Some(project) = override_semantic {
if project.model.is_some() {
semantic.model = project.model;
}
if project.timeout_ms.is_some() {
semantic.timeout_ms = project.timeout_ms;
}
if project.query_instruction.is_some() {
semantic.query_instruction = project.query_instruction;
}
if project.max_batch_size.is_some() {
semantic.max_batch_size = project.max_batch_size;
}
if project.max_input_tokens.is_some() {
semantic.max_input_tokens = project.max_input_tokens;
}
if project.max_files.is_some() {
semantic.max_files = project.max_files;
}
}
(!semantic.is_empty()).then_some(semantic)
}
fn merge_lsp_config(base: Option<RawLsp>, override_lsp: Option<RawLsp>) -> Option<RawLsp> {
let mut lsp = base.unwrap_or_default();
if let Some(project) = override_lsp {
if let Some(max_servers) = project.max_servers {
if max_servers <= lsp.max_servers.unwrap_or(8) {
lsp.max_servers = Some(max_servers);
}
}
if let Some(idle) = project.idle_minutes {
if lsp_idle_minutes(Some(idle)) <= lsp_idle_minutes(lsp.idle_minutes) {
lsp.idle_minutes = Some(idle);
}
}
if project.idle_shutdown == Some(true) {
lsp.idle_shutdown = Some(true);
}
if project.python.is_some() {
lsp.python = project.python;
}
if project.diagnostics_on_edit.is_some() {
lsp.diagnostics_on_edit = project.diagnostics_on_edit;
}
}
(!lsp.is_empty()).then_some(lsp)
}
fn merge_experimental_config(
base: Option<RawExperimental>,
override_experimental: Option<RawExperimental>,
) -> Option<RawExperimental> {
let Some(override_experimental) = override_experimental else {
return base;
};
let mut experimental = base.unwrap_or_default();
experimental.lsp_ty = override_experimental.lsp_ty.or(experimental.lsp_ty);
(!experimental.is_empty()).then_some(experimental)
}
fn project_safe_bash(project: Option<RawBashFeatures>) -> Option<RawBashFeatures> {
project.map(|mut features| {
features.changed_files = features
.changed_files
.filter(|mode| *mode == crate::config::BashChangedFiles::Off);
features.linux_scope = None;
features.linux_scope_max_runtime_secs = None;
// Project environment entries retain their own tier through resolution.
features.project_env = features.env.take();
features.runon_env = None;
features.disclaim_privacy = features.disclaim_privacy.filter(|value| *value);
features
})
}
#[cfg(any(test, feature = "test-support"))]
#[test]
fn retired_runon_gate_preserves_explicit_user_choice_and_project_cannot_change_it() {
assert!(!resolve_config(&[]).config.remote_exec.enabled);
for (legacy, expected) in [(Some(false), false), (Some(true), true), (None, true)] {
let mut user = serde_json::json!({"remote_exec":{"enabled":true}});
if let Some(legacy) = legacy {
user["bash"] = serde_json::json!({"runon_enabled":legacy});
}
let result = resolve_config(&[
ConfigTier {
tier: "user".into(),
source: "user.jsonc".into(),
doc: user.to_string(),
},
ConfigTier {
tier: "project".into(),
source: "project.jsonc".into(),
doc: r#"{"bash":{"runon_enabled":false}}"#.into(),
},
]);
assert!(result.errors.is_empty(), "{:?}", result.errors);
assert_eq!(result.config.remote_exec.enabled, expected);
}
}
#[cfg(any(test, feature = "test-support"))]
#[test]
fn macos_full_sync_is_user_only_and_defaults_off() {
let defaults = resolve_config(&[]);
assert!(!defaults.config.durability.macos_full_sync);
assert!(!Config::default().durability.macos_full_sync);
for enabled in [false, true] {
let result = resolve_config(&[
ConfigTier {
tier: "user".into(),
source: "user.jsonc".into(),
doc: format!("{{\"durability\":{{\"macos_full_sync\":{enabled}}}}}"),
},
ConfigTier {
tier: "project".into(),
source: "project.jsonc".into(),
doc: format!("{{\"durability\":{{\"macos_full_sync\":{}}}}}", !enabled),
},
]);
assert!(result.errors.is_empty(), "{:?}", result.errors);
assert_eq!(result.config.durability.macos_full_sync, enabled);
assert!(result
.dropped
.iter()
.any(|drop| { drop.key == "durability.macos_full_sync" && drop.tier == "project" }));
}
let project = resolve_config(&[ConfigTier {
tier: "project".into(),
source: "project.jsonc".into(),
doc: r#"{"durability":{"macos_full_sync":true}}"#.into(),
}]);
assert!(!project.config.durability.macos_full_sync);
assert_eq!(project.dropped[0].key, "durability.macos_full_sync");
}
#[cfg(test)]
#[test]
fn macos_full_sync_ignores_all_harness_overrides() {
for harness in [Harness::Opencode, Harness::Pi] {
for base in [false, true] {
let key = harness.wire_label();
let result = resolve_config_for_harness(
&[
ConfigTier {
tier: "user".into(),
source: "user.jsonc".into(),
doc: serde_json::json!({
"durability": {"macos_full_sync": base},
"harnesses": {(key.clone()): {"durability": {"macos_full_sync": !base}}}
})
.to_string(),
},
ConfigTier {
tier: "project".into(),
source: "project.jsonc".into(),
doc: serde_json::json!({
"harnesses": {(key.clone()): {"durability": {"macos_full_sync": !base}}}
})
.to_string(),
},
],
Some(&harness),
);
assert!(result.errors.is_empty(), "{:?}", result.errors);
assert_eq!(result.config.durability.macos_full_sync, base);
for tier in ["user", "project"] {
assert!(result
.dropped
.iter()
.any(|drop| { drop.key == "durability.macos_full_sync" && drop.tier == tier }));
}
}
}
}
#[cfg(test)]
#[test]
fn bash_memory_limit_parses_and_project_cannot_raise_it() {
let resolve = |user: &str, project: &str| {
serde_json::to_value(
resolve_config(&[
ConfigTier {
tier: "user".into(),
source: "user.jsonc".into(),
doc: user.into(),
},
ConfigTier {
tier: "project".into(),
source: "project.jsonc".into(),
doc: project.into(),
},
])
.config
.bash,
)
.unwrap()["memory_limit_mib"]
.clone()
};
assert_eq!(
resolve(r#"{"bash":{"memory_limit_mib":64}}"#, "{}"),
serde_json::json!(64)
);
assert_eq!(
resolve(
r#"{"bash":{"memory_limit_mib":64}}"#,
r#"{"bash":{"memory_limit_mib":128}}"#
),
serde_json::json!(64)
);
assert_eq!(
resolve(
r#"{"bash":{"memory_limit_mib":64}}"#,
r#"{"bash":{"memory_limit_mib":32}}"#
),
serde_json::json!(32)
);
assert_eq!(
resolve(r#"{"bash":{"memory_limit_mib":64}}"#, r#"{"bash":false}"#),
serde_json::json!(64)
);
}
#[cfg(any(test, feature = "test-support"))]
#[test]
fn bash_memory_limit_rejects_invalid_values() {
assert!(resolve_config(&[]).config.bash.memory_limit_mib.is_none());
for value in ["0", "-1", "1.5", "true", "\"4GB\"", "4294967296"] {
let doc = format!("{{\"bash\":{{\"memory_limit_mib\":{value}}}}}");
assert!(serde_json::from_str::<RawAftConfig>(&doc).is_err(), "{doc}");
}
}
fn merge_bash_config(
base: Option<RawBashFeatures>,
override_bash: Option<RawBashFeatures>,
) -> Option<RawBashFeatures> {
match (base, override_bash) {
(None, None) => None,
(None, Some(override_bash)) => Some(override_bash),
(Some(base), None) => Some(base),
(Some(base), Some(override_bash)) => {
let override_features = override_bash;
Some(RawBashFeatures {
changed_files: override_features.changed_files.or(base.changed_files),
enabled: override_features.enabled.or(base.enabled),
rewrite: override_features.rewrite.or(base.rewrite),
compress: override_features.compress.or(base.compress),
background: override_features.background.or(base.background),
host_fallback: override_features.host_fallback.or(base.host_fallback),
subagent_background: override_features
.subagent_background
.or(base.subagent_background),
detach_on_user_message: override_features
.detach_on_user_message
.or(base.detach_on_user_message),
db_schema_hints: override_features.db_schema_hints.or(base.db_schema_hints),
long_running_reminder_enabled: override_features
.long_running_reminder_enabled
.or(base.long_running_reminder_enabled),
long_running_reminder_interval_ms: override_features
.long_running_reminder_interval_ms
.or(base.long_running_reminder_interval_ms),
foreground_wait_window_ms: override_features
.foreground_wait_window_ms
.or(base.foreground_wait_window_ms),
watch_sync_max_ms: override_features
.watch_sync_max_ms
.or(base.watch_sync_max_ms),
worker_wait_max_ms: override_features
.worker_wait_max_ms
.or(base.worker_wait_max_ms),
linux_scope: override_features.linux_scope.or(base.linux_scope),
linux_scope_max_runtime_secs: override_features
.linux_scope_max_runtime_secs
.or(base.linux_scope_max_runtime_secs),
memory_limit_mib: override_features.memory_limit_mib.or(base.memory_limit_mib),
disclaim_privacy: override_features.disclaim_privacy.or(base.disclaim_privacy),
powershell_tool: override_features.powershell_tool.or(base.powershell_tool),
env: merge_env_maps(base.env, override_features.env),
project_env: merge_env_maps(base.project_env, override_features.project_env),
runon_env: override_features.runon_env.or(base.runon_env),
})
}
}
}
/// Merge two `bash.env` maps by name: the override adds or replaces single
/// names and never removes a base name.
fn merge_env_maps(
base: Option<BTreeMap<String, String>>,
override_map: Option<BTreeMap<String, String>>,
) -> Option<BTreeMap<String, String>> {
match (base, override_map) {
(None, None) => None,
(Some(base), None) => Some(base),
(None, Some(override_map)) => Some(override_map),
(Some(mut base), Some(override_map)) => {
base.extend(override_map);
Some(base)
}
}
}
fn merge_idle_config(base: Option<RawIdle>, override_idle: Option<RawIdle>) -> Option<RawIdle> {
let Some(override_idle) = override_idle else {
return base;
};
let mut idle = base.unwrap_or_default();
if override_idle.root_ttl_minutes.is_some() {
idle.root_ttl_minutes = override_idle.root_ttl_minutes;
}
if override_idle.checkout_hours.is_some() {
idle.checkout_hours = override_idle.checkout_hours;
}
(!idle.is_empty()).then_some(idle)
}
fn merge_inspect_config(
base: Option<RawInspect>,
override_inspect: Option<RawInspect>,
) -> Option<RawInspect> {
let Some(override_inspect) = override_inspect else {
return base;
};
let mut inspect = base.unwrap_or_default();
inspect.enabled = override_inspect.enabled.or(inspect.enabled);
if let Some(project_timeout) = override_inspect.diagnostics_timeout_ms {
// A project may ask for more time, but it must not silently shrink another
// consumer's diagnostic completeness by reducing the user's effective wait.
inspect.diagnostics_timeout_ms = Some(
project_timeout.max(
inspect
.diagnostics_timeout_ms
.unwrap_or(DEFAULT_INSPECT_DIAGNOSTICS_TIMEOUT_MS),
),
);
}
inspect.tier2_pass_timeout_ms = override_inspect
.tier2_pass_timeout_ms
.or(inspect.tier2_pass_timeout_ms);
if let Some(project) = override_inspect.categories {
let categories = inspect.categories.get_or_insert_with(BTreeMap::new);
for (key, enabled) in project {
let user_enabled = categories.get(&key).copied().unwrap_or(true);
categories.insert(key, enabled && user_enabled);
}
}
inspect.duplicates = merge_inspect_duplicates(inspect.duplicates, override_inspect.duplicates);
(!inspect.is_empty()).then_some(inspect)
}
/// Merge a project tier's `pi` block. `external_access_ask: false` is ignored
/// there: a repository must not silence a protection the user has, so a
/// project may only turn the outside-access prompt on. `record_project_drops`
/// reports the ignored value.
fn merge_pi_config(base: Option<RawPi>, override_pi: Option<RawPi>) -> Option<RawPi> {
let Some(override_pi) = override_pi else {
return base;
};
let mut pi = base.unwrap_or_default();
pi.tool_presentation = override_pi.tool_presentation.or(pi.tool_presentation);
pi.external_access_ask = override_pi
.external_access_ask
.filter(|ask| *ask)
.or(pi.external_access_ask);
(!pi.is_empty()).then_some(pi)
}
fn merge_inspect_duplicates(
base: Option<RawInspectDuplicates>,
override_duplicates: Option<RawInspectDuplicates>,
) -> Option<RawInspectDuplicates> {
let Some(override_duplicates) = override_duplicates else {
return base;
};
let mut duplicates = base.unwrap_or_default();
duplicates.expected_mirrors = override_duplicates
.expected_mirrors
.or(duplicates.expected_mirrors);
(!duplicates.is_empty()).then_some(duplicates)
}
/// Resource settings are ordered by cost: a shorter idle window or an off
/// category tightens the user's budget. A project cannot increase that budget.
fn record_resource_loosening(
base: &RawAftConfig,
project: &RawAftConfig,
tier: &str,
dropped: &mut Vec<DroppedKey>,
) {
let floor = resolve_sandbox_config(base.sandbox.as_ref()).profile;
if let Some(profile) = project
.sandbox
.as_ref()
.and_then(|sandbox| sandbox.profile.as_ref())
{
for (role, next, floor) in [
("worker", profile.worker, floor.worker),
("head", profile.head, floor.head),
] {
if next.is_some_and(|next| next < floor) {
push_drop(
dropped,
&format!("sandbox.profile.{role}"),
tier,
"projects may only select a stricter sandbox profile",
);
}
}
}
const REASON: &str = "resource: project settings may only tighten the user budget";
if let Some(next) = project.lsp.as_ref().and_then(|lsp| lsp.max_servers) {
let floor = base
.lsp
.as_ref()
.and_then(|lsp| lsp.max_servers)
.unwrap_or(8);
if next > floor {
push_drop(dropped, "lsp.max_servers", tier, REASON);
}
}
let cap = |raw: &RawAftConfig| raw.bash.as_ref().and_then(|bash| bash.memory_limit_mib);
if let (Some(user), Some(project)) = (cap(base), cap(project)) {
if project > user {
push_drop(dropped, "bash.memory_limit_mib", tier, REASON);
}
}
if let Some(next) = project.lsp.as_ref().and_then(|lsp| lsp.idle_minutes) {
let floor = base.lsp.as_ref().and_then(|lsp| lsp.idle_minutes);
if lsp_idle_minutes(Some(next)) > lsp_idle_minutes(floor) {
push_drop(dropped, "lsp.idle_minutes", tier, REASON);
}
}
if project.lsp.as_ref().and_then(|lsp| lsp.idle_shutdown) == Some(false)
&& base.lsp.as_ref().and_then(|lsp| lsp.idle_shutdown) != Some(false)
{
push_drop(dropped, "lsp.idle_shutdown", tier, REASON);
}
if let Some(categories) = project
.inspect
.as_ref()
.and_then(|inspect| inspect.categories.as_ref())
{
for (key, enabled) in categories {
let floor = base
.inspect
.as_ref()
.and_then(|inspect| inspect.categories.as_ref())
.and_then(|categories| categories.get(key))
.copied()
.unwrap_or(true);
if *enabled && !floor {
push_drop(dropped, &format!("inspect.categories.{key}"), tier, REASON);
}
}
}
}
fn record_project_drops(raw: &RawAftConfig, tier: &str, dropped: &mut Vec<DroppedKey>) {
if raw
.shell
.as_ref()
.is_some_and(|shell| shell.env_provider.is_some())
{
push_drop(dropped, "shell.env_provider", tier, USER_ONLY_REASON);
}
if raw
.durability
.as_ref()
.is_some_and(|durability| durability.macos_full_sync.is_some())
{
push_drop(
dropped,
"durability.macos_full_sync",
tier,
USER_ONLY_REASON,
);
}
if raw
.storage
.as_ref()
.is_some_and(|storage| storage.cache_dir.is_some())
{
push_drop(dropped, "storage.cache_dir", tier, USER_ONLY_REASON);
}
if matches!(&raw.bash, Some(features) if features.disclaim_privacy == Some(false)) {
push_drop(
dropped,
"bash.disclaim_privacy",
tier,
"projects may only enable privacy disclaiming",
);
}
// A project's own `bash.env` is not dropped: it is validated and carried in
// `project_env`, then applied only while the project is trusted.
if matches!(&raw.bash, Some(features) if features.runon_env.is_some()) {
push_drop(dropped, "bash.runon_env", tier, USER_ONLY_REASON);
}
if raw.restrict_to_project_root.is_some() {
push_drop(dropped, "restrict_to_project_root", tier, USER_ONLY_REASON);
}
if raw.url_fetch_allow_private.is_some() {
push_drop(dropped, "url_fetch_allow_private", tier, USER_ONLY_REASON);
}
if raw.formatter_timeout_secs.is_some() {
push_drop(dropped, "formatter_timeout_secs", tier, USER_ONLY_REASON);
}
if raw.type_checker_timeout_secs.is_some() {
push_drop(dropped, "type_checker_timeout_secs", tier, USER_ONLY_REASON);
}
if raw.auto_update.is_some() {
push_drop(dropped, "auto_update", tier, USER_ONLY_REASON);
}
if raw.bridge.is_some() {
push_drop(dropped, "bridge", tier, USER_ONLY_REASON);
}
if raw.subc.is_some() {
push_drop(dropped, "subc", tier, USER_ONLY_REASON);
}
if raw
.pi
.as_ref()
.is_some_and(|pi| pi.external_access_ask == Some(false))
{
push_drop(
dropped,
"pi.external_access_ask",
tier,
"security: a project config may only turn the outside-access prompt on",
);
}
if raw
.backup
.as_ref()
.is_some_and(|backup| backup.enabled.is_some() || backup.max_depth.is_some())
{
push_drop(dropped, "backup", tier, USER_ONLY_REASON);
}
if raw.github.is_some() {
push_drop(dropped, "github", tier, USER_ONLY_REASON);
}
if raw.gh_shim.is_some() {
push_drop(dropped, "gh_shim", tier, USER_ONLY_REASON);
}
if let Some(remote_exec) = &raw.remote_exec {
if remote_exec.enabled == Some(true) {
push_drop(
dropped,
"remote_exec.enabled",
tier,
REMOTE_EXEC_PROJECT_REASON,
);
}
if remote_exec.default_demand.is_some() {
push_drop(
dropped,
"remote_exec.default_demand",
tier,
REMOTE_EXEC_PROJECT_REASON,
);
}
}
if raw
.index
.as_ref()
.and_then(|index| index.roots.as_ref())
.is_some()
{
push_drop(dropped, "index.roots", tier, USER_ONLY_REASON);
}
if let Some(sandbox) = &raw.sandbox {
if sandbox.write_allow.is_some() {
push_drop(dropped, "sandbox.write_allow", tier, USER_ONLY_REASON);
}
}
if raw.bash.as_ref().is_some_and(
|bash| matches!(bash, features if features.changed_files.is_some_and(|mode| mode != crate::config::BashChangedFiles::Off)),
) {
push_drop(dropped, "bash.changed_files", tier, "a project config may only turn changed-file reporting off");
}
if raw
.bash
.as_ref()
.is_some_and(|bash| matches!(bash, features if features.linux_scope.is_some()))
{
push_drop(dropped, "bash.linux_scope", tier, USER_ONLY_REASON);
}
if raw.bash.as_ref().is_some_and(
|bash| matches!(bash, features if features.linux_scope_max_runtime_secs.is_some()),
) {
push_drop(
dropped,
"bash.linux_scope_max_runtime_secs",
tier,
USER_ONLY_REASON,
);
}
for tool in feature_config::normalize_tool_list(
raw.disabled_tools
.iter()
.flatten()
.filter(|tool| feature_config::is_project_protected_tool(tool))
.cloned(),
) {
push_drop(
dropped,
&format!("disabled_tools.{tool}"),
tier,
PROTECTED_TOOL_REASON,
);
}
if let Some(semantic) = &raw.semantic {
if semantic.backend.is_some() {
push_drop(dropped, "semantic.backend", tier, SEMANTIC_SECRET_REASON);
}
if semantic.base_url.is_some() {
push_drop(dropped, "semantic.base_url", tier, SEMANTIC_SECRET_REASON);
}
if semantic.api_key_env.is_some() {
push_drop(
dropped,
"semantic.api_key_env",
tier,
SEMANTIC_SECRET_REASON,
);
}
if semantic.query_timeout_ms.is_some() {
push_drop(dropped, "semantic.query_timeout_ms", tier, USER_ONLY_REASON);
}
}
if let Some(rerank) = raw
.search
.as_ref()
.and_then(|search| search.rerank.as_ref())
{
// `backend: "off"` is the one accepted project value; everything else
// could start a model download, reach an endpoint, read a credential
// variable or change how much of the result list is reordered.
if rerank
.backend
.is_some_and(|backend| backend != RerankBackendKind::Off)
{
push_drop(
dropped,
"search.rerank.backend",
tier,
RERANK_PROJECT_REASON,
);
}
for (key, present) in [
("search.rerank.model", rerank.model.is_some()),
("search.rerank.endpoint", rerank.endpoint.is_some()),
("search.rerank.api_key_env", rerank.api_key_env.is_some()),
("search.rerank.top_n", rerank.top_n.is_some()),
("search.rerank.timeout_ms", rerank.timeout_ms.is_some()),
] {
if present {
push_drop(dropped, key, tier, RERANK_PROJECT_REASON);
}
}
}
if let Some(lsp) = &raw.lsp {
if lsp.servers.is_some() {
push_drop(dropped, "lsp.servers", tier, LSP_USER_ONLY_REASON);
}
if lsp.versions.is_some() {
push_drop(dropped, "lsp.versions", tier, LSP_USER_ONLY_REASON);
}
if lsp.auto_install.is_some() {
push_drop(dropped, "lsp.auto_install", tier, LSP_USER_ONLY_REASON);
}
if lsp.grace_days.is_some() {
push_drop(dropped, "lsp.grace_days", tier, LSP_USER_ONLY_REASON);
}
if lsp.disabled.is_some() {
push_drop(dropped, "lsp.disabled", tier, LSP_USER_ONLY_REASON);
}
}
}
fn push_drop(dropped: &mut Vec<DroppedKey>, key: &str, tier: &str, reason: &str) {
dropped.push(DroppedKey {
key: key.to_string(),
tier: tier.to_string(),
reason: reason.to_string(),
});
}
/// Apply merged core-domain fields onto a freshly defaulted `Config`. Absent
/// scalar fields therefore retain defaults, while semantic, inspect, and LSP
/// fields are fully resolved from the tiers. Process-state fields are not part
/// of `RawAftConfig` and are preserved separately by `resolve_config_onto`.
fn apply_resolved_config(
raw: &RawAftConfig,
config: &mut Config,
warnings: &mut Vec<ConfigWarning>,
) -> Result<(), Vec<String>> {
config.shell = raw.shell.clone().unwrap_or_default();
if let Some(provider) = &config.shell.env_provider {
provider.validate().map_err(|error| vec![error])?;
}
config.hashline_enabled = matches!(raw.edit_mode, Some(RawEditMode::Hashline));
config.durability.macos_full_sync = raw
.durability
.as_ref()
.and_then(|durability| durability.macos_full_sync)
.unwrap_or(false);
// The user-base default has already been applied; an absent list here is
// a resolver bug and must not silently become an empty (all-enabled) list.
let Some(disabled_tools) = &raw.disabled_tools else {
return Err(vec![
"invalid_resolved_config:missing:disabled_tools".to_string()
]);
};
config.disabled_tools = feature_config::normalize_tool_list(disabled_tools.iter().cloned());
config.aft_search_registered = config.tool_registered("aft_search");
let indexes = raw.indexes.unwrap_or_default();
let defaults = IndexesConfig::default();
config.indexes = IndexesConfig {
trigram: indexes.trigram.unwrap_or(defaults.trigram),
semantic: indexes.semantic.unwrap_or(defaults.semantic),
callgraph: indexes.callgraph.unwrap_or(defaults.callgraph),
};
if let Some(value) = raw.format_on_edit {
config.format_on_edit = value;
}
if let Some(value) = raw.revision_reads {
config.revision_reads = value;
}
if let Some(value) = raw.formatter_timeout_secs {
config.formatter_timeout_secs = value;
}
if let Some(value) = raw.type_checker_timeout_secs {
config.type_checker_timeout_secs = value;
}
if let Some(value) = raw.validate_on_edit {
config.validate_on_edit = Some(value.as_str().to_string());
}
if let Some(formatter) = &raw.formatter {
config.formatter = formatter
.iter()
.map(|(language, formatter)| (language.clone(), formatter.as_str().to_string()))
.collect();
}
if let Some(checker) = &raw.checker {
config.checker = checker
.iter()
.map(|(language, checker)| (language.clone(), checker.as_str().to_string()))
.collect();
}
if let Some(value) = raw.restrict_to_project_root {
config.restrict_to_project_root = value;
}
config.memory = raw.memory;
if let Some(value) = raw.url_fetch_allow_private {
config.url_fetch_allow_private = value;
}
config.semantic = resolve_semantic_config(raw.semantic.as_ref(), raw.subc.as_ref());
config.search = resolve_search_config(raw.search.as_ref());
config.inspect = resolve_inspect_config(raw.inspect.as_ref());
config.backup = resolve_backup_config(raw.backup.as_ref());
config.github = resolve_github_config(raw.github.as_ref(), warnings);
config.gh_shim = resolve_gh_shim_config(raw.gh_shim.as_ref());
config.git = resolve_git_config(raw.git.as_ref());
config.sandbox = resolve_sandbox_config(raw.sandbox.as_ref());
config.remote_exec = resolve_remote_exec_config(raw);
resolve_lsp_config(raw, config);
resolve_bash_fields(raw, config, warnings);
Ok(())
}
fn resolve_index_config(raw: Option<&RawIndex>, warnings: &mut Vec<ConfigWarning>) -> IndexConfig {
let Some(raw) = raw else {
return IndexConfig::default();
};
let Some(roots) = raw.roots.as_ref() else {
return IndexConfig::default();
};
let home = crate::environment::non_empty_os_var("HOME")
.or_else(|| crate::environment::non_empty_os_var("USERPROFILE"))
.map(PathBuf::from);
let mut normalized_roots = Vec::with_capacity(roots.len());
for (position, root) in roots.iter().enumerate() {
for field in root.unknown.keys() {
warnings.push(ConfigWarning {
code: "unknown_index_root_field",
key: "index.roots",
tier: "user".to_string(),
value: field.clone(),
message: format!(
"Ignoring unknown field index.roots[{position}].{field}; only path and indexes are defined"
),
});
}
let result = (|| -> Result<IndexRootConfig, String> {
let path = root.path.as_deref().ok_or_else(|| {
"index.roots entry is missing required string field path".to_string()
})?;
expand_index_root_path(path, home.as_deref())?;
let indexes = root.indexes.as_ref().ok_or_else(|| {
"index.roots entry is missing required non-empty indexes array".to_string()
})?;
if indexes.is_empty() {
return Err("index.roots indexes must be a non-empty array".to_string());
}
let mut normalized = Vec::with_capacity(indexes.len() + 1);
for name in indexes {
let kind = IndexKind::from_name(name).ok_or_else(|| {
format!(
"index.roots indexes contains unknown name {name:?}; valid names: search, semantic, callgraph"
)
})?;
if normalized.contains(&kind) {
return Err(format!(
"index.roots indexes contains duplicate name {name:?}"
));
}
normalized.push(kind);
}
if normalized.contains(&IndexKind::Semantic) && !normalized.contains(&IndexKind::Search)
{
normalized.push(IndexKind::Search);
warnings.push(ConfigWarning {
code: "index_dependency_closure",
key: "index.roots",
tier: "user".to_string(),
value: path.to_string(),
message: format!(
"Added search to index.roots[{position}].indexes because semantic depends on search"
),
});
}
normalized.sort_unstable();
Ok(IndexRootConfig {
path: path.to_string(),
indexes: normalized,
})
})();
match result {
Ok(root) => normalized_roots.push(root),
Err(message) => {
warnings.push(ConfigWarning {
code: "invalid_index_roots",
key: "index.roots",
tier: "user".to_string(),
value: position.to_string(),
message,
});
return IndexConfig::default();
}
}
}
IndexConfig {
roots: normalized_roots,
}
}
fn resolve_semantic_config(
raw: Option<&RawSemantic>,
subc: Option<&RawSubc>,
) -> SemanticBackendConfig {
let mut semantic = SemanticBackendConfig::default();
semantic.subc_connection_file = subc
.and_then(|subc| subc.connection_file.as_deref())
.map(str::trim)
.filter(|path| !path.is_empty())
.map(PathBuf::from);
let Some(raw) = raw else {
return semantic;
};
if let Some(value) = raw.backend {
semantic.backend = value;
if value == SemanticBackend::Synapse && raw.model.is_none() {
// Synapse has no implicit vector space. Leaving this empty lets backend
// initialization return an honest missing-model configuration error.
semantic.model.clear();
}
}
if let Some(value) = &raw.model {
semantic.model = value.clone();
}
if let Some(value) = &raw.base_url {
semantic.base_url = Some(value.clone());
}
if let Some(value) = &raw.api_key_env {
semantic.api_key_env = Some(value.clone());
}
if let Some(value) = raw.timeout_ms {
semantic.timeout_ms = value.min(MAX_SEMANTIC_TIMEOUT_MS);
}
if let Some(value) = &raw.query_instruction {
semantic.query_instruction = value.clone();
}
if let Some(value) = raw.query_timeout_ms {
semantic.query_timeout_ms =
value.clamp(MIN_SEMANTIC_QUERY_TIMEOUT_MS, MAX_SEMANTIC_QUERY_TIMEOUT_MS);
}
if let Some(value) = raw.max_batch_size {
semantic.max_batch_size = value.min(MAX_SEMANTIC_BATCH_SIZE);
}
if let Some(value) = raw.max_input_tokens {
semantic.max_input_tokens = Some(value);
}
if let Some(value) = raw.max_files {
semantic.max_files = value;
}
semantic
}
fn resolve_idle_config(raw: Option<&RawIdle>, warnings: &mut Vec<ConfigWarning>) -> IdleConfig {
let mut idle = IdleConfig::default();
let Some(raw) = raw else {
return idle;
};
idle.root_ttl_minutes = resolve_clamped_minutes(
raw.root_ttl_minutes.as_ref(),
"idle.root_ttl_minutes",
DEFAULT_IDLE_ROOT_TTL_MINUTES,
MIN_IDLE_ROOT_TTL_MINUTES,
MAX_IDLE_ROOT_TTL_MINUTES,
warnings,
);
idle.checkout_hours = resolve_clamped_minutes(
raw.checkout_hours.as_ref(),
"idle.checkout_hours",
crate::config::DEFAULT_IDLE_CHECKOUT_HOURS,
crate::config::MIN_IDLE_CHECKOUT_HOURS,
crate::config::MAX_IDLE_CHECKOUT_HOURS,
warnings,
);
idle
}
/// An integer setting clamped to `min..=max`, with a warning when it is out
/// of range or not an integer. Used for the idle windows; the unit (minutes or
/// hours) is the caller's.
fn resolve_clamped_minutes(
raw: Option<&Value>,
key: &'static str,
default: u32,
min: u32,
max: u32,
warnings: &mut Vec<ConfigWarning>,
) -> u32 {
let Some(value) = raw else {
return default;
};
let Some(parsed) = json_integer(value) else {
warnings.push(ConfigWarning {
code: "invalid_idle_ttl",
key,
tier: "config".to_string(),
value: value.to_string(),
message: format!("{key} must be an integer; using default {default}"),
});
return default;
};
let clamped = parsed.clamp(i64::from(min), i64::from(max)) as u32;
if i64::from(clamped) != parsed {
warnings.push(ConfigWarning {
code: "clamped_idle_ttl",
key,
tier: "config".to_string(),
value: parsed.to_string(),
message: format!("{key}={parsed} is outside {min}..={max}; clamped to {clamped}"),
});
}
clamped
}
fn resolve_clamped_bash_watch_sync_max_ms(
raw: Option<u64>,
warnings: &mut Vec<ConfigWarning>,
) -> u64 {
let Some(raw) = raw else {
return DEFAULT_BASH_WATCH_SYNC_MAX_MS;
};
let clamped = raw.clamp(MIN_BASH_WATCH_SYNC_MAX_MS, MAX_BASH_WATCH_SYNC_MAX_MS);
if clamped != raw {
warnings.push(ConfigWarning {
code: "clamped_bash_watch_sync_max_ms",
key: "bash.watch_sync_max_ms",
tier: "config".to_string(),
value: raw.to_string(),
message: format!(
"bash.watch_sync_max_ms={raw} is outside {MIN_BASH_WATCH_SYNC_MAX_MS}..={MAX_BASH_WATCH_SYNC_MAX_MS}; clamped to {clamped}"
),
});
}
clamped
}
fn json_integer(value: &Value) -> Option<i64> {
match value {
Value::Number(number) if number.is_i64() => number.as_i64(),
Value::Number(number) if number.is_u64() => {
number.as_u64().and_then(|value| i64::try_from(value).ok())
}
_ => None,
}
}
fn resolve_inspect_config(raw: Option<&RawInspect>) -> InspectConfig {
let mut inspect = InspectConfig::default();
let Some(raw) = raw else {
return inspect;
};
if let Some(enabled) = raw.enabled {
inspect.enabled = enabled;
}
if let Some(categories) = &raw.categories {
inspect.categories = serde_json::from_value(serde_json::to_value(categories).unwrap())
.expect("validated inspect categories");
}
if let Some(value) = raw.diagnostics_timeout_ms {
inspect.diagnostics_timeout_ms = value.clamp(
MIN_INSPECT_DIAGNOSTICS_TIMEOUT_MS,
MAX_INSPECT_DIAGNOSTICS_TIMEOUT_MS,
);
}
if let Some(value) = raw.tier2_pass_timeout_ms {
inspect.tier2_pass_timeout_ms = value;
}
if let Some(expected_mirrors) = raw
.duplicates
.as_ref()
.and_then(|duplicates| duplicates.expected_mirrors.clone())
{
inspect.duplicates.expected_mirrors = expected_mirrors
.into_iter()
.map(|pair| [pair.source, pair.mirror])
.collect();
}
inspect
}
fn resolve_backup_config(raw: Option<&RawBackup>) -> BackupConfig {
let mut backup = BackupConfig::default();
if let Some(raw) = raw {
if raw.enabled.is_some() {
backup.enabled = raw.enabled;
}
if raw.max_depth.is_some() {
backup.max_depth = raw.max_depth;
}
if raw.max_file_size.is_some() {
backup.max_file_size = raw.max_file_size;
}
}
backup
}
fn resolve_github_config(
raw: Option<&RawGithub>,
warnings: &mut Vec<ConfigWarning>,
) -> GithubConfig {
let mut github = GithubConfig::default();
if let Some(value) = raw.and_then(|raw| raw.shim) {
github.shim = value;
}
if let Some(value) = raw.and_then(|raw| raw.read) {
github.read = value;
}
if let Some(value) = raw.and_then(|raw| raw.write) {
github.write = value;
}
// Write implies read; the legacy `github.enabled` master was translated
// into explicit leaves before this point.
if github.write && !github.read {
github.read = true;
warnings.push(ConfigWarning {
code: "github_write_requires_read",
key: "github.write",
tier: "user".to_string(),
value: "true".to_string(),
message: "github.write=true requires github.read=true; treating github.read as enabled"
.to_string(),
});
}
github
}
fn resolve_gh_shim_config(raw: Option<&RawGhShim>) -> GhShimConfig {
let mut gh_shim = GhShimConfig::default();
gh_shim.binary_path = raw
.and_then(|raw| raw.binary_path.as_ref())
.map(PathBuf::from);
gh_shim
}
fn resolve_git_config(raw: Option<&RawGit>) -> GitConfig {
GitConfig {
co_author: raw
.and_then(|raw| raw.co_author.clone())
.unwrap_or_else(|| "off".to_string()),
}
}
fn resolve_sandbox_config(raw: Option<&RawSandbox>) -> SandboxConfig {
let Some(raw) = raw else {
return SandboxConfig::default();
};
SandboxConfig {
profile: crate::config::SandboxRoles {
worker: raw
.profile
.as_ref()
.and_then(|profile| profile.worker)
.unwrap_or(crate::config::SandboxMode::Relaxed),
head: raw
.profile
.as_ref()
.and_then(|profile| profile.head)
.unwrap_or(crate::config::SandboxMode::Off),
},
write_allow: raw.write_allow.clone().unwrap_or_default(),
read_deny: raw.read_deny.clone().unwrap_or_default(),
}
}
fn resolve_remote_exec_config(raw: &RawAftConfig) -> RemoteExecConfig {
let user = raw.remote_exec.as_ref();
RemoteExecConfig {
enabled: user.and_then(|r| r.enabled) == Some(true) && !raw.remote_exec_project_off,
default_demand: user.and_then(|r| r.default_demand.clone()),
project_off: raw.remote_exec_project_off,
}
}
fn resolve_lsp_config(raw: &RawAftConfig, config: &mut Config) {
let lsp = raw.lsp.as_ref();
config.lsp_idle_minutes = lsp_idle_minutes(lsp.and_then(|lsp| lsp.idle_minutes));
config.lsp_idle_shutdown = lsp.and_then(|lsp| lsp.idle_shutdown).unwrap_or(true);
config.lsp_max_servers = lsp.and_then(|lsp| lsp.max_servers).unwrap_or(8);
let mut disabled: HashSet<String> = lsp
.and_then(|lsp| lsp.disabled.as_ref())
.into_iter()
.flatten()
.map(|value| value.to_ascii_lowercase())
.collect();
let mut experimental_ty = raw
.experimental
.as_ref()
.and_then(|experimental| experimental.lsp_ty);
match lsp.and_then(|lsp| lsp.python).unwrap_or(RawPythonLsp::Auto) {
RawPythonLsp::Ty => {
experimental_ty = Some(true);
disabled.insert("python".to_string());
}
RawPythonLsp::Pyright => {
experimental_ty = Some(false);
disabled.insert("ty".to_string());
}
RawPythonLsp::Auto => {}
}
if let Some(value) = experimental_ty {
config.experimental_lsp_ty = value;
}
if let Some(value) = lsp.and_then(|lsp| lsp.diagnostics_on_edit) {
config.diagnostics_on_edit = value;
}
if let Some(servers) = lsp.and_then(|lsp| lsp.servers.as_ref()) {
let invalid = &mut config.invalid_lsp_initialization_options;
config.lsp_servers = servers
.iter()
.map(|(id, server)| UserServerDef {
id: id.clone(),
extensions: server
.extensions
.clone()
.unwrap_or_default()
.into_iter()
.map(|extension| extension.trim_start_matches('.').to_string())
.collect(),
binary: server.binary.clone().unwrap_or_default(),
args: server.args.clone().unwrap_or_default(),
root_markers: server
.root_markers
.clone()
.unwrap_or_else(|| vec![".git".to_string()]),
env: server.env.clone().unwrap_or_default(),
initialization_options: server.initialization_options.as_deref().and_then(|text| {
match serde_json::from_str(text) {
Ok(options) => Some(options),
Err(_) => {
invalid.push(id.clone());
None
}
}
}),
disabled: server.disabled.unwrap_or(false),
})
.collect();
}
if !disabled.is_empty() {
config.disabled_lsp = disabled;
}
}
fn lsp_idle_minutes(value: Option<i64>) -> u32 {
use crate::config::{DEFAULT_LSP_IDLE_MINUTES, MAX_LSP_IDLE_MINUTES, MIN_LSP_IDLE_MINUTES};
value.unwrap_or(i64::from(DEFAULT_LSP_IDLE_MINUTES)).clamp(
i64::from(MIN_LSP_IDLE_MINUTES),
i64::from(MAX_LSP_IDLE_MINUTES),
) as u32
}
/// A validated `bash.env` map together with the tier it was written at.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfiguredBashEnv {
pub names: BTreeMap<String, String>,
pub tier: crate::bash_env::BashEnvTier,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ResolvedBashConfig {
changed_files: crate::config::BashChangedFiles,
enabled: bool,
rewrite: bool,
compress: bool,
background: bool,
host_fallback: bool,
subagent_background: bool,
detach_on_user_message: bool,
db_schema_hints: bool,
long_running_reminder_enabled: Option<bool>,
long_running_reminder_interval_ms: Option<u64>,
foreground_wait_window_ms: u64,
watch_sync_max_ms: u64,
worker_wait_max_ms: u64,
linux_scope: bool,
linux_scope_max_runtime_secs: u64,
memory_limit_mib: Option<u64>,
disclaim_privacy: bool,
powershell_tool: bool,
env: BTreeMap<String, String>,
project_env: BTreeMap<String, String>,
runon_env: Vec<String>,
}
fn resolve_bash_fields(raw: &RawAftConfig, config: &mut Config, warnings: &mut Vec<ConfigWarning>) {
let bash = resolve_bash_config(raw, warnings);
// `subagent_background` is plugin-owned; Rust resolves it only to accept
// and merge the same config.
let _plugin_only = bash.subagent_background;
config.bash.enabled = bash.enabled;
config.bash.changed_files = bash.changed_files;
config.bash.host_fallback = bash.host_fallback;
config.bash.detach_on_user_message = bash.detach_on_user_message;
config.bash.db_schema_hints = bash.db_schema_hints;
config.bash.watch_sync_max_ms = bash.watch_sync_max_ms;
config.bash.worker_wait_max_ms = bash.worker_wait_max_ms;
config.bash.linux_scope = bash.linux_scope;
config.bash.linux_scope_max_runtime_secs = bash.linux_scope_max_runtime_secs;
config.bash.memory_limit_mib = bash.memory_limit_mib;
config.bash.disclaim_privacy = bash.disclaim_privacy;
config.bash.powershell_tool = bash.powershell_tool;
config.bash.env = bash.env;
config.bash.project_env = bash.project_env;
config.bash.runon_env = bash.runon_env;
config.experimental_bash_rewrite = bash.rewrite;
config.experimental_bash_compress = bash.compress;
config.experimental_bash_background = bash.background;
config.foreground_wait_window_ms = bash.foreground_wait_window_ms;
if let Some(value) = bash.long_running_reminder_enabled {
config.bash_long_running_reminder_enabled = value;
}
if let Some(value) = bash.long_running_reminder_interval_ms {
config.bash_long_running_reminder_interval_ms = value;
}
}
fn resolve_bash_config(
raw: &RawAftConfig,
warnings: &mut Vec<ConfigWarning>,
) -> ResolvedBashConfig {
let top = raw.bash.as_ref();
let top_features = top;
let reminder_enabled = top_features.and_then(|features| features.long_running_reminder_enabled);
let reminder_interval =
top_features.and_then(|features| features.long_running_reminder_interval_ms);
let top_host_fallback = top_features
.and_then(|features| features.host_fallback)
.unwrap_or(false);
let top_subagent_background = top_features
.and_then(|features| features.subagent_background)
.unwrap_or(true);
let top_detach_on_user_message = top_features
.and_then(|features| features.detach_on_user_message)
.unwrap_or(true);
let raw_foreground_wait = top_features.and_then(|features| features.foreground_wait_window_ms);
let raw_watch_sync_max = top_features.and_then(|features| features.watch_sync_max_ms);
let watch_sync_max_ms = resolve_clamped_bash_watch_sync_max_ms(raw_watch_sync_max, warnings);
// Below-minimum values never get here: the raw schema rejects them, which
// drops the `bash` block like any other invalid value.
let worker_wait_max_ms = top_features
.and_then(|features| features.worker_wait_max_ms)
.unwrap_or(DEFAULT_BASH_WORKER_WAIT_MAX_MS);
let top_linux_scope = top_features
.and_then(|features| features.linux_scope)
.unwrap_or(true);
let top_powershell_tool = top_features
.and_then(|features| features.powershell_tool)
.unwrap_or(false);
let foreground_wait_window_ms = raw_foreground_wait
.unwrap_or(FOREGROUND_WAIT_WINDOW_DEFAULT_MS)
.max(FOREGROUND_WAIT_WINDOW_MIN_MS);
let base = ResolvedBashConfig {
changed_files: top_features
.and_then(|features| features.changed_files)
.unwrap_or_default(),
enabled: false,
rewrite: false,
compress: false,
background: false,
host_fallback: false,
subagent_background: true,
detach_on_user_message: true,
db_schema_hints: top_features
.and_then(|features| features.db_schema_hints)
.unwrap_or(true),
long_running_reminder_enabled: reminder_enabled,
long_running_reminder_interval_ms: reminder_interval,
foreground_wait_window_ms,
watch_sync_max_ms,
worker_wait_max_ms,
linux_scope: top_linux_scope,
linux_scope_max_runtime_secs: top_features
.and_then(|features| features.linux_scope_max_runtime_secs)
.unwrap_or(crate::config::DEFAULT_LINUX_SCOPE_MAX_RUNTIME_SECS),
memory_limit_mib: top_features.and_then(|features| features.memory_limit_mib),
disclaim_privacy: top_features
.and_then(|features| features.disclaim_privacy)
.unwrap_or(false),
powershell_tool: false,
env: BTreeMap::new(),
project_env: BTreeMap::new(),
runon_env: Vec::new(),
};
match top {
Some(features) => ResolvedBashConfig {
enabled: features.enabled.unwrap_or(true),
rewrite: features.rewrite.unwrap_or(true),
compress: features.compress.unwrap_or(true),
background: features.background.unwrap_or(true),
host_fallback: top_host_fallback,
subagent_background: top_subagent_background,
detach_on_user_message: top_detach_on_user_message,
powershell_tool: top_powershell_tool,
env: features.env.clone().unwrap_or_default(),
project_env: features.project_env.clone().unwrap_or_default(),
runon_env: features.runon_env.clone().unwrap_or_default(),
..base
},
None => ResolvedBashConfig {
enabled: true,
rewrite: true,
compress: true,
background: true,
..base
},
}
}
fn deserialize_opt_git_co_author<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<String>::deserialize(deserializer)?;
value
.map(|value| {
normalize_git_co_author(&value).ok_or_else(|| {
de::Error::custom(
"git.co_author must be 'off', 'auto', or an explicit 'Name <email>' identity",
)
})
})
.transpose()
}
fn deserialize_opt_trimmed_non_empty_string<'de, D>(
deserializer: D,
) -> Result<Option<String>, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<String>::deserialize(deserializer)?;
value
.map(|value| {
let trimmed = value.trim().to_string();
if trimmed.is_empty() {
Err(de::Error::custom("must be a non-empty string"))
} else {
Ok(trimmed)
}
})
.transpose()
}
fn deserialize_opt_trimmed_non_empty_string_vec<'de, D>(
deserializer: D,
) -> Result<Option<Vec<String>>, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<Vec<String>>::deserialize(deserializer)?;
value
.map(|values| {
values
.into_iter()
.map(|value| {
let trimmed = value.trim().to_string();
if trimmed.is_empty() {
Err(de::Error::custom("array entries must be non-empty strings"))
} else {
Ok(trimmed)
}
})
.collect()
})
.transpose()
}
fn deserialize_opt_lsp_extensions<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<Vec<String>>::deserialize(deserializer)?;
value
.map(|values| {
if values.is_empty() {
return Err(de::Error::custom(
"extensions must contain at least one entry",
));
}
values
.into_iter()
.map(|value| {
let trimmed = value.trim().to_string();
if trimmed.is_empty() || trimmed.trim_start_matches('.').is_empty() {
Err(de::Error::custom(
"extension must include characters other than leading dots",
))
} else {
Ok(trimmed)
}
})
.collect()
})
.transpose()
}
fn deserialize_opt_lsp_servers<'de, D>(
deserializer: D,
) -> Result<Option<BTreeMap<String, RawLspServerEntry>>, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<BTreeMap<String, RawLspServerEntry>>::deserialize(deserializer)?;
value
.map(|entries| {
entries
.into_iter()
.map(|(key, value)| {
let trimmed = key.trim().to_string();
if trimmed.is_empty() {
Err(de::Error::custom(
"lsp.servers keys must be non-empty strings",
))
} else {
Ok((trimmed, value))
}
})
.collect()
})
.transpose()
}
fn deserialize_opt_versions_map<'de, D>(
deserializer: D,
) -> Result<Option<HashMap<String, String>>, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<HashMap<String, String>>::deserialize(deserializer)?;
value
.map(|entries| {
entries
.into_iter()
.map(|(key, value)| {
let trimmed_key = key.trim().to_string();
let trimmed_value = value.trim().to_string();
if trimmed_key.is_empty() || trimmed_value.is_empty() {
Err(de::Error::custom(
"lsp.versions keys and values must be non-empty strings",
))
} else {
Ok((trimmed_key, trimmed_value))
}
})
.collect()
})
.transpose()
}
fn deserialize_opt_positive_u64<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<u64>::deserialize(deserializer)?;
match value {
Some(0) => Err(de::Error::custom("must be a positive integer")),
other => Ok(other),
}
}
fn deserialize_opt_linux_scope_max_runtime_secs<'de, D>(
deserializer: D,
) -> Result<Option<u64>, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<u64>::deserialize(deserializer)
.map_err(|error| de::Error::custom(format!("linux_scope_max_runtime_secs: {error}")))?;
if value.is_some_and(|value| !(1..=4_294_967_295).contains(&value)) {
return Err(de::Error::custom(
"linux_scope_max_runtime_secs must be from 1 to 4294967295",
));
}
Ok(value)
}
fn deserialize_opt_memory_limit_mib<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = Option::<u64>::deserialize(deserializer)?;
if value.is_some_and(|value| value == 0 || value > 4_294_967_295) {
return Err(serde::de::Error::custom(
"expected memory limit in MiB from 1 to 4294967295",
));
}
Ok(value)
}
fn deserialize_opt_positive_usize<'de, D>(deserializer: D) -> Result<Option<usize>, D::Error>
where
D: Deserializer<'de>,
{
let value = deserialize_opt_positive_u64(deserializer)?;
value
.map(|value| usize::try_from(value).map_err(|_| de::Error::custom("value is too large")))
.transpose()
}
fn deserialize_opt_timeout_secs<'de, D>(deserializer: D) -> Result<Option<u32>, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<u64>::deserialize(deserializer)?;
match value {
Some(value) if !(1..=600).contains(&value) => {
Err(de::Error::custom("timeout must be in 1..=600 seconds"))
}
Some(value) => u32::try_from(value)
.map(Some)
.map_err(|_| de::Error::custom("timeout is too large")),
None => Ok(None),
}
}
fn deserialize_opt_bridge_request_timeout_ms<'de, D>(
deserializer: D,
) -> Result<Option<u64>, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<u64>::deserialize(deserializer)?;
match value {
Some(value) if value < 1_000 => Err(de::Error::custom(
"bridge.request_timeout_ms must be at least 1000",
)),
other => Ok(other),
}
}
fn deserialize_opt_worker_wait_max_ms<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<u64>::deserialize(deserializer)?;
match value {
Some(value) if value < MIN_BASH_WORKER_WAIT_MAX_MS => Err(de::Error::custom(format!(
"bash.worker_wait_max_ms must be at least {MIN_BASH_WORKER_WAIT_MAX_MS}"
))),
other => Ok(other),
}
}
fn deserialize_opt_inspect_categories<'de, D>(
deserializer: D,
) -> Result<Option<BTreeMap<String, bool>>, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<BTreeMap<String, bool>>::deserialize(deserializer)?;
if let Some(categories) = &value {
if categories
.keys()
.any(|key| !InspectCategories::KEYS.contains(&key.as_str()))
{
return Err(de::Error::custom("unknown inspect category"));
}
}
Ok(value)
}
#[cfg(test)]
mod tests {
#[test]
fn storage_cache_dir_is_a_recognized_user_setting() {
let raw = serde_json::from_str::<super::RawAftConfig>(
r#"{"storage":{"cache_dir":{"kind":"dir","path":"/cache/aft"}}}"#,
);
assert!(raw.is_ok(), "storage.cache_dir must be recognized: {raw:?}");
}
#[test]
fn storage_cache_dir_rejects_malformed_choices() {
for choice in [
r#"{"kind":"other"}"#,
r#"{"kind":"dir"}"#,
r#"{"kind":"main_disk","path":"/unexpected"}"#,
] {
let candidate = tier(
"user",
&format!(r#"{{"storage":{{"cache_dir":{choice}}}}}"#),
);
assert!(strict_tier_error(&candidate, None).is_some(), "{choice}");
let result = resolve_config(&[candidate]);
assert_eq!(
result.errors,
["invalid_cache_config: storage.cache_dir"],
"{choice}"
);
assert!(result.config.cache_config_unknown.is_some(), "{choice}");
assert!(!result.config.cache_dir_opt_out, "{choice}");
}
}
#[test]
fn storage_cache_dir_project_and_harness_choices_are_dropped() {
for choice in [
r#"{"kind":"default"}"#,
r#"{"kind":"main_disk"}"#,
r#"{"kind":"dir","path":"~/do-not-use"}"#,
] {
let storage = format!(r#""storage":{{"cache_dir":{choice}}}"#);
let result = resolve_config_for_harness(
&[
tier(
"user",
&format!(r#"{{"harnesses":{{"pi":{{{storage}}}}}}}"#),
),
tier("project", &format!(r#"{{{storage}}}"#)),
],
Some(&Harness::Pi),
);
assert!(result.errors.is_empty(), "{choice}: {:?}", result.errors);
assert!(result.config.cache_dir.is_none());
assert!(!result.config.cache_dir_opt_out);
for tier in ["user", "project"] {
assert!(result
.dropped
.iter()
.any(|drop| drop.tier == tier && drop.key == "storage.cache_dir"));
}
}
}
#[test]
fn memory_config_only_user_base_selects_machine_limits() {
use crate::memory_profile::MemoryMode;
for (name, expected) in [
("lean", MemoryMode::Lean),
("balanced", MemoryMode::Balanced),
] {
for harness in [Harness::Pi, Harness::Opencode] {
let result = resolve_config_for_harness(
&[
tier(
"user",
&format!(
r#"{{"memory":"{name}","harnesses":{{"pi":{{"memory":{{}},"sandbox":{{"profile":{{"worker":"strict"}}}}}},"opencode":{{"memory":null,"sandbox":{{"profile":{{"worker":"strict"}}}}}}}}}}"#
),
),
tier(
"project",
r#"{"memory":5,"harnesses":{"pi":{"memory":"fast"},"opencode":{"memory":"lean"}}}"#,
),
],
Some(&harness),
);
assert!(result.errors.is_empty(), "{:?}", result.errors);
assert_eq!(result.config.memory, Some(expected));
assert!(result
.dropped
.iter()
.any(|drop| drop.key == "memory" && drop.tier == "user"));
assert!(result
.dropped
.iter()
.any(|drop| drop.key == "memory" && drop.tier == "project"));
}
}
let project = resolve_config(&[tier("project", r#"{"memory":"lean"}"#)]);
assert!(project.errors.is_empty());
assert_eq!(project.config.memory, None);
}
#[test]
fn storage_cache_dir_only_user_base_can_select_storage_wide_root() {
let result = super::resolve_config_for_harness(&[
super::ConfigTier { tier: "user".into(), source: "user".into(), doc: r#"{"storage":{"cache_dir":"/cache/base"},"harnesses":{"pi":{"storage":{"cache_dir":"/cache/pi"}}}}"#.into() },
super::ConfigTier { tier: "project".into(), source: "project".into(), doc: r#"{"storage":{"cache_dir":"/evil"},"harnesses":{"pi":{"storage":{"cache_dir":"/evil/pi"}}}}"#.into() },
], Some(&crate::harness::Harness::Pi));
assert!(result.errors.is_empty());
assert_eq!(
result.config.cache_dir,
Some(std::path::PathBuf::from("/cache/base"))
);
assert!(result
.dropped
.iter()
.any(|dropped| dropped.key == "storage.cache_dir"));
}
#[test]
fn cache_dir_and_bash_env_keep_distinct_harness_trust_rules() {
// `storage.cache_dir` is storage-wide: only the user-tier base may set
// it, at either level. `bash.env` has its own per-tier rule: a harness
// block merges names, and a project's names are carried for the
// per-command trust check instead of being dropped. The two rules must
// not borrow from each other.
for harness in [
crate::harness::Harness::Opencode,
crate::harness::Harness::Pi,
] {
let result = super::resolve_config_for_harness(
&[
tier(
"user",
r#"{
"storage":{"cache_dir":"/cache/base"},
"bash":{"env":{"TZ":"UTC"}},
"harnesses":{
"opencode":{"storage":{"cache_dir":"/cache/override"},"bash":{"env":{"TZ":"Etc/GMT"}}},
"pi":{"storage":{"cache_dir":"/cache/override"},"bash":{"env":{"TZ":"Etc/GMT"}}}
}
}"#,
),
tier(
"project",
r#"{
"storage":{"cache_dir":"/evil"},
"bash":{"env":{"PROJECT_MARKER":"/evil/marker"}},
"harnesses":{
"opencode":{"storage":{"cache_dir":"/evil/override"},"bash":{"env":{"TZ":"project"}}},
"pi":{"storage":{"cache_dir":"/evil/override"},"bash":{"env":{"TZ":"project"}}}
}
}"#,
),
],
Some(&harness),
);
assert!(result.errors.is_empty(), "{:?}", result.errors);
// Only the user-tier base selects the cache root, at either level.
assert_eq!(result.config.cache_dir, Some("/cache/base".into()));
assert!(result
.dropped
.iter()
.any(|drop| drop.key == "storage.cache_dir" && drop.tier == "user"));
assert!(result
.dropped
.iter()
.any(|drop| drop.key == "storage.cache_dir" && drop.tier == "project"));
// The harness block merges its `bash.env` name over the base one.
assert_eq!(result.config.bash.env.len(), 1);
assert_eq!(result.config.bash.env["TZ"], "Etc/GMT");
// The project's names are carried for the per-command trust check,
// never merged into the user map and never reported as dropped.
assert_eq!(
result.config.bash.project_env.get("TZ").map(String::as_str),
Some("project")
);
assert!(result
.config
.bash
.project_env
.contains_key("PROJECT_MARKER"));
assert!(!result.dropped.iter().any(|drop| drop.key == "bash.env"));
}
}
#[test]
fn cache_dir_stays_fenced_when_bash_env_rejects_the_user_config() {
for in_harness in [false, true] {
let mut document = serde_json::json!({"storage":{"cache_dir":"/cache/base"}});
let blocked = serde_json::json!({"env":{"BASH_ENV":"/evil/startup"}});
if in_harness {
document["harnesses"] = serde_json::json!({"pi":{"bash":blocked}});
} else {
document["bash"] = blocked;
}
let result = super::resolve_config_for_harness(
&[tier("user", &document.to_string())],
Some(&crate::harness::Harness::Pi),
);
assert!(result
.errors
.iter()
.any(|error| error.contains("blocked bash.env key BASH_ENV")));
assert_eq!(result.config.cache_dir, Some("/cache/base".into()));
assert!(result.config.cache_config_unknown.is_some());
assert!(result.config.bash.env.is_empty());
}
}
#[test]
fn storage_cache_dir_relative_stays_unavailable_without_redirecting() {
let result = super::resolve_config(&[super::ConfigTier {
tier: "user".into(),
source: "user".into(),
doc: r#"{"storage":{"cache_dir":{"kind":"dir","path":"relative"}}}"#.into(),
}]);
assert_eq!(
result.config.cache_dir,
Some(std::path::PathBuf::from("relative"))
);
assert!(result.config.cache_unavailable.is_some());
assert!(result
.warnings
.iter()
.any(|warning| warning.code == "cache_dir_unavailable"
&& warning
.message
.contains("AFT is running without its caches until it is back.")));
}
#[test]
fn storage_cache_dir_expands_tilde_before_absolute_validation() {
let home = std::env::var_os("HOME")
.or_else(|| std::env::var_os("USERPROFILE"))
.map(std::path::PathBuf::from)
.unwrap();
let result = super::resolve_config(&[super::ConfigTier {
tier: "user".into(),
source: "user".into(),
doc: r#"{"storage":{"cache_dir":"~/aft-cache"}}"#.into(),
}]);
assert_eq!(result.config.cache_dir, Some(home.join("aft-cache")));
assert!(!result
.warnings
.iter()
.any(|warning| warning.code == "cache_dir_unavailable"));
}
use super::*;
#[test]
fn harness_ignored_keys_match_plugin_declarations() {
let source = include_str!("../../../packages/aft-bridge/src/config-keys.ts");
let declared = |name: &str| -> Vec<String> {
let prefix = format!("export const {name} = [");
let body = source
.split_once(&prefix)
.expect("host key declaration")
.1
.split_once(']')
.expect("host key list end")
.0;
body.split(',')
.map(str::trim)
.filter(|entry| !entry.is_empty())
.map(|entry| serde_json::from_str(entry).expect("literal host key"))
.collect()
};
for (harness, name) in [
(Harness::Pi, "OPENCODE_ONLY_KEYS"),
(Harness::Opencode, "PI_ONLY_KEYS"),
] {
assert_eq!(declared(name), harness_ignored_config_keys(Some(&harness)));
}
assert!(harness_ignored_config_keys(None).is_empty());
assert!(harness_ignored_config_keys(Some(&Harness::Runner)).is_empty());
}
#[test]
fn pi_ignored_keys_do_not_discard_active_harness_hardening() {
for tier_name in ["user", "project"] {
for ignored in [
serde_json::json!("opaque"),
Value::Null,
serde_json::json!(false),
serde_json::json!({"unexpected": true}),
] {
let input = tier(
tier_name,
&serde_json::json!({"harnesses":{"pi":{
"auto_update": ignored,
"sandbox":{"profile":{"worker":"strict"}}
}}})
.to_string(),
);
let resolved =
resolve_config_for_harness(std::slice::from_ref(&input), Some(&Harness::Pi));
assert!(resolved.errors.is_empty(), "{:?}", resolved.errors);
assert_eq!(
resolved.config.sandbox.profile.worker,
crate::config::SandboxMode::Strict
);
assert!(strict_tier_error(&input, Some(&Harness::Pi)).is_none());
assert!(!resolved
.warnings
.iter()
.any(|warning| warning.code == "invalid_harness_override"));
let (raw, _) =
parse_tier(&input, Some(&Harness::Pi), &mut Vec::new(), &mut Vec::new())
.unwrap();
assert!(raw.harnesses.unwrap()["pi"].get("auto_update").is_none());
}
}
}
#[test]
fn pi_ignored_keys_do_not_reject_root_hardening_on_reload() {
for tier_name in ["user", "project"] {
for ignored in [
serde_json::json!("opaque"),
Value::Null,
serde_json::json!(false),
serde_json::json!({"unexpected": true}),
] {
let input = tier(
tier_name,
&serde_json::json!({
"auto_update": ignored,
"sandbox":{"profile":{"worker":"strict"}}
})
.to_string(),
);
let resolved =
resolve_config_for_harness(std::slice::from_ref(&input), Some(&Harness::Pi));
assert!(resolved.errors.is_empty(), "{:?}", resolved.errors);
assert_eq!(
resolved.config.sandbox.profile.worker,
crate::config::SandboxMode::Strict
);
assert!(strict_tier_error(&input, Some(&Harness::Pi)).is_none());
let (raw, _) =
parse_tier(&input, Some(&Harness::Pi), &mut Vec::new(), &mut Vec::new())
.unwrap();
assert_eq!(raw.auto_update, None);
}
}
}
#[test]
fn opencode_owned_auto_update_remains_security_validated() {
let valid = tier("user", r#"{"auto_update":false}"#);
let (raw, _) = parse_tier(
&valid,
Some(&Harness::Opencode),
&mut Vec::new(),
&mut Vec::new(),
)
.unwrap();
assert_eq!(raw.auto_update, Some(false));
for tier_name in ["user", "project"] {
let root = tier(
tier_name,
r#"{"auto_update":"opaque","sandbox":{"profile":{"worker":"strict"}}}"#,
);
let active = tier(
tier_name,
r#"{"harnesses":{"opencode":{"auto_update":"opaque","sandbox":{"profile":{"worker":"strict"}}}}}"#,
);
assert_eq!(
resolve_config_for_harness(&[root], Some(&Harness::Opencode)).errors,
["invalid_security_config:auto_update"]
);
assert_eq!(
resolve_config_for_harness(&[active], Some(&Harness::Opencode)).errors,
["invalid_security_config:harnesses.opencode.auto_update"]
);
}
}
#[test]
fn discarded_nonsecurity_sections_are_named_without_rejecting_valid_settings() {
let result = resolve_config(&[tier(
"user",
r#"{"inspect":{"categories":{"diagnostics":"off"}},"format_on_edit":true}"#,
)]);
assert!(result.errors.is_empty());
assert!(result.config.format_on_edit);
assert!(result
.warnings
.iter()
.any(|warning| warning.code == "invalid_config_section"
&& warning.message == "Discarded invalid configuration section: inspect"));
}
#[test]
fn malformed_active_harness_hardening_rejects_but_inactive_blocks_stay_opaque() {
let tier = tier(
"user",
r#"{"harnesses":{"opencode":{"sandbox":{"profile":{"worker":5}}},"pi":{"sandbox":{"profile":{"worker":"strict"}}}}}"#,
);
let rejected =
resolve_config_for_harness(std::slice::from_ref(&tier), Some(&Harness::Opencode));
assert_eq!(
rejected.errors,
["invalid_security_config:harnesses.opencode.sandbox"]
);
let accepted = resolve_config_for_harness(&[tier], Some(&Harness::Pi));
assert!(accepted.errors.is_empty());
assert_eq!(
accepted.config.sandbox.profile.worker,
crate::config::SandboxMode::Strict
);
}
#[test]
fn malformed_security_sections_reject_candidate_without_resetting_last_good() {
for (key, value) in [
("sandbox", serde_json::json!({"profile": {"worker": 5}})),
("indexes", serde_json::json!({"semantic":"off"})),
("remote_exec", serde_json::json!({"enabled":"off"})),
("disabled_tools", serde_json::json!("aft_write")),
("restrict_to_project_root", serde_json::json!(1)),
] {
let tier = ConfigTier {
tier: "user".into(),
source: "malformed-security.jsonc".into(),
doc: serde_json::json!({key:value, "format_on_edit":true}).to_string(),
};
let mut last_good = Config {
restrict_to_project_root: true,
..Config::default()
};
let before = serde_json::to_value(&last_good).unwrap();
let diagnostics = resolve_config_onto_with_diagnostics(&[tier], &mut last_good);
assert_eq!(
diagnostics.errors,
[format!("invalid_security_config:{key}")]
);
assert_eq!(
serde_json::to_value(&last_good).unwrap(),
before,
"rejected {key} must not reset published hardening"
);
}
}
#[test]
fn unreadable_tier_document_does_not_silently_publish_defaults() {
let tier = ConfigTier {
tier: "user".into(),
source: "broken.jsonc".into(),
doc: "{".into(),
};
assert_eq!(resolve_config(&[tier]).errors, ["invalid_config_document"]);
}
#[test]
fn malformed_security_root_and_active_harness_sections_fail_closed() {
for key in [
"restrict_to_project_root",
"url_fetch_allow_private",
"sandbox",
"indexes",
"index",
"remote_exec",
"disabled_tools",
"bash",
"lsp",
"semantic",
"search",
"subc",
"opencode",
"github",
"gh_shim",
"auto_update",
] {
let root = tier("user", &serde_json::json!({key: null}).to_string());
assert_eq!(
resolve_config_for_harness(&[root], Some(&Harness::Opencode)).errors,
[format!("invalid_security_config:{key}")]
);
let active = tier(
"project",
&serde_json::json!({"harnesses": {"opencode": {key: null}}}).to_string(),
);
assert_eq!(
resolve_config_for_harness(&[active], Some(&Harness::Opencode)).errors,
[format!("invalid_security_config:harnesses.opencode.{key}")]
);
}
let mixed = tier(
"user",
r#"{"harnesses":{"opencode":{"sandbox":{"profile":{"worker":"strict"}},"inspect":false}}}"#,
);
assert_eq!(
resolve_config_for_harness(&[mixed], Some(&Harness::Opencode)).errors,
["invalid_security_config:harnesses.opencode"]
);
let pi = tier("user", r#"{"auto_update":"opaque"}"#);
assert!(resolve_config_for_harness(&[pi], Some(&Harness::Pi))
.errors
.is_empty());
for doc in ["null", "[]", "false", "1"] {
assert_eq!(
resolve_config(&[tier("project", doc)]).errors,
["invalid_config_document"]
);
}
}
#[test]
fn project_merge_moves_owned_semantic_section_without_cloning() {
let mut base: RawAftConfig = serde_json::from_value(serde_json::json!({
"semantic": {"model": "owned-user-model"}
}))
.unwrap();
let model_allocation = base
.semantic
.as_ref()
.unwrap()
.model
.as_ref()
.unwrap()
.as_ptr();
merge_project_config(&mut base, RawAftConfig::default());
assert_eq!(
base.semantic
.as_ref()
.unwrap()
.model
.as_ref()
.unwrap()
.as_ptr(),
model_allocation,
"an unspecified project override must retain the owned model allocation"
);
}
#[test]
fn lsp_idle_default_and_project_tightening() {
let default = resolve_config(&[]).config;
assert_eq!(default.lsp_idle_minutes, 60);
assert!(default.lsp_idle_shutdown);
for (user, project, minutes, shutdown, refused) in [
(
r#"{"idle_minutes":60}"#,
r#"{"idle_minutes":30}"#,
30,
true,
None,
),
(
r#"{"idle_minutes":30}"#,
r#"{"idle_minutes":60}"#,
30,
true,
Some("lsp.idle_minutes"),
),
(
r#"{"idle_shutdown":true}"#,
r#"{"idle_minutes":"never"}"#,
60,
true,
Some("lsp.idle_shutdown"),
),
(
r#"{"idle_minutes":30,"idle_shutdown":false}"#,
r#"{"idle_shutdown":true}"#,
30,
true,
None,
),
(
r#"{"idle_minutes":"never"}"#,
r#"{"idle_minutes":30,"idle_shutdown":false}"#,
30,
false,
None,
),
] {
let result = resolve_config(&[
tier("user", &format!(r#"{{"lsp":{user}}}"#)),
tier("project", &format!(r#"{{"lsp":{project}}}"#)),
]);
assert!(result.errors.is_empty(), "{:?}", result.errors);
assert_eq!(result.config.lsp_idle_minutes, minutes);
assert_eq!(result.config.lsp_idle_shutdown, shutdown);
assert_eq!(drop_keys(&result).first().map(String::as_str), refused);
}
}
#[test]
fn settings_shapes_preserve_legacy_true_in_harness_and_reject_explicit_null() {
let harness = resolve_config_for_harness(
&[tier(
"user",
r#"{"bash":{"enabled":false,"rewrite":false,"compress":false,"background":false},"harnesses":{"pi":{"bash":true}}}"#,
)],
Some(&Harness::Pi),
);
assert!(harness.errors.is_empty());
assert!(harness.config.bash.enabled);
assert!(harness.config.experimental_bash_rewrite);
assert!(harness.config.experimental_bash_compress);
assert!(harness.config.experimental_bash_background);
for (document, path) in [
(r#"{"lsp":{"idle_minutes":null}}"#, "lsp.idle_minutes"),
(r#"{"lsp":{"idle_shutdown":null}}"#, "lsp.idle_shutdown"),
(
r#"{"bash":{"memory_limit_mib":null}}"#,
"bash.memory_limit_mib",
),
(
r#"{"lsp":{"servers":{"rust":{"initialization_options":null}}}}"#,
"lsp.servers.rust.initialization_options",
),
(
r#"{"inspect":{"duplicates":{"expected_mirrors":null}}}"#,
"inspect.duplicates.expected_mirrors",
),
(
r#"{"harnesses":{"pi":{"format_on_edit":null}}}"#,
"harnesses.pi.format_on_edit",
),
] {
let candidate = tier("user", document);
let expected = format!("invalid_config_null:{path}");
assert_eq!(
strict_tier_error(&candidate, Some(&Harness::Pi)),
Some(expected.clone())
);
assert_eq!(
resolve_config_for_harness(&[candidate], Some(&Harness::Pi)).errors,
[expected]
);
}
let opt_out = resolve_config(&[tier("user", r#"{"storage":{"cache_dir":null}}"#)]);
assert!(opt_out.errors.is_empty());
assert!(opt_out.config.cache_dir_opt_out);
}
#[test]
fn lsp_max_servers_defaults_and_project_can_only_lower() {
assert_eq!(resolve_config(&[]).config.lsp_max_servers, 8);
for (user, project, expected, refused) in [
(8, 3, 3, false),
(3, 8, 3, true),
(8, 0, 0, false),
(16, 12, 12, false),
] {
let result = resolve_config(&[
tier("user", &format!(r#"{{"lsp":{{"max_servers":{user}}}}}"#)),
tier(
"project",
&format!(r#"{{"lsp":{{"max_servers":{project}}}}}"#),
),
]);
assert!(result.errors.is_empty(), "{:?}", result.errors);
assert_eq!(result.config.lsp_max_servers, expected);
assert_eq!(result.config.lsp_user_max_servers, Some(user));
assert_eq!(
drop_keys(&result).contains(&"lsp.max_servers".to_string()),
refused
);
}
let result = resolve_config(&[tier("project", r#"{"lsp":{"max_servers":23}}"#)]);
assert_eq!(result.config.lsp_max_servers, 8);
assert!(drop_keys(&result).contains(&"lsp.max_servers".to_string()));
}
#[test]
fn inspect_categories_project_can_only_disable() {
let result = resolve_config(&[
tier(
"user",
r#"{"inspect":{"categories":{"dead_code":false,"todos":true}}}"#,
),
tier(
"project",
r#"{"inspect":{"categories":{"dead_code":true,"todos":false}}}"#,
),
]);
assert!(result.errors.is_empty(), "{:?}", result.errors);
let config = serde_json::to_value(&result.config).unwrap();
assert_eq!(config["inspect"]["categories"]["dead_code"], false);
assert_eq!(config["inspect"]["categories"]["todos"], false);
assert_eq!(config["inspect"]["categories"]["diagnostics"], true);
assert!(drop_keys(&result).contains(&"inspect.categories.dead_code".to_string()));
}
/// One document per refused retired name, with the name the
/// refusal reports. Every entry of `REFUSED_RETIRED_PATHS` and every
/// prefixed tool name appears.
fn refused_retired_documents() -> Vec<(&'static str, Value)> {
let mut documents = vec![
(
"sandbox.enabled",
serde_json::json!({"sandbox": {"enabled": true}}),
),
(
"tool_surface",
serde_json::json!({"tool_surface": "minimal"}),
),
(
"hoist_builtin_tools",
serde_json::json!({"hoist_builtin_tools": false}),
),
("enabled", serde_json::json!({"enabled": false})),
("search_index", serde_json::json!({"search_index": false})),
(
"experimental_search_index",
serde_json::json!({"experimental_search_index": false}),
),
(
"semantic_search",
serde_json::json!({"semantic_search": false}),
),
(
"experimental_semantic_search",
serde_json::json!({"experimental_semantic_search": false}),
),
(
"callgraph_store",
serde_json::json!({"callgraph_store": false}),
),
(
"github.enabled",
serde_json::json!({"github": {"enabled": false}}),
),
("gh_read", serde_json::json!({"gh_read": {"enabled": true}})),
(
"gh_shim.enabled",
serde_json::json!({"gh_shim": {"enabled": false, "binary_path": "/opt/aft/bin/aft"}}),
),
(
"experimental_lsp_ty",
serde_json::json!({"experimental_lsp_ty": true}),
),
(
"experimental_bash_rewrite",
serde_json::json!({"experimental_bash_rewrite": true}),
),
(
"experimental_bash_compress",
serde_json::json!({"experimental_bash_compress": true}),
),
(
"experimental_bash_background",
serde_json::json!({"experimental_bash_background": true}),
),
(
"experimental.bash",
serde_json::json!({"experimental": {"bash": {"background": true}}}),
),
(
"experimental.bash",
serde_json::json!({"experimental": {"bash": {"long_running_reminder_interval_ms": 5000}}}),
),
(
"idle.lsp_ttl_minutes",
serde_json::json!({"idle": {"lsp_ttl_minutes": 10}}),
),
(
"inspect.tier2_soft_deadline_ms",
serde_json::json!({"inspect": {"tier2_soft_deadline_ms": 50}}),
),
(
"inspect.max_drill_down_items",
serde_json::json!({"inspect": {"max_drill_down_items": 20}}),
),
(
"views.enabled",
serde_json::json!({"views": {"enabled": true}}),
),
(
"views.callgraph_copies",
serde_json::json!({"views": {"callgraph_copies": 2}}),
),
(
"worktree.ram_overlay",
serde_json::json!({"worktree": {"ram_overlay": false}}),
),
];
for (alias, _) in feature_config::LEGACY_TOOL_ALIASES {
documents.push((alias, serde_json::json!({"disabled_tools": [alias]})));
}
documents
}
/// A refused retired name produces `removed_config_key`
/// in the user config, also inside a harness block, and `doctor --fix`
/// rewrites the file into one that loads. A project config with the same
/// name loads, with the name translated exactly as `doctor --fix` would
/// rewrite it.
#[test]
fn refused_retired_user_keys_are_refused_and_doctor_fix_repairs_them() {
let documents = refused_retired_documents();
let listed: std::collections::BTreeSet<&str> =
documents.iter().map(|(name, _)| *name).collect();
for path in feature_config::REFUSED_RETIRED_PATHS {
assert!(listed.contains(path), "{path} has no refusal case");
}
for (name, document) in documents {
for (prefix, document) in [
("", document.clone()),
(
"harnesses.pi.",
serde_json::json!({"harnesses": {"pi": document}}),
),
] {
let text = document.to_string();
for tier_name in ["user", "project"] {
let resolved =
resolve_config_for_harness(&[tier(tier_name, &text)], Some(&Harness::Pi));
if tier_name == "user" {
assert_eq!(
resolved.errors,
[format!(
"removed_config_key:{prefix}{name}; run npx @cortexkit/aft doctor --fix"
)],
"{tier_name}: {text}"
);
assert!(
strict_tier_error(&tier(tier_name, &text), Some(&Harness::Pi))
.is_some_and(|error| error.contains("removed_config_key:")),
"{tier_name}: {text}"
);
} else {
assert!(
resolved.errors.is_empty(),
"a project config loads: {text}: {:?}",
resolved.errors
);
assert_eq!(
strict_tier_error(&tier(tier_name, &text), Some(&Harness::Pi)),
None,
"{tier_name}: {text}"
);
}
let fix_tier = if tier_name == "user" {
crate::config_fix::FixTier::User
} else {
crate::config_fix::FixTier::Project
};
let fixed = crate::config_fix::migrate_config_text(&text, fix_tier)
.expect("doctor --fix rewrites the file");
assert!(fixed.changed, "{tier_name}: {text}");
let repaired = resolve_config_for_harness(
&[tier(tier_name, &fixed.text)],
Some(&Harness::Pi),
);
assert!(
repaired.errors.is_empty(),
"{tier_name}: {text} -> {}: {:?}",
fixed.text,
repaired.errors
);
if tier_name == "project" {
// The loaded project config means what the rewritten
// file means.
assert_eq!(
serde_json::to_value(&resolved.config).unwrap(),
serde_json::to_value(&repaired.config).unwrap(),
"{text} -> {}",
fixed.text
);
}
}
}
}
}
/// `doctor --fix` keeps what a refused name meant: the replacement keys
/// carry its value.
#[test]
fn doctor_fix_carries_refused_values_to_their_replacements() {
let fixed = |text: &str| {
let text =
crate::config_fix::migrate_config_text(text, crate::config_fix::FixTier::User)
.unwrap()
.text;
let result = resolve_config(&[tier("user", &text)]);
assert!(result.errors.is_empty(), "{text}: {:?}", result.errors);
result.config
};
let minutes =
|config: &Config| serde_json::to_value(config).unwrap()["lsp_idle_minutes"].clone();
assert_eq!(minutes(&fixed(r#"{"idle":{"lsp_ttl_minutes":10}}"#)), 10);
assert!(!fixed(r#"{"search_index":false}"#).indexes.trigram);
let reminder =
fixed(r#"{"experimental":{"bash":{"long_running_reminder_interval_ms":5000}}}"#);
assert_eq!(reminder.bash_long_running_reminder_interval_ms, 5000);
assert!(
reminder.experimental_bash_rewrite,
"the flags keep their defaults"
);
let background = fixed(r#"{"experimental":{"bash":{"background":true}}}"#);
assert!(background.experimental_bash_background);
assert!(!background.experimental_bash_rewrite);
assert!(!background.experimental_bash_compress);
let disabled = fixed(r#"{"disabled_tools":["aft_read"]}"#);
assert_eq!(disabled.disabled_tools, ["read"]);
}
/// At 0.64, names retired in 0.63 or 0.64 still load in either tier: AFT
/// translates them in memory and says so in a notice.
#[test]
fn names_retired_in_the_last_two_releases_still_translate() {
let _release = feature_config::override_running_release_for_test((0, 64));
for tier_name in ["user", "project"] {
let hang = resolve_config(&[tier(tier_name, r#"{"bridge":{"hang_threshold":2}}"#)]);
assert!(hang.errors.is_empty(), "{tier_name}: {:?}", hang.errors);
let checkout =
resolve_config(&[tier(tier_name, r#"{"views":{"idle_checkout_hours":72}}"#)]);
assert!(
checkout.errors.is_empty(),
"{tier_name}: {:?}",
checkout.errors
);
assert_eq!(checkout.config.idle.checkout_hours, 72);
}
}
fn tier(tier: &str, doc: &str) -> ConfigTier {
ConfigTier {
tier: tier.to_string(),
source: format!("/tmp/{tier}/aft.jsonc"),
doc: doc.to_string(),
}
}
fn drop_keys(result: &ResolveResult) -> Vec<String> {
result
.dropped
.iter()
.map(|dropped| dropped.key.clone())
.collect()
}
/// The project tier may switch a user-enabled reranker off.
#[test]
fn a_project_may_turn_rerank_off() {
let result = resolve_config(&[
tier(
"user",
r#"{"search": {"rerank": {"backend": "onnx", "model": "bge-reranker-base", "top_n": 15}}}"#,
),
tier("project", r#"{"search": {"rerank": {"backend": "off"}}}"#),
]);
assert!(result.errors.is_empty(), "{:?}", result.errors);
assert!(drop_keys(&result).is_empty(), "{:?}", result.dropped);
let rerank = result.config.search.rerank.expect("rerank block");
assert_eq!(rerank.backend, Some(RerankBackendKind::Off));
// The user's other settings stay as they were.
assert_eq!(rerank.model.as_deref(), Some("bge-reranker-base"));
assert_eq!(rerank.top_n, Some(15));
}
/// Every other project-tier rerank value is dropped and reported, and the
/// user's values (or their absence) stand.
#[test]
fn project_rerank_overrides_other_than_off_are_dropped_and_reported() {
let project = r#"{"search": {"rerank": {
"backend": "remote",
"model": "evil-model",
"endpoint": "https://evil.example.test/rerank",
"api_key_env": "EVIL_KEY",
"top_n": 200,
"timeout_ms": 60000
}}}"#;
for user in [
None,
Some(r#"{"search": {"rerank": {"backend": "onnx", "timeout_ms": 800}}}"#),
] {
let mut tiers = Vec::new();
if let Some(user) = user {
tiers.push(tier("user", user));
}
tiers.push(tier("project", project));
let result = resolve_config(&tiers);
assert!(result.errors.is_empty(), "{:?}", result.errors);
assert_eq!(
drop_keys(&result),
[
"search.rerank.backend",
"search.rerank.model",
"search.rerank.endpoint",
"search.rerank.api_key_env",
"search.rerank.top_n",
"search.rerank.timeout_ms",
]
);
assert!(result.dropped.iter().all(
|dropped| dropped.reason == RERANK_PROJECT_REASON && dropped.tier == "project"
));
match user {
None => assert_eq!(result.config.search, SearchConfig::default()),
Some(_) => assert_eq!(
result.config.search.rerank,
Some(RerankConfig {
backend: Some(RerankBackendKind::Onnx),
timeout_ms: Some(800),
..RerankConfig::default()
})
),
}
}
}
/// A project harness block is still project tier: it cannot enable rerank.
#[test]
fn a_project_harness_block_cannot_enable_rerank() {
let result = resolve_config_for_harness(
&[tier(
"project",
r#"{"harnesses": {"opencode": {"search": {"rerank": {"backend": "onnx"}}}}}"#,
)],
Some(&Harness::Opencode),
);
assert_eq!(drop_keys(&result), ["search.rerank.backend"]);
assert_eq!(result.config.search, SearchConfig::default());
}
#[test]
fn a_superseded_legacy_note_is_logged_once_per_file_and_text() {
let source = "/tmp/superseded-note-test/aft.jsonc";
assert!(first_superseded_note(source, "base", "note"));
assert!(!first_superseded_note(source, "base", "note"));
assert!(first_superseded_note(source, "base", "changed note"));
assert!(first_superseded_note(
"/tmp/other/aft.jsonc",
"base",
"note"
));
}
/// A project's former registration gates (`backup.enabled: false`,
/// `bash: false`) never bring back the move/delete default the user
/// switched off with an explicit empty list.
#[test]
fn project_legacy_keys_do_not_reapply_the_default_disables() {
for project in [r#"{"backup": {"enabled": false}}"#, r#"{"bash": false}"#] {
let result = resolve_config_for_harness(
&[
tier("user", r#"{"disabled_tools": []}"#),
tier("project", project),
],
None,
);
assert!(result.errors.is_empty());
for kept in ["aft_move", "aft_delete"] {
assert!(
!result.config.disabled_tools.iter().any(|name| name == kept),
"{project}: {kept}"
);
}
}
}
/// Security invariant (Oracle drift decision): nested objects are non-strict
/// (match TS z.object — unknown nested keys are stripped, object survives),
/// but the TOP-LEVEL RawAftConfig stays strict. A privileged process-state
/// field is top-level, so a project tier trying to smuggle one still hits the
/// strict top-level → that tier fails full parse, and partial-parse drops the
/// unknown key. It can NEVER reach Config.
#[test]
fn nested_unknown_keys_are_stripped_but_top_level_privileged_keys_cannot_smuggle() {
// Nested unknown key: stripped, object survives, and the bash object
// resolves as enabled. The point: the unknown key did not fail the
// parse — the object survived and resolved.
let nested = resolve_config(&[tier(
"user",
r#"{ "disabled_tools": [], "bash": { "unknown_key": true } }"#,
)]);
assert!(nested.config.experimental_bash_rewrite);
assert!(nested.config.experimental_bash_compress);
assert!(nested.config.experimental_bash_background);
// Top-level privileged process-state field (storage_dir) from a PROJECT
// tier: not in RawAftConfig → full parse fails → partial-parse drops it.
// It must never appear in Config (Config keeps its default storage_dir).
let smuggle = resolve_config(&[
tier("user", r#"{ "indexes": { "trigram": true } }"#),
tier(
"project",
r#"{ "storage_dir": "/tmp/evil", "bash_permissions": true, "indexes": { "trigram": false } }"#,
),
]);
// The valid project index setting still applies via partial parsing.
assert!(!smuggle.config.indexes.trigram);
// The smuggled process-state fields never reach Config.
assert!(smuggle.config.storage_dir.is_none());
assert!(!smuggle.config.bash_permissions);
}
#[test]
fn config_resolve_empty_tiers_applies_bash_surface_default() {
// No config file ⇒ empty config object, which still flows through the
// resolver and picks up the bash surface default (recommended ⇒ on),
// matching the TS pipeline (golden fixture `empty`). NOT Config::default()
// — that would leave bash off, diverging from TS.
let result = resolve_config(&[]);
let default_config = Config::default();
assert!(result.dropped.is_empty());
// Non-bash fields stay at runtime default.
assert_eq!(result.config.format_on_edit, default_config.format_on_edit);
assert_eq!(result.config.indexes, default_config.indexes);
assert_eq!(result.config.disabled_tools, ["aft_delete", "aft_move"]);
assert_eq!(result.config.semantic, default_config.semantic);
assert_eq!(
result.config.inspect.enabled,
default_config.inspect.enabled
);
assert_eq!(result.config.lsp_servers.len(), 0);
// Bash surface default: recommended ⇒ rewrite/compress/background all on.
assert!(result.config.experimental_bash_rewrite);
assert!(result.config.experimental_bash_compress);
assert!(result.config.experimental_bash_background);
}
#[test]
fn bash_watch_sync_max_defaults_clamps_and_warns() {
let default_result = resolve_config(&[]);
assert_eq!(
default_result.config.bash.watch_sync_max_ms,
DEFAULT_BASH_WATCH_SYNC_MAX_MS
);
assert!(default_result
.warnings
.iter()
.all(|warning| warning.key != "bash.watch_sync_max_ms"));
let clamped = resolve_config(&[tier("user", r#"{ "bash": { "watch_sync_max_ms": 5 } }"#)]);
assert_eq!(
clamped.config.bash.watch_sync_max_ms,
MIN_BASH_WATCH_SYNC_MAX_MS
);
assert!(clamped.warnings.iter().any(|warning| {
warning.code == "clamped_bash_watch_sync_max_ms"
&& warning.key == "bash.watch_sync_max_ms"
&& warning.value == "5"
}));
let project_override = resolve_config(&[
tier("user", r#"{ "bash": { "watch_sync_max_ms": 120000 } }"#),
tier("project", r#"{ "bash": { "watch_sync_max_ms": 1800000 } }"#),
]);
assert_eq!(
project_override.config.bash.watch_sync_max_ms,
MAX_BASH_WATCH_SYNC_MAX_MS
);
}
/// `bash.worker_wait_max_ms` defaults to 30 minutes, a project may set it
/// (it only changes how long a worker waits), and a value below the
/// one-minute minimum is rejected instead of clamped. An invalid bash block
/// can discard permission/scope settings, so initial load and live reload
/// both refuse the candidate rather than applying neighboring settings.
#[test]
fn bash_worker_wait_max_defaults_accepts_project_and_rejects_below_minimum() {
assert_eq!(
resolve_config(&[]).config.bash.worker_wait_max_ms,
DEFAULT_BASH_WORKER_WAIT_MAX_MS
);
let project_override = resolve_config(&[
tier("user", r#"{ "bash": { "worker_wait_max_ms": 600000 } }"#),
tier("project", r#"{ "bash": { "worker_wait_max_ms": 120000 } }"#),
]);
assert!(project_override.errors.is_empty());
assert_eq!(project_override.config.bash.worker_wait_max_ms, 120_000);
assert!(project_override
.dropped
.iter()
.all(|drop| !drop.key.contains("worker_wait_max_ms")));
let below = tier(
"user",
r#"{ "format_on_edit": false, "bash": { "compress": false, "worker_wait_max_ms": 59999 } }"#,
);
let error = strict_tier_error(&below, None).expect("below-minimum value is an error");
assert!(
error.contains("bash.worker_wait_max_ms must be at least 60000"),
"{error}"
);
let resolved = resolve_config(&[below]);
assert_eq!(resolved.errors, ["invalid_security_config:bash"]);
let minimum = resolve_config(&[tier(
"user",
&format!(r#"{{ "bash": {{ "worker_wait_max_ms": {MIN_BASH_WORKER_WAIT_MAX_MS} }} }}"#),
)]);
assert_eq!(
minimum.config.bash.worker_wait_max_ms,
MIN_BASH_WORKER_WAIT_MAX_MS
);
}
#[test]
fn bash_env_keeps_user_and_project_maps_apart() {
// A project's values are no longer dropped: they are validated and
// carried in `project_env`, which `commands/bash.rs` applies only while
// the project root is trusted.
let result = resolve_config(&[
tier(
"user",
r#"{"bash":{"env":{"TZ":"UTC","SOME_USER_ENV":"from-user"}}}"#,
),
tier(
"project",
r#"{"bash":{"env":{"TZ":"Mars","SOME_PROJECT_ENV":"from-project"}}}"#,
),
]);
assert!(result.errors.is_empty(), "{:?}", result.errors);
assert_eq!(
result.config.bash.env.get("TZ").map(String::as_str),
Some("UTC")
);
assert_eq!(
result
.config
.bash
.env
.get("SOME_USER_ENV")
.map(String::as_str),
Some("from-user")
);
assert!(!result.config.bash.env.contains_key("SOME_PROJECT_ENV"));
assert_eq!(
result.config.bash.project_env.get("TZ").map(String::as_str),
Some("Mars")
);
assert_eq!(
result
.config
.bash
.project_env
.get("SOME_PROJECT_ENV")
.map(String::as_str),
Some("from-project")
);
assert!(!result.dropped.iter().any(|drop| drop.key == "bash.env"));
}
#[test]
fn bash_env_harness_block_merges_names_into_the_base_map() {
// A harness block adds or replaces single names; it no longer replaces
// the whole map, which used to drop every base name silently.
let result = resolve_config_for_harness(
&[tier(
"user",
r#"{
"bash": { "env": { "BASE_NAME": "base", "SHARED_NAME": "base" } },
"harnesses": { "opencode": { "bash": { "env": { "HARNESS_NAME": "harness", "SHARED_NAME": "harness" } } } }
}"#,
)],
Some(&Harness::Opencode),
);
assert!(result.errors.is_empty(), "{:?}", result.errors);
let env = &result.config.bash.env;
assert_eq!(env.get("BASE_NAME").map(String::as_str), Some("base"));
assert_eq!(env.get("HARNESS_NAME").map(String::as_str), Some("harness"));
assert_eq!(env.get("SHARED_NAME").map(String::as_str), Some("harness"));
}
#[test]
fn bash_runon_env_is_user_only() {
let result = resolve_config(&[
tier(
"user",
r#"{"bash":{"env":{"TZ":"UTC"},"runon_env":["TZ"]}}"#,
),
tier(
"project",
r#"{"bash":{"env":{"IBToolNeverDeque":"1"},"runon_env":["IBToolNeverDeque"]}}"#,
),
]);
assert!(result.errors.is_empty(), "{:?}", result.errors);
assert_eq!(result.config.bash.runon_env, ["TZ"]);
assert!(
result
.dropped
.iter()
.any(|drop| drop.key == "bash.runon_env"),
"{:?}",
result.dropped
);
}
#[test]
fn shell_env_provider_is_off_by_default_and_user_only() {
assert!(resolve_config(&[]).config.shell.env_provider.is_none());
let result = resolve_config(&[
tier("user", r#"{"shell":{"env_provider":{"kind":"mise"}}}"#),
tier(
"project",
r#"{"shell":{"env_provider":{"kind":"custom","command":["hostile"]}}}"#,
),
]);
assert!(result.errors.is_empty(), "{:?}", result.errors);
let provider = result.config.shell.env_provider.unwrap();
assert_eq!(provider.kind, crate::config::ShellEnvProviderKind::Mise);
assert_eq!(provider.timeout_ms, 2000);
assert_eq!(provider.argv(), ["mise", "env", "--json"]);
assert!(result
.dropped
.iter()
.any(|drop| drop.key == "shell.env_provider"));
let project = resolve_config(&[tier(
"project",
r#"{"shell":{"env_provider":{"kind":"mise"}}}"#,
)]);
assert!(project.config.shell.env_provider.is_none());
}
#[test]
fn shell_env_provider_validates_command_timeout_and_platform() {
for kind in ["mise", "direnv"] {
let result = resolve_config(&[tier(
"user",
&format!(
r#"{{"shell":{{"env_provider":{{"kind":"{kind}","watch":["ignored.env"]}}}}}}"#
),
)]);
assert_eq!(
result.errors,
["invalid_security_config:shell.env_provider.watch"]
);
}
for provider in [
r#"{"kind":"custom"}"#,
r#"{"kind":"mise","timeout_ms":99}"#,
r#"{"kind":"mise","timeout_ms":10001}"#,
r#"{"kind":"custom","command":[]}"#,
] {
let result = resolve_config(&[tier(
"user",
&format!(r#"{{"shell":{{"env_provider":{provider}}}}}"#),
)]);
assert!(!result.errors.is_empty(), "{provider}");
}
let direnv = resolve_config(&[tier(
"user",
r#"{"shell":{"env_provider":{"kind":"direnv"}}}"#,
)]);
if cfg!(windows) {
assert!(direnv
.errors
.iter()
.any(|error| error.contains("direnv is not supported on Windows")));
} else {
assert!(direnv.errors.is_empty(), "{:?}", direnv.errors);
assert_eq!(
direnv.config.shell.env_provider.unwrap().argv(),
["direnv", "export", "json"]
);
}
}
#[test]
fn bash_env_null_value_rejects_the_candidate() {
let project = tier("project", r#"{"bash":{"env":{"TZ":null}}}"#);
let result = resolve_config(std::slice::from_ref(&project));
assert_eq!(result.errors, ["invalid_security_config:bash"]);
let strict = strict_tier_error(&project, None).unwrap_or_default();
assert_eq!(strict, "invalid_config_null:bash.env.TZ");
}
/// One representative name per refused group, at each tier and each place
/// a tier can write it. The expectation is a rejected candidate whose error
/// names the key.
#[test]
fn refused_bash_env_names_reject_the_candidate_at_every_tier() {
// (name, refused at user tier, refused at project tier)
let cases: &[(&str, bool, bool)] = &[
("PATH", true, true),
("LD_PRELOAD", true, true),
("path", true, true),
("HOME", true, true),
("XDG_CONFIG_HOME", true, true),
("NODE_PATH", true, true),
("Git_Config_Count", true, true),
("GIT_DIR", true, true),
("aft_x", true, true),
("SUBC_X", true, true),
("SCCACHE_DIR", true, true),
("RUST_TEST_THREADS", true, true),
("NEXTEST_TEST_THREADS", true, true),
("RUSTC_WRAPPER", true, true),
("AFT_INTERNAL_LINUX_SCOPE", true, true),
// Project-tier-only: the user's own file may set them.
("API_KEY", false, true),
("NPM_TOKEN", false, true),
("AWS_PROFILE", false, true),
("GH_HOST", false, true),
("SSH_AUTH_SOCK", false, true),
("HTTPS_PROXY", false, true),
("NODE_EXTRA_CA_CERTS", false, true),
];
for (name, refused_user, refused_project) in cases {
for in_harness in [false, true] {
let doc = |name: &str| {
let env = format!(r#""env": {{ "{name}": "value" }}"#);
if in_harness {
format!(r#"{{ "harnesses": {{ "opencode": {{ "bash": {{ {env} }} }} }} }}"#)
} else {
format!(r#"{{ "bash": {{ {env} }} }}"#)
}
};
for (tier_name, refused) in [("user", *refused_user), ("project", *refused_project)]
{
let config_tier = tier(tier_name, &doc(name));
let result = resolve_config_for_harness(
std::slice::from_ref(&config_tier),
Some(&Harness::Opencode),
);
let where_set = if in_harness {
" in harnesses.opencode"
} else {
""
};
if refused {
assert_eq!(
result.errors.len(),
1,
"{tier_name} {name}{where_set}: {:?}",
result.errors
);
let error = &result.errors[0];
// Whichever block carried the name, the error names it.
assert!(
error.contains(&format!("key {name}")),
"{tier_name} {name}{where_set}: {error}"
);
let strict = strict_tier_error(&config_tier, Some(&Harness::Opencode))
.unwrap_or_default();
if in_harness {
assert!(strict.contains("in harnesses.opencode"), "{strict}");
} else {
assert!(strict.contains(&format!("key {name}")), "{strict}");
}
} else {
assert!(
result.errors.is_empty(),
"{tier_name} {name}{where_set} must be accepted: {:?}",
result.errors
);
let kept = match tier_name {
"user" => result.config.bash.env.contains_key(*name),
_ => result.config.bash.project_env.contains_key(*name),
};
assert!(kept, "{tier_name} {name}{where_set} must be kept");
}
}
}
}
}
#[test]
fn refused_project_bash_env_name_rejects_even_though_the_project_is_untrusted() {
// Validation is trust-blind: a bad commit fails for its author at once
// rather than on the first machine that trusts it.
let result = resolve_config(&[
tier("user", "{}"),
tier("project", r#"{"bash":{"env":{"API_KEY":"x"}}}"#),
]);
assert_eq!(result.errors.len(), 1, "{:?}", result.errors);
assert!(result.errors[0].contains("API_KEY"), "{:?}", result.errors);
}
#[test]
fn bash_env_names_differing_only_by_case_in_one_tier_are_not_tested_here() {
// Two names that differ only by case collapse into one on Windows, so
// the maps are keyed by name; this test pins that a single name is
// still reported once rather than as a duplicate.
let result = resolve_config(&[tier("user", r#"{"bash":{"env":{"TZ":"UTC"}}}"#)]);
assert_eq!(result.config.bash.env.len(), 1);
assert!(result.config.bash.project_env.is_empty());
}
#[test]
fn bash_env_rejects_preexec_hijack_keys_at_config_load() {
let user = tier(
"user",
r#"{"bash":{"env":{"NODE_OPTIONS":"--require evil"}}}"#,
);
let result = resolve_config(std::slice::from_ref(&user));
let error = result.errors.join(" ");
assert!(error.contains("bash.env"), "{error}");
assert!(error.contains("NODE_OPTIONS"), "{error}");
assert!(error.contains("blocked"), "{error}");
let strict_error = strict_tier_error(&user, None).unwrap_or_default();
assert!(strict_error.contains("NODE_OPTIONS"), "{strict_error}");
}
#[test]
fn config_resolve_user_only_config_applies_fields() {
let result = resolve_config(&[tier(
"user",
r#"{
"$schema": "https://example.test/aft.schema.json",
"format_on_edit": false,
"formatter_timeout_secs": 42,
"type_checker_timeout_secs": 43,
"validate_on_edit": "full",
"formatter": { "rust": "rustfmt", "typescript": "prettier" },
"checker": { "rust": "cargo", "typescript": "tsc" },
"restrict_to_project_root": true,
"indexes": { "trigram": true, "semantic": true, "callgraph": false },
"memory": "balanced",
"url_fetch_allow_private": true,
"semantic": {
"backend": "openai_compatible",
"model": " user-model ",
"base_url": "https://semantic.example.test",
"api_key_env": "AFT_API_KEY",
"timeout_ms": 12345,
"query_timeout_ms": 2345,
"max_batch_size": 12,
"max_input_tokens": 2048,
"max_files": 3456
},
"inspect": { "enabled": false, "diagnostics_timeout_ms": 15000 },
"experimental": { "lsp_ty": true },
"lsp": {
"servers": {
"rust": { "extensions": [".rs"], "binary": "rust-analyzer" }
},
"disabled": ["Python"],
"python": "pyright"
},
"bash": { "rewrite": false, "compress": true, "background": false,
"long_running_reminder_enabled": false,
"long_running_reminder_interval_ms": 123000 }
}"#,
)]);
assert!(result.dropped.is_empty());
assert!(!result.config.format_on_edit);
assert_eq!(result.config.formatter_timeout_secs, 42);
assert_eq!(result.config.type_checker_timeout_secs, 43);
assert_eq!(result.config.validate_on_edit.as_deref(), Some("full"));
assert_eq!(
result.config.formatter.get("rust").map(String::as_str),
Some("rustfmt")
);
assert_eq!(
result.config.checker.get("typescript").map(String::as_str),
Some("tsc")
);
assert!(result.config.restrict_to_project_root);
assert!(result.config.indexes.trigram);
assert!(result.config.indexes.semantic);
assert!(!result.config.indexes.callgraph);
assert_eq!(
result.config.memory,
Some(crate::memory_profile::MemoryMode::Balanced)
);
assert!(result.config.url_fetch_allow_private);
assert_eq!(
result.config.semantic.backend,
SemanticBackend::OpenAiCompatible
);
assert_eq!(result.config.semantic.model, "user-model");
assert_eq!(
result.config.semantic.base_url.as_deref(),
Some("https://semantic.example.test")
);
assert_eq!(
result.config.semantic.api_key_env.as_deref(),
Some("AFT_API_KEY")
);
assert_eq!(result.config.semantic.timeout_ms, 12345);
assert_eq!(result.config.semantic.query_timeout_ms, 2345);
assert_eq!(result.config.semantic.max_batch_size, 12);
assert_eq!(result.config.semantic.max_input_tokens, Some(2048));
assert_eq!(result.config.semantic.max_files, 3456);
assert!(!result.config.inspect.enabled);
assert_eq!(result.config.inspect.diagnostics_timeout_ms, 15_000);
assert!(!result.config.experimental_lsp_ty);
assert!(result.config.disabled_lsp.contains("ty"));
assert_eq!(result.config.lsp_servers.len(), 1);
assert_eq!(result.config.lsp_servers[0].id, "rust");
assert_eq!(
result.config.lsp_servers[0].extensions,
vec!["rs".to_string()]
);
assert_eq!(result.config.lsp_servers[0].binary, "rust-analyzer");
assert_eq!(result.config.lsp_servers[0].args, Vec::<String>::new());
assert_eq!(
result.config.lsp_servers[0].root_markers,
vec![".git".to_string()]
);
assert!(!result.config.experimental_bash_rewrite);
assert!(result.config.experimental_bash_compress);
assert!(!result.config.experimental_bash_background);
assert!(!result.config.bash_long_running_reminder_enabled);
assert_eq!(result.config.bash_long_running_reminder_interval_ms, 123000);
}
#[test]
fn edit_mode_resolves_at_user_and_project_tiers_with_project_precedence() {
let hashline = resolve_config(&[
tier("user", r#"{"edit_mode":"default"}"#),
tier("project", r#"{"edit_mode":"hashline"}"#),
]);
assert!(hashline.config.hashline_enabled);
assert!(hashline.dropped.is_empty());
let default = resolve_config(&[
tier("user", r#"{"edit_mode":"hashline"}"#),
tier("project", r#"{"edit_mode":"default"}"#),
]);
assert!(!default.config.hashline_enabled);
assert!(default.dropped.is_empty());
}
#[test]
fn harness_overrides_select_the_active_harness_and_preserve_tier_order() {
let tiers = [
tier(
"user",
r#"{
"disabled_tools": ["aft_delete", "aft_move", "apply_patch", "bash", "edit", "glob", "grep", "read", "write"],
"harnesses": {
"opencode": { "disabled_tools": [] },
"pi": { "disabled_tools": ["apply_patch", "bash", "edit", "glob", "grep", "read", "write"] }
}
}"#,
),
tier(
"project",
r#"{
"disabled_tools": ["apply_patch", "bash", "edit", "glob", "grep", "read", "write"],
"harnesses": { "opencode": { "disabled_tools": [] } }
}"#,
),
];
let opencode = resolve_config_for_harness(&tiers, Some(&Harness::Opencode));
let pi = resolve_config_for_harness(&tiers, Some(&Harness::Pi));
// The user base already disables the host names; a harness block can
// only add disables, so the OpenCode empty list cannot re-enable them.
// The project's host disables are ignored: host slots are protected
// from project disables.
let hosts_and_default = [
"aft_delete",
"aft_move",
"apply_patch",
"bash",
"edit",
"glob",
"grep",
"read",
"write",
];
assert_eq!(opencode.config.disabled_tools, hosts_and_default);
assert_eq!(pi.config.disabled_tools, hosts_and_default);
let harness_only = [tier(
"user",
r#"{ "harnesses": { "pi": { "disabled_tools": ["apply_patch", "bash", "edit", "glob", "grep", "read", "write"] } } }"#,
)];
assert_eq!(
resolve_config_for_harness(&harness_only, Some(&Harness::Opencode),)
.config
.disabled_tools,
["aft_delete", "aft_move"]
);
assert_eq!(
resolve_config_for_harness(&harness_only, Some(&Harness::Pi),)
.config
.disabled_tools,
hosts_and_default
);
}
#[test]
fn project_harness_overrides_are_filtered_at_the_existing_trust_boundary() {
let result = resolve_config_for_harness(
&[
tier(
"user",
r#"{
"restrict_to_project_root": true,
"semantic": {
"backend": "ollama",
"base_url": "http://localhost:11434",
"api_key_env": "USER_KEY"
},
"sandbox": { "profile": { "worker": "strict", "head": "strict" }, "write_allow": ["/user/write"] }
}"#,
),
tier(
"project",
r#"{
"harnesses": {
"opencode": {
"edit_mode": "hashline",
"restrict_to_project_root": false,
"semantic": {
"backend": "openai_compatible",
"base_url": "https://evil.example.test",
"api_key_env": "EVIL_KEY"
},
"subc": { "connection_file": "/tmp/evil-subc.json" },
"sandbox": { "profile": { "worker": "relaxed", "head": "off" }, "write_allow": ["/project/write"] }
}
}
}"#,
),
],
Some(&Harness::Opencode),
);
assert!(result.config.hashline_enabled);
assert!(result.config.restrict_to_project_root);
assert_eq!(result.config.semantic.backend, SemanticBackend::Ollama);
assert_eq!(
result.config.semantic.api_key_env.as_deref(),
Some("USER_KEY")
);
assert!(result.config.sandbox.head_enabled());
assert_eq!(
result.config.sandbox.write_allow,
vec![PathBuf::from("/user/write")]
);
let keys = drop_keys(&result);
for key in [
"restrict_to_project_root",
"semantic.backend",
"semantic.base_url",
"semantic.api_key_env",
"subc",
"sandbox.profile.head",
"sandbox.write_allow",
] {
assert!(keys.contains(&key.to_string()), "missing dropped key {key}");
}
}
#[test]
fn github_is_user_only_and_records_project_drops() {
let remains_disabled = resolve_config(&[
tier(
"user",
r#"{"github":{"shim":false,"read":false,"write":false}}"#,
),
tier(
"project",
r#"{"github":{"shim":true,"read":true,"write":true}}"#,
),
]);
assert!(!remains_disabled.config.github.shim);
assert!(!remains_disabled.config.github.read);
assert!(!remains_disabled.config.github.write);
assert_eq!(drop_keys(&remains_disabled), vec!["github"]);
assert_eq!(remains_disabled.dropped[0].tier, "project");
assert_eq!(remains_disabled.dropped[0].reason, USER_ONLY_REASON);
}
#[test]
fn removed_opencode_prompt_keys_refuse_every_tier_and_harness() {
for tier_name in ["user", "project"] {
for doc in [
r#"{"opencode":{"server_url":"http://127.0.0.1:4096","server_password_env":"PW"}}"#,
r#"{"harnesses":{"opencode":{"opencode":{"server_url":"http://127.0.0.1:4096"}}}}"#,
] {
let input = tier(tier_name, doc);
let result = resolve_config_for_harness(&[input.clone()], Some(&Harness::Opencode));
assert!(!result.errors.is_empty());
assert!(result
.errors
.iter()
.all(|error| error.starts_with("removed_config_key:")));
assert!(strict_tier_error(&input, Some(&Harness::Opencode))
.unwrap()
.contains("removed_config_key:"));
}
}
}
#[test]
fn removed_opencode_keys_in_ignored_deeper_harnesses_load() {
for tier_name in ["user", "project"] {
let input = tier(
tier_name,
r#"{"harnesses":{"opencode":{"harnesses":{"pi":{"opencode":{"server_url":"http://127.0.0.1:4096","server_password_env":"PW"}}}}}}"#,
);
let result = resolve_config_for_harness(&[input.clone()], Some(&Harness::Opencode));
assert!(result.errors.is_empty(), "{:?}", result.errors);
let strict = strict_tier_error(&input, Some(&Harness::Opencode));
assert!(
strict.is_none(),
"strict loader rejected ignored data: {strict:?}"
);
}
}
#[test]
fn github_write_forces_read_and_records_a_warning_naming_both_keys() {
let result = resolve_config(&[tier("user", r#"{"github":{"write":true,"read":false}}"#)]);
assert!(result.config.github.write);
assert!(result.config.github.read);
let warning = result
.warnings
.iter()
.find(|warning| warning.code == "github_write_requires_read")
.expect("write-implies-read warning");
assert_eq!(warning.key, "github.write");
assert!(warning.message.contains("github.write"));
assert!(warning.message.contains("github.read"));
}
/// `gh_shim.enabled` is refused, but the supported binary override alone
/// is not a retired name and still loads.
#[test]
fn gh_shim_binary_path_alone_still_loads() {
let binary = resolve_config(&[tier(
"user",
r#"{"gh_shim":{"binary_path":"/opt/aft/bin/aft"}}"#,
)]);
assert!(binary.errors.is_empty(), "{:?}", binary.errors);
assert_eq!(
binary.config.gh_shim.binary_path,
Some(PathBuf::from("/opt/aft/bin/aft"))
);
}
#[test]
fn git_co_author_accepts_project_precedence_and_rejects_invalid_identities() {
let resolved = resolve_config(&[
tier("user", r#"{"git":{"co_author":"auto"}}"#),
tier(
"project",
r#"{"git":{"co_author":"Pair Agent <pair@example.test>"}}"#,
),
]);
assert_eq!(
resolved.config.git.co_author,
"Pair Agent <pair@example.test>"
);
assert!(resolved.dropped.is_empty());
let invalid = resolve_config(&[tier(
"user",
r#"{"git":{"co_author":"not-an-identity"},"indexes":{"trigram":true}}"#,
)]);
assert_eq!(invalid.config.git.co_author, "off");
assert!(invalid.config.indexes.trigram);
}
#[test]
fn unknown_edit_mode_warns_and_falls_back_without_dropping_valid_keys() {
let result = resolve_config(&[tier(
"project",
r#"{"edit_mode":"future","format_on_edit":true}"#,
)]);
assert!(!result.config.hashline_enabled);
assert!(result.config.format_on_edit);
assert_eq!(result.warnings.len(), 1);
assert_eq!(result.warnings[0].code, "invalid_edit_mode");
assert_eq!(result.warnings[0].key, "edit_mode");
assert_eq!(result.warnings[0].tier, "project");
assert_eq!(result.warnings[0].value, "future");
}
#[test]
fn synapse_requires_explicit_model_and_receives_user_subc_connection_file() {
let without_model = resolve_config(&[tier(
"user",
r#"{
"semantic": { "backend": "synapse" },
"subc": { "connection_file": "/tmp/subc-connection.json" }
}"#,
)]);
assert_eq!(
without_model.config.semantic.backend,
SemanticBackend::Synapse
);
assert!(without_model.config.semantic.model.is_empty());
assert_eq!(
without_model.config.semantic.subc_connection_file,
Some(PathBuf::from("/tmp/subc-connection.json"))
);
let with_model = resolve_config(&[tier(
"user",
r#"{
"semantic": { "backend": "synapse", "model": "configured-model" },
"subc": { "connection_file": "/tmp/subc-connection.json" }
}"#,
)]);
assert_eq!(with_model.config.semantic.model, "configured-model");
}
#[test]
fn semantic_query_instruction_resolves_at_user_and_project_tiers() {
let result = resolve_config(&[
tier(
"user",
r#"{"semantic":{"query_instruction":"user retrieval task"}}"#,
),
tier(
"project",
r#"{"semantic":{"query_instruction":"project retrieval task"}}"#,
),
]);
assert_eq!(
result.config.semantic.query_instruction,
"project retrieval task"
);
assert_eq!(
resolve_config(&[]).config.semantic.query_instruction,
crate::config::DEFAULT_SEMANTIC_QUERY_INSTRUCTION
);
}
#[test]
fn semantic_query_timeout_clamps_to_interactive_budget_range() {
let below_min =
resolve_config(&[tier("user", r#"{ "semantic": { "query_timeout_ms": 1 } }"#)]);
assert_eq!(
below_min.config.semantic.query_timeout_ms,
MIN_SEMANTIC_QUERY_TIMEOUT_MS
);
let above_max = resolve_config(&[tier(
"user",
r#"{ "semantic": { "query_timeout_ms": 50000 } }"#,
)]);
assert_eq!(
above_max.config.semantic.query_timeout_ms,
MAX_SEMANTIC_QUERY_TIMEOUT_MS
);
}
#[test]
fn inspect_diagnostics_timeout_clamps_to_blocking_phase_range() {
let below_min = resolve_config(&[tier(
"user",
r#"{ "inspect": { "diagnostics_timeout_ms": 1 } }"#,
)]);
assert_eq!(
below_min.config.inspect.diagnostics_timeout_ms,
MIN_INSPECT_DIAGNOSTICS_TIMEOUT_MS
);
let above_max = resolve_config(&[tier(
"user",
r#"{ "inspect": { "diagnostics_timeout_ms": 700000 } }"#,
)]);
assert_eq!(
above_max.config.inspect.diagnostics_timeout_ms,
MAX_INSPECT_DIAGNOSTICS_TIMEOUT_MS
);
}
#[test]
fn idle_root_ttl_clamps_to_five_through_thirty() {
let below = resolve_config(&[tier("user", r#"{ "idle": { "root_ttl_minutes": 1 } }"#)]);
assert_eq!(
below.config.idle.root_ttl_minutes,
MIN_IDLE_ROOT_TTL_MINUTES
);
assert!(below
.warnings
.iter()
.any(|warning| warning.code == "clamped_idle_ttl"
&& warning.key == "idle.root_ttl_minutes"));
let above = resolve_config(&[tier("user", r#"{ "idle": { "root_ttl_minutes": 60 } }"#)]);
assert_eq!(
above.config.idle.root_ttl_minutes,
MAX_IDLE_ROOT_TTL_MINUTES
);
assert!(above
.warnings
.iter()
.any(|warning| warning.code == "clamped_idle_ttl"
&& warning.key == "idle.root_ttl_minutes"));
let at_min = resolve_config(&[tier("user", r#"{ "idle": { "root_ttl_minutes": 5 } }"#)]);
assert_eq!(at_min.config.idle.root_ttl_minutes, 5);
assert!(at_min.warnings.is_empty());
let at_max = resolve_config(&[tier("user", r#"{ "idle": { "root_ttl_minutes": 30 } }"#)]);
assert_eq!(at_max.config.idle.root_ttl_minutes, 30);
assert!(at_max.warnings.is_empty());
}
#[test]
fn removed_views_enabled_refused_for_user_and_noticed_for_project() {
let doc = r#"{"views":{"enabled":true}}"#;
let user = resolve_config(&[tier("user", doc)]);
assert_eq!(
user.errors,
vec!["removed_config_key:views.enabled; run npx @cortexkit/aft doctor --fix"]
);
let project = resolve_config(&[tier("project", doc)]);
assert!(project.errors.is_empty(), "{:?}", project.errors);
assert!(project.warnings.is_empty(), "{:?}", project.warnings);
assert_eq!(
serde_json::to_value(project.config).unwrap(),
serde_json::to_value(resolve_config(&[]).config).unwrap()
);
let mut map = serde_json::from_str::<Value>(doc)
.unwrap()
.as_object()
.unwrap()
.clone();
let translation =
feature_config::translate_document(&mut map, feature_config::DocumentTier::Project);
let notice =
feature_config::project_retired_keys_notice("/project/aft.jsonc", &translation);
let expected = feature_config::REMOVED_DATA_LAYER_NOTES
.iter()
.find(|(path, _)| *path == "views.enabled")
.unwrap()
.1;
assert_eq!(notice, expected);
}
#[test]
fn removed_views_callgraph_copies_refused_for_user_and_noticed_for_project() {
let doc = r#"{"views":{"callgraph_copies":2}}"#;
let user = resolve_config(&[tier("user", doc)]);
assert_eq!(
user.errors,
vec!["removed_config_key:views.callgraph_copies; run npx @cortexkit/aft doctor --fix"]
);
let project = resolve_config(&[tier("project", doc)]);
assert!(project.errors.is_empty(), "{:?}", project.errors);
assert!(project.warnings.is_empty(), "{:?}", project.warnings);
assert_eq!(
serde_json::to_value(project.config).unwrap(),
serde_json::to_value(resolve_config(&[]).config).unwrap()
);
let mut map = serde_json::from_str::<Value>(doc)
.unwrap()
.as_object()
.unwrap()
.clone();
let translation =
feature_config::translate_document(&mut map, feature_config::DocumentTier::Project);
let notice =
feature_config::project_retired_keys_notice("/project/aft.jsonc", &translation);
let expected = feature_config::REMOVED_DATA_LAYER_NOTES
.iter()
.find(|(path, _)| *path == "views.callgraph_copies")
.unwrap()
.1;
assert_eq!(notice, expected);
}
#[test]
fn removed_worktree_ram_overlay_refused_for_user_and_noticed_for_project() {
let doc = r#"{"worktree":{"ram_overlay":false}}"#;
let user = resolve_config(&[tier("user", doc)]);
assert_eq!(
user.errors,
vec!["removed_config_key:worktree.ram_overlay; run npx @cortexkit/aft doctor --fix"]
);
let project = resolve_config(&[tier("project", doc)]);
assert!(project.errors.is_empty(), "{:?}", project.errors);
assert!(project.warnings.is_empty(), "{:?}", project.warnings);
assert_eq!(
serde_json::to_value(project.config).unwrap(),
serde_json::to_value(resolve_config(&[]).config).unwrap()
);
let mut map = serde_json::from_str::<Value>(doc)
.unwrap()
.as_object()
.unwrap()
.clone();
let translation =
feature_config::translate_document(&mut map, feature_config::DocumentTier::Project);
let notice =
feature_config::project_retired_keys_notice("/project/aft.jsonc", &translation);
let expected = feature_config::REMOVED_DATA_LAYER_NOTES
.iter()
.find(|(path, _)| *path == "worktree.ram_overlay")
.unwrap()
.1;
assert_eq!(notice, expected);
}
/// `idle.checkout_hours` replaces `views.idle_checkout_hours` with the
/// same default (168) and range (1..=8760), and merges per key beside
/// `idle.root_ttl_minutes`.
#[test]
fn idle_checkout_hours_defaults_clamps_and_merges_per_key() {
let default = resolve_config(&[tier("user", r#"{}"#)]);
assert_eq!(default.config.idle.checkout_hours, 168);
let merged = resolve_config(&[
tier(
"user",
r#"{"idle":{"checkout_hours":2,"root_ttl_minutes":20}}"#,
),
tier("project", r#"{"idle":{"root_ttl_minutes":15}}"#),
]);
assert_eq!(merged.config.idle.checkout_hours, 2);
assert_eq!(merged.config.idle.root_ttl_minutes, 15);
let project = resolve_config(&[
tier("user", r#"{"idle":{"checkout_hours":2}}"#),
tier("project", r#"{"idle":{"checkout_hours":48}}"#),
]);
assert_eq!(project.config.idle.checkout_hours, 48);
for (doc, want) in [
(r#"{"idle":{"checkout_hours":0}}"#, 1),
(r#"{"idle":{"checkout_hours":9000}}"#, 8760),
] {
let clamped = resolve_config(&[tier("user", doc)]);
assert_eq!(clamped.config.idle.checkout_hours, want, "{doc}");
assert!(
clamped
.warnings
.iter()
.any(|warning| warning.code == "clamped_idle_ttl"
&& warning.key == "idle.checkout_hours"),
"{doc}: {:?}",
clamped.warnings
);
}
let fractional = resolve_config(&[tier("user", r#"{"idle":{"checkout_hours":1.5}}"#)]);
assert_eq!(fractional.config.idle.checkout_hours, 168);
assert!(fractional
.warnings
.iter()
.any(|warning| warning.code == "invalid_idle_ttl"
&& warning.key == "idle.checkout_hours"));
}
/// A retired `views.idle_checkout_hours` is translated to
/// `idle.checkout_hours` (clamped to its range) at both tiers, and loses
/// to an explicit `idle.checkout_hours` in the same file.
#[test]
fn retired_views_idle_checkout_hours_becomes_idle_checkout_hours() {
let _release = feature_config::override_running_release_for_test((0, 64));
let user = resolve_config(&[tier("user", r#"{"views":{"idle_checkout_hours":2}}"#)]);
assert!(user.errors.is_empty(), "{:?}", user.errors);
assert_eq!(user.config.idle.checkout_hours, 2);
let project = resolve_config(&[
tier("user", r#"{"idle":{"checkout_hours":2}}"#),
tier(
"project",
r#"{"views":{"idle_checkout_hours":72,"enabled":true}}"#,
),
]);
assert_eq!(project.config.idle.checkout_hours, 72);
let clamped = resolve_config(&[tier("user", r#"{"views":{"idle_checkout_hours":0}}"#)]);
assert_eq!(clamped.config.idle.checkout_hours, 1);
let canonical = resolve_config(&[tier(
"user",
r#"{"views":{"idle_checkout_hours":2},"idle":{"checkout_hours":5}}"#,
)]);
assert_eq!(canonical.config.idle.checkout_hours, 5);
}
#[test]
fn config_0_65_idle_rename_refuses_user_but_project_loads_with_notice() {
let _release = feature_config::override_running_release_for_test((0, 65));
for (doc, key) in [
(
r#"{"views":{"idle_checkout_hours":72}}"#,
"views.idle_checkout_hours",
),
(
r#"{"harnesses":{"pi":{"views":{"idle_checkout_hours":72}}}}"#,
"harnesses.pi.views.idle_checkout_hours",
),
] {
let user = tier("user", doc);
let rejected = resolve_config_for_harness(&[user.clone()], Some(&Harness::Pi));
assert_eq!(
rejected.errors,
[format!(
"removed_config_key:{key}; run npx @cortexkit/aft doctor --fix"
)]
);
assert!(strict_tier_error(&user, Some(&Harness::Pi)).is_some());
let project = tier("project", doc);
assert!(strict_tier_error(&project, Some(&Harness::Pi)).is_none());
let loaded = resolve_config_for_harness(&[project], Some(&Harness::Pi));
assert!(loaded.errors.is_empty(), "{:?}", loaded.errors);
assert_eq!(loaded.config.idle.checkout_hours, 72);
assert!(loaded.warnings.is_empty(), "{:?}", loaded.warnings);
let mut map = serde_json::from_str::<Value>(doc)
.unwrap()
.as_object()
.unwrap()
.clone();
let translation =
feature_config::translate_document(&mut map, feature_config::DocumentTier::Project);
let notice =
feature_config::project_retired_keys_notice("/project/aft.jsonc", &translation);
assert!(
notice.contains(&format!("uses retired keys ({key})")),
"{notice}"
);
assert!(
notice.contains("views.idle_checkout_hours is now idle.checkout_hours"),
"{notice}"
);
}
}
#[test]
fn lsp_idle_clamps_to_five_through_1440() {
for (raw, expected) in [(0, 5), (5, 5), (1440, 1440), (2000, 1440)] {
let result = resolve_config(&[tier(
"user",
&format!(r#"{{"lsp":{{"idle_minutes":{raw}}}}}"#),
)]);
assert!(result.errors.is_empty());
assert_eq!(result.config.lsp_idle_minutes, expected);
}
}
#[test]
fn idle_non_integer_ttl_is_dropped_with_warning() {
let result = resolve_config(&[tier("user", r#"{ "idle": { "root_ttl_minutes": 12.5 } }"#)]);
assert_eq!(
result.config.idle.root_ttl_minutes,
DEFAULT_IDLE_ROOT_TTL_MINUTES
);
assert!(result
.warnings
.iter()
.any(|warning| warning.code == "invalid_idle_ttl"
&& warning.key == "idle.root_ttl_minutes"));
}
#[test]
fn idle_project_tier_overrides_user_root_ttl() {
let result = resolve_config(&[
tier("user", r#"{"idle":{"root_ttl_minutes":20}}"#),
tier("project", r#"{"idle":{"root_ttl_minutes":15}}"#),
]);
assert_eq!(result.config.idle.root_ttl_minutes, 15);
}
#[test]
fn project_inspect_diagnostics_timeout_can_raise_but_never_lower_user_value() {
let lower = resolve_config(&[
tier(
"user",
r#"{ "inspect": { "diagnostics_timeout_ms": 180000 } }"#,
),
tier(
"project",
r#"{ "inspect": { "diagnostics_timeout_ms": 90000 } }"#,
),
]);
assert_eq!(lower.config.inspect.diagnostics_timeout_ms, 180_000);
let higher = resolve_config(&[
tier(
"user",
r#"{ "inspect": { "diagnostics_timeout_ms": 180000 } }"#,
),
tier(
"project",
r#"{ "inspect": { "diagnostics_timeout_ms": 240000 } }"#,
),
]);
assert_eq!(higher.config.inspect.diagnostics_timeout_ms, 240_000);
}
#[test]
fn project_indexes_can_only_turn_an_index_off() {
// A project may switch an index off but never back on: its values AND
// with the user resolution.
let result = resolve_config_for_harness(
&[
tier("user", r#"{ "indexes": { "trigram": false } }"#),
tier("project", r#"{ "indexes": { "trigram": true } }"#),
],
None,
);
assert!(!result.config.indexes.trigram);
assert!(result.dropped.is_empty());
let project_off = resolve_config(&[
tier("user", r#"{}"#),
tier(
"project",
r#"{ "indexes": { "semantic": false }, "harnesses": { "opencode": { "indexes": { "callgraph": false, "semantic": true } } } }"#,
),
]);
assert!(project_off.config.indexes.trigram);
let opencode = resolve_config_for_harness(
&[
tier("user", r#"{}"#),
tier(
"project",
r#"{ "indexes": { "semantic": false }, "harnesses": { "opencode": { "indexes": { "callgraph": false, "semantic": true } } } }"#,
),
],
Some(&Harness::Opencode),
);
assert!(!opencode.config.indexes.semantic);
assert!(!opencode.config.indexes.callgraph);
assert!(!project_off.config.indexes.semantic);
assert!(project_off.config.indexes.callgraph);
// A user harness block overrides the user base in either direction.
let user_harness = resolve_config_for_harness(
&[tier(
"user",
r#"{ "indexes": { "trigram": false }, "harnesses": { "pi": { "indexes": { "trigram": true } } } }"#,
)],
Some(&Harness::Pi),
);
assert!(user_harness.config.indexes.trigram);
}
#[test]
fn sandbox_profiles_default_by_role_and_project_cannot_loosen() {
let defaults = resolve_config(&[tier("user", "{}")]);
let sandbox = serde_json::to_value(&defaults.config.sandbox).unwrap();
assert_eq!(sandbox["profile"]["worker"], "relaxed");
assert_eq!(sandbox["profile"]["head"], "off");
let result = resolve_config(&[
tier(
"user",
r#"{"sandbox":{"profile":{"worker":"strict","head":"relaxed"}}}"#,
),
tier(
"project",
r#"{"sandbox":{"profile":{"worker":"off","head":"off"}}}"#,
),
]);
let sandbox = serde_json::to_value(&result.config.sandbox).unwrap();
assert_eq!(sandbox["profile"]["worker"], "strict");
assert_eq!(sandbox["profile"]["head"], "relaxed");
assert!(drop_keys(&result).contains(&"sandbox.profile.worker".to_string()));
assert!(drop_keys(&result).contains(&"sandbox.profile.head".to_string()));
for role in ["worker", "head"] {
for (floor_rank, floor) in ["off", "relaxed", "strict"].into_iter().enumerate() {
for (next_rank, next) in ["off", "relaxed", "strict"].into_iter().enumerate() {
let user =
serde_json::json!({"sandbox":{"profile":{(role):floor}}}).to_string();
let project =
serde_json::json!({"sandbox":{"profile":{(role):next}}}).to_string();
let result = resolve_config(&[tier("user", &user), tier("project", &project)]);
let sandbox = serde_json::to_value(&result.config.sandbox).unwrap();
assert_eq!(
sandbox["profile"][role],
if next_rank >= floor_rank { next } else { floor },
"{role}: {floor} -> {next}"
);
}
}
}
}
#[test]
fn project_sandbox_can_add_read_denies_but_not_enable_or_add_writes() {
let result = resolve_config(&[
tier(
"user",
r#"{
"sandbox": {
"profile": { "worker": "strict", "head": "strict" },
"write_allow": ["/user/write"],
"read_deny": ["/user/secret"]
}
}"#,
),
tier(
"project",
r#"{
"sandbox": {
"profile": { "worker": "relaxed", "head": "off" },
"write_allow": ["/project/write"],
"read_deny": ["/project/secret", "/user/secret"]
}
}"#,
),
]);
assert!(result.config.sandbox.head_enabled());
assert_eq!(
result.config.sandbox.write_allow,
vec![PathBuf::from("/user/write")]
);
assert_eq!(
result.config.sandbox.read_deny,
vec![
PathBuf::from("/user/secret"),
PathBuf::from("/project/secret")
]
);
assert_eq!(
drop_keys(&result),
vec![
"sandbox.write_allow".to_string(),
"sandbox.profile.worker".to_string(),
"sandbox.profile.head".to_string()
]
);
}
#[test]
fn project_can_enable_sandbox_but_never_disable_it() {
// Hardening is one-way: a repo may opt itself into kernel confinement.
let opt_in = resolve_config(&[
tier("user", r#"{}"#),
tier(
"project",
r#"{ "sandbox": { "profile": { "worker": "strict", "head": "strict" } } }"#,
),
]);
assert!(opt_in.config.sandbox.head_enabled());
assert!(
!drop_keys(&opt_in).contains(&"sandbox.profile.head".to_string()),
"a stricter project profile is an accepted opt-in, not a dropped key"
);
// The weakening direction stays user-only: a looser project profile
// cannot win.
let opt_out = resolve_config(&[
tier(
"user",
r#"{ "sandbox": { "profile": { "worker": "strict", "head": "strict" } } }"#,
),
tier(
"project",
r#"{ "sandbox": { "profile": { "worker": "relaxed", "head": "off" } } }"#,
),
]);
assert!(opt_out.config.sandbox.head_enabled());
assert!(drop_keys(&opt_out).contains(&"sandbox.profile.head".to_string()));
}
#[test]
fn config_resolve_project_user_only_keys_are_dropped_and_user_values_win() {
let result = resolve_config(&[
tier(
"user",
r#"{
"restrict_to_project_root": true,
"url_fetch_allow_private": true,
"formatter_timeout_secs": 11,
"type_checker_timeout_secs": 33,
"auto_update": true,
"bridge": { "request_timeout_ms": 3000 },
"semantic": {
"backend": "openai_compatible",
"base_url": "https://user.example.test",
"api_key_env": "USER_KEY",
"model": "user-model",
"query_timeout_ms": 900,
"max_input_tokens": 512
},
"lsp": {
"servers": {
"rust": { "extensions": [".rs"], "binary": "rust-analyzer" }
},
"disabled": ["user-disabled"],
"versions": { "typescript-language-server": "1.0.0" },
"auto_install": true,
"grace_days": 7
}
}"#,
),
tier(
"project",
r#"{
"restrict_to_project_root": false,
"url_fetch_allow_private": false,
"formatter_timeout_secs": 22,
"type_checker_timeout_secs": 44,
"auto_update": false,
"bridge": { "request_timeout_ms": 4000 },
"semantic": {
"backend": "ollama",
"base_url": "https://project.example.test",
"api_key_env": "PROJECT_KEY",
"model": "project-model",
"timeout_ms": 2222,
"query_timeout_ms": 2222,
"max_input_tokens": 960
},
"lsp": {
"servers": {
"rust": { "extensions": [".evil"], "binary": "evil-lsp" }
},
"disabled": ["project-disabled"],
"versions": { "evil-lsp": "9.9.9" },
"auto_install": false,
"grace_days": 1,
"python": "ty"
}
}"#,
),
]);
assert!(result.config.restrict_to_project_root);
assert!(result.config.url_fetch_allow_private);
assert_eq!(result.config.formatter_timeout_secs, 11);
assert_eq!(result.config.type_checker_timeout_secs, 33);
assert_eq!(
result.config.semantic.backend,
SemanticBackend::OpenAiCompatible
);
assert_eq!(
result.config.semantic.base_url.as_deref(),
Some("https://user.example.test")
);
assert_eq!(
result.config.semantic.api_key_env.as_deref(),
Some("USER_KEY")
);
assert_eq!(result.config.semantic.model, "project-model");
assert_eq!(result.config.semantic.timeout_ms, 2222);
assert_eq!(result.config.semantic.query_timeout_ms, 900);
assert_eq!(result.config.semantic.max_input_tokens, Some(960));
assert_eq!(result.config.lsp_servers.len(), 1);
assert_eq!(result.config.lsp_servers[0].binary, "rust-analyzer");
assert!(result.config.disabled_lsp.contains("user-disabled"));
assert!(!result.config.disabled_lsp.contains("project-disabled"));
assert!(result.config.disabled_lsp.contains("python"));
assert!(result.config.experimental_lsp_ty);
let keys = drop_keys(&result);
let expected = [
"restrict_to_project_root",
"url_fetch_allow_private",
"formatter_timeout_secs",
"type_checker_timeout_secs",
"auto_update",
"bridge",
"semantic.backend",
"semantic.base_url",
"semantic.api_key_env",
"semantic.query_timeout_ms",
"lsp.servers",
"lsp.versions",
"lsp.auto_install",
"lsp.grace_days",
"lsp.disabled",
];
for key in expected {
assert!(keys.contains(&key.to_string()), "missing dropped key {key}");
}
assert_eq!(keys.len(), expected.len());
assert!(result
.dropped
.iter()
.all(|dropped| dropped.tier == "project"));
}
#[test]
fn disabled_tools_resolve_into_runtime_config() {
let result = resolve_config(&[tier(
"user",
r#"{ "disabled_tools": ["aft_zoom", "aft_search"] }"#,
)]);
assert!(result
.config
.disabled_tools
.iter()
.any(|tool| tool == "aft_zoom"));
assert!(result
.config
.disabled_tools
.iter()
.any(|tool| tool == "aft_search"));
}
#[test]
fn project_empty_disabled_list_preserves_explicit_presence() {
let result = resolve_config(&[
tier("user", r#"{ "disabled_tools": [] }"#),
tier("project", r#"{ "disabled_tools": [] }"#),
]);
assert!(result.config.disabled_tools.is_empty());
// The absent-base default applies to the user base only (no user file
// behaves like `{}`); an empty project list adds nothing to it.
let project_only = resolve_config(&[tier("project", r#"{ "disabled_tools": [] }"#)]);
assert_eq!(
project_only.config.disabled_tools,
["aft_delete", "aft_move"]
);
let user_empty_project_zoom = resolve_config(&[
tier("user", r#"{ "disabled_tools": [] }"#),
tier("project", r#"{ "disabled_tools": ["aft_zoom"] }"#),
]);
assert_eq!(user_empty_project_zoom.config.disabled_tools, ["aft_zoom"]);
for doc in [None, Some("{}")] {
let tiers: Vec<ConfigTier> = doc.map(|doc| tier("user", doc)).into_iter().collect();
assert_eq!(
resolve_config(&tiers).config.disabled_tools,
["aft_delete", "aft_move"]
);
}
let search_only =
resolve_config(&[tier("user", r#"{ "disabled_tools": ["aft_search"] }"#)]);
assert_eq!(search_only.config.disabled_tools, ["aft_search"]);
assert!(!search_only.config.aft_search_registered);
}
#[test]
fn project_disabled_tools_cannot_remove_host_slots() {
let result = resolve_config(&[
tier("user", r#"{ "disabled_tools": ["write"] }"#),
tier(
"project",
r#"{ "disabled_tools": ["read", "bash", "aft_safety", "aft_zoom"] }"#,
),
]);
assert_eq!(result.config.disabled_tools, ["aft_zoom", "write"]);
let dropped = drop_keys(&result);
for key in [
"disabled_tools.aft_safety",
"disabled_tools.bash",
"disabled_tools.read",
] {
assert!(dropped.contains(&key.to_string()), "{key}");
}
}
#[test]
fn remote_exec_is_user_only_and_a_project_may_only_turn_it_off() {
assert_eq!(
resolve_config(&[]).config.remote_exec,
RemoteExecConfig::default()
);
let user = r#"{ "remote_exec": { "enabled": true, "default_demand": "linux" } }"#;
let on = resolve_config(&[tier("user", user)]).config.remote_exec;
assert!(on.enabled && !on.project_off);
assert_eq!(on.default_demand.as_deref(), Some("linux"));
// A project can neither enable remote runs nor pick their runner.
let project_on = resolve_config(&[tier(
"project",
r#"{ "remote_exec": { "enabled": true, "default_demand": "linux" } }"#,
)]);
assert_eq!(project_on.config.remote_exec, RemoteExecConfig::default());
let dropped = drop_keys(&project_on);
assert!(dropped.contains(&"remote_exec.enabled".to_string()));
assert!(dropped.contains(&"remote_exec.default_demand".to_string()));
// It can turn them off, and the refusal can then name the project.
let off = resolve_config(&[
tier("user", user),
tier("project", r#"{ "remote_exec": { "enabled": false } }"#),
]);
assert!(!off.config.remote_exec.enabled);
assert!(off.config.remote_exec.project_off);
assert!(drop_keys(&off).is_empty());
}
#[test]
fn bash_linux_scope_is_user_only_and_defaults_on() {
assert!(resolve_config(&[]).config.bash.linux_scope);
let result = resolve_config(&[
tier("user", r#"{ "bash": { "linux_scope": true } }"#),
tier("project", r#"{ "bash": { "linux_scope": false } }"#),
]);
assert!(result.config.bash.linux_scope);
assert!(drop_keys(&result).contains(&"bash.linux_scope".to_string()));
}
#[test]
fn task_scope_config_contract() {
let direct = crate::config::BashConfig::default();
assert!(direct.linux_scope);
assert_eq!(direct.linux_scope_max_runtime_secs, 86_400);
let defaults = resolve_config(&[]).config.bash;
assert!(defaults.linux_scope);
assert_eq!(defaults.linux_scope_max_runtime_secs, 86_400);
let result = resolve_config(&[
tier(
"user",
r#"{"bash":{"linux_scope":false,"linux_scope_max_runtime_secs":7200}}"#,
),
tier(
"project",
r#"{"bash":{"linux_scope":true,"linux_scope_max_runtime_secs":1}}"#,
),
]);
assert!(!result.config.bash.linux_scope);
assert_eq!(result.config.bash.linux_scope_max_runtime_secs, 7200);
assert!(drop_keys(&result).contains(&"bash.linux_scope_max_runtime_secs".into()));
for value in ["0", "-1", "1.5", "4294967296", "true", "\"86400\""] {
let text = format!("{{\"linux_scope_max_runtime_secs\":{value}}}");
let error = serde_json::from_str::<RawBashFeatures>(&text).unwrap_err();
assert!(error.to_string().contains("linux_scope_max_runtime_secs"));
}
}
#[test]
fn privacy_disclaim_project_only_tightens_and_reports_weakening() {
assert!(!resolve_config(&[]).config.bash.disclaim_privacy);
for user in [false, true] {
for project in [false, true] {
let result = resolve_config(&[
tier(
"user",
&format!(r#"{{"bash":{{"disclaim_privacy":{user}}}}}"#),
),
tier(
"project",
&format!(r#"{{"bash":{{"disclaim_privacy":{project}}}}}"#),
),
]);
assert_eq!(result.config.bash.disclaim_privacy, user || project);
assert_eq!(
drop_keys(&result).contains(&"bash.disclaim_privacy".to_string()),
!project
);
}
}
}
#[test]
fn config_resolve_bash_ladder_and_merge_parity() {
let true_result = resolve_config(&[tier("user", r#"{ "bash": true }"#)]);
assert!(true_result.config.experimental_bash_rewrite);
assert!(true_result.config.experimental_bash_compress);
assert!(true_result.config.experimental_bash_background);
let false_result = resolve_config(&[tier("user", r#"{ "bash": false }"#)]);
assert!(!false_result.config.bash.enabled);
assert!(!false_result.config.experimental_bash_rewrite);
assert!(!false_result.config.experimental_bash_compress);
assert!(!false_result.config.experimental_bash_background);
let object_default_result = resolve_config(&[tier("user", r#"{ "bash": {} }"#)]);
assert!(object_default_result.config.experimental_bash_rewrite);
assert!(object_default_result.config.experimental_bash_compress);
assert!(object_default_result.config.experimental_bash_background);
let object_partial_result =
resolve_config(&[tier("user", r#"{ "bash": { "compress": false } }"#)]);
assert!(object_partial_result.config.experimental_bash_rewrite);
assert!(!object_partial_result.config.experimental_bash_compress);
assert!(object_partial_result.config.experimental_bash_background);
let surface_default_result = resolve_config(&[tier("user", r#"{}"#)]);
assert!(surface_default_result.config.experimental_bash_rewrite);
assert!(surface_default_result.config.experimental_bash_compress);
assert!(surface_default_result.config.experimental_bash_background);
assert!(!false_result.config.bash.enabled);
assert!(true_result.config.bash.enabled);
assert!(object_default_result.config.bash.enabled);
let explicit_off = resolve_config(&[tier("user", r#"{ "bash": { "enabled": false } }"#)]);
assert!(!explicit_off.config.bash.enabled);
assert!(explicit_off.config.experimental_bash_rewrite);
assert_eq!(false_result.config.bash, explicit_off.config.bash);
let merged_result = resolve_config(&[
tier("user", r#"{ "bash": true }"#),
tier("project", r#"{ "bash": { "compress": false } }"#),
]);
assert!(merged_result.config.experimental_bash_rewrite);
assert!(!merged_result.config.experimental_bash_compress);
assert!(merged_result.config.experimental_bash_background);
let false_then_object_result = resolve_config(&[
tier("user", r#"{ "bash": false }"#),
tier("project", r#"{ "bash": { "compress": true } }"#),
]);
assert!(!false_then_object_result.config.bash.enabled);
assert!(!false_then_object_result.config.experimental_bash_rewrite);
assert!(false_then_object_result.config.experimental_bash_compress);
assert!(!false_then_object_result.config.experimental_bash_background);
}
#[test]
fn settings_shapes_project_bash_true_cannot_reenable_user_gate() {
let result = resolve_config(&[
tier(
"user",
r#"{"bash":{"enabled":false,"rewrite":false,"compress":false,"background":false}}"#,
),
tier("project", r#"{"bash":true}"#),
]);
assert!(result.errors.is_empty());
assert!(!result.config.bash.enabled);
assert!(result.config.experimental_bash_rewrite);
assert!(result.config.experimental_bash_compress);
assert!(result.config.experimental_bash_background);
}
#[test]
fn config_resolve_bash_foreground_wait_clamps_to_floor() {
let Ok((raw, _)) = parse_tier(
&tier(
"user",
r#"{ "bash": { "foreground_wait_window_ms": 1, "subagent_background": true } }"#,
),
None,
&mut Vec::new(),
&mut Vec::new(),
) else {
panic!("test tier should parse");
};
let mut warnings = Vec::new();
let bash = resolve_bash_config(&raw, &mut warnings);
assert_eq!(
bash.foreground_wait_window_ms,
FOREGROUND_WAIT_WINDOW_MIN_MS
);
assert!(bash.subagent_background);
let result = resolve_config(&[tier(
"user",
r#"{ "bash": { "foreground_wait_window_ms": 1 } }"#,
)]);
assert_eq!(
result.config.foreground_wait_window_ms,
FOREGROUND_WAIT_WINDOW_MIN_MS
);
// Unset → the default wait-window (matches the plugin's
// FOREGROUND_WAIT_WINDOW_DEFAULT_MS = 15_000). This locks the default,
// not just the floor, so a future edit can't silently shorten the
// server-side promotion window once the plugin orchestrates through Rust.
let defaulted = resolve_config(&[tier("user", r#"{ "bash": true }"#)]);
assert_eq!(
defaulted.config.foreground_wait_window_ms,
FOREGROUND_WAIT_WINDOW_DEFAULT_MS
);
assert_eq!(FOREGROUND_WAIT_WINDOW_DEFAULT_MS, 15_000);
}
#[test]
fn config_resolve_partial_parse_drops_invalid_section_and_keeps_valid_sections() {
let result = resolve_config(&[tier(
"user",
r#"{
"semantic": { "timeout_ms": 0 },
"indexes": { "trigram": true },
"format_on_edit": false
}"#,
)]);
assert!(result.config.indexes.trigram);
assert!(!result.config.format_on_edit);
assert_eq!(result.config.semantic, SemanticBackendConfig::default());
assert!(result.dropped.is_empty());
}
#[test]
fn config_resolve_unrelated_unknown_user_key_keeps_lenient_defaults() {
let result = resolve_config(&[tier(
"user",
r#"{ "not_a_real_key": true, "indexes": { "trigram": true } }"#,
)]);
assert!(result.config.indexes.trigram);
assert!(result.dropped.is_empty());
assert!(result.errors.is_empty(), "{result:?}");
assert!(result.config.cache_config_unknown.is_none());
}
#[test]
fn resolve_config_onto_resets_core_fields_no_cross_bind_inheritance() {
// Cross-bind escalation regression: a first (trusted) bind sets a
// capability field; a second bind that omits it must NOT inherit it.
// This is the configure-path entry (seeded from a prior config), where
// reset-onto-default — unlike the old overlay — makes the resolved core
// config a pure function of the CURRENT bind's tiers.
let mut config = Config::default();
// Bind 1 (trusted user tier) sets url_fetch_allow_private + a custom LSP
// server + restrict_to_project_root.
let dropped1 = resolve_config_onto(
&[tier(
"user",
r#"{
"url_fetch_allow_private": true,
"restrict_to_project_root": true,
"lsp": { "servers": { "rust": { "extensions": [".rs"], "binary": "rust-analyzer" } } }
}"#,
)],
&mut config,
);
assert!(dropped1.is_empty());
assert!(config.url_fetch_allow_private);
assert!(config.restrict_to_project_root);
assert_eq!(config.lsp_servers.len(), 1);
// Bind 2 omits all three. With reset semantics they return to DEFAULT —
// the second bind cannot inherit the first bind's capabilities.
let _ = resolve_config_onto(
&[tier("user", r#"{ "indexes": { "trigram": true } }"#)],
&mut config,
);
assert!(
!config.url_fetch_allow_private,
"url_fetch_allow_private must reset to default, not inherit prior bind"
);
assert!(
!config.restrict_to_project_root,
"restrict_to_project_root must reset to default"
);
assert!(
config.lsp_servers.is_empty(),
"lsp_servers must reset to default, not inherit prior bind's custom server"
);
assert!(
config.indexes.trigram,
"this bind's own field still applies"
);
}
#[test]
fn resolve_config_onto_empty_tiers_resets_to_default() {
// The empty-tier path must still reset (it routes through the same
// always-run resolution in handle_configure). A bind with no tiers after
// a privileged bind must drop the privileged config.
let mut config = Config::default();
let _ = resolve_config_onto(
&[tier("user", r#"{ "url_fetch_allow_private": true }"#)],
&mut config,
);
assert!(config.url_fetch_allow_private);
let _ = resolve_config_onto(&[], &mut config);
assert!(
!config.url_fetch_allow_private,
"empty-tier bind must reset core config to default"
);
}
#[test]
fn resolve_config_onto_preserves_process_state_fields() {
// Process-state fields (not part of RawAftConfig) are carried across the
// reset so plugin-mode behavior is unchanged (the plugin re-sends them
// via flat configure params right after this call).
let mut config = Config {
storage_dir: Some(std::path::PathBuf::from("/tmp/aft-store")),
lsp_paths_extra: vec![std::path::PathBuf::from("/tmp/lsp-bin")],
bash_permissions: true,
project_root: Some(std::path::PathBuf::from("/tmp/proj")),
..Default::default()
};
let _ = resolve_config_onto(
&[tier("user", r#"{ "indexes": { "trigram": true } }"#)],
&mut config,
);
assert_eq!(
config.storage_dir,
Some(std::path::PathBuf::from("/tmp/aft-store"))
);
assert_eq!(
config.lsp_paths_extra,
vec![std::path::PathBuf::from("/tmp/lsp-bin")]
);
assert!(config.bash_permissions);
assert_eq!(
config.project_root,
Some(std::path::PathBuf::from("/tmp/proj"))
);
assert!(config.indexes.trigram);
}
#[test]
fn index_roots_are_user_only_normalized_and_validate_before_resolution() {
let result = resolve_config(&[tier(
"user",
r#"{
"index": {
"roots": [{
"path": "~/.aft-standing-root",
"indexes": ["semantic", "callgraph"],
"future_field": true
}]
}
}"#,
)]);
assert_eq!(result.config.index.roots.len(), 1);
assert_eq!(result.config.index.roots[0].path, "~/.aft-standing-root");
assert_eq!(
result.config.index.roots[0].indexes,
vec![IndexKind::Search, IndexKind::Semantic, IndexKind::Callgraph]
);
assert!(result
.warnings
.iter()
.any(|warning| warning.code == "index_dependency_closure"));
assert!(result
.warnings
.iter()
.any(|warning| warning.code == "unknown_index_root_field"));
for invalid in [
r#"{ "index": { "roots": [{ "path": "relative", "indexes": ["search"] }] } }"#,
r#"{ "index": { "roots": [{ "path": "~/a", "indexes": [] }] } }"#,
r#"{ "index": { "roots": [{ "path": "~/a", "indexes": ["search", "search"] }] } }"#,
r#"{ "index": { "roots": [{ "path": "~/a", "indexes": ["unknown"] }] } }"#,
] {
let invalid = resolve_config(&[tier("user", invalid)]);
assert!(invalid.config.index.roots.is_empty());
let warning = invalid
.warnings
.iter()
.find(|warning| warning.code == "invalid_index_roots")
.expect("invalid standing roots must be named");
assert!(warning.message.contains("index.roots"));
}
}
#[test]
fn index_roots_project_and_mcp_tiers_are_rejected_at_the_trust_boundary() {
let result = resolve_config(&[
tier(
"user",
r#"{ "index": { "roots": [{ "path": "~/user", "indexes": ["search"] }] } }"#,
),
tier(
"project",
r#"{ "index": { "roots": [{ "path": "~/project", "indexes": ["semantic"] }] } }"#,
),
tier(
"mcp:untrusted",
r#"{ "index": { "roots": [{ "path": "~/mcp", "indexes": ["callgraph"] }] } }"#,
),
]);
assert_eq!(result.config.index.roots[0].path, "~/user");
assert_eq!(
result
.dropped
.iter()
.filter(|dropped| dropped.key == "index.roots")
.map(|dropped| dropped.tier.as_str())
.collect::<Vec<_>>(),
vec!["project", "mcp:untrusted"]
);
}
#[test]
fn config_resolve_jsonc_comments_and_trailing_commas_parse() {
let result = resolve_config(&[tier(
"user",
r#"{
// line comment
"indexes": { "trigram": true },
"formatter": {
"rust": "rustfmt", /* block comment */
},
}"#,
)]);
assert!(result.config.indexes.trigram);
assert_eq!(
result.config.formatter.get("rust").map(String::as_str),
Some("rustfmt")
);
}
fn external_access_ask(user: Option<bool>, project: Option<bool>) -> Option<bool> {
let block = |value: Option<bool>| {
value.map(|ask| RawPi {
external_access_ask: Some(ask),
..RawPi::default()
})
};
merge_pi_config(block(user), block(project)).and_then(|pi| pi.external_access_ask)
}
/// A repository must not silence the outside-access prompt for the user:
/// a project may turn it on, never off.
#[test]
fn project_tier_may_only_turn_the_outside_access_prompt_on() {
assert_eq!(external_access_ask(Some(true), Some(false)), Some(true));
assert_eq!(external_access_ask(None, Some(false)), None);
assert_eq!(external_access_ask(Some(false), Some(true)), Some(true));
assert_eq!(external_access_ask(Some(false), None), Some(false));
let result = resolve_config(&[
tier("user", r#"{ "pi": { "external_access_ask": true } }"#),
tier("project", r#"{ "pi": { "external_access_ask": false } }"#),
]);
assert!(result.errors.is_empty(), "{:?}", result.errors);
assert_eq!(drop_keys(&result), vec!["pi.external_access_ask"]);
let result = resolve_config(&[
tier("user", r#"{ "pi": { "external_access_ask": false } }"#),
tier("project", r#"{ "pi": { "external_access_ask": true } }"#),
]);
assert!(drop_keys(&result).is_empty(), "{:?}", result.dropped);
}
}