Skip to main content

aft_base/
feature_config.rs

1//! Feature-based configuration policy shared by the resolver, the configure
2//! handler and (later) the setup/doctor CLI.
3//!
4//! Configuration used to pick a tool surface level (`tool_surface`), a hoisting
5//! mode (`hoist_builtin_tools`) and a set of index booleans. It now has one
6//! registration rule — a tool is registered unless its canonical name is in
7//! `disabled_tools` — plus three first-class index switches under `indexes`.
8//! This module owns the literal tool inventory, the table of retired keys, the
9//! per-block translation of those keys into canonical ones, validation of a
10//! resolved configuration object and the migration-notice projection digest.
11//!
12//! Retired names in [`REFUSED_RETIRED_PATHS`] and the prefixed tool names in
13//! [`LEGACY_TOOL_ALIASES`] are refused in user config with `removed_config_key`.
14//! The translation below still covers those names,
15//! because `aft doctor --fix` and the automatic rewrite of the user file
16//! ([`crate::config_fix::auto_migrate_user_config`]) build their rewrite from
17//! it; project config translates them with a notice. Names retired more
18//! recently are translated in memory into their current equivalents on every
19//! load, and the current keys then pass through the normal user/project trust
20//! rules. The remaining data-layer rename ([`DATA_LAYER_RETIRED_PATHS`]) gets a notice until
21//! [`DATA_LAYER_KEYS_REFUSED_FROM`] and are refused from that release on. A
22//! project file is never written, only reported with a notice. The TypeScript plugins carry a mirror of
23//! the same rules in `packages/aft-bridge/src/feature-config.ts`; the config
24//! parity fixtures and the shared notice-projection fixtures keep them equal.
25
26use std::collections::BTreeSet;
27
28use serde_json::{Map, Value};
29
30pub(crate) mod settings_shape;
31use sha2::{Digest, Sha256};
32
33/// Every agent-visible tool name a registration adapter may publish, in
34/// sorted order. Known-name checks use this complete inventory, never the
35/// currently enabled subset.
36pub const CANONICAL_TOOLS: [&str; 23] = [
37    "aft_callgraph",
38    "aft_conflicts",
39    "aft_delete",
40    "aft_import",
41    "aft_inspect",
42    "aft_move",
43    "aft_outline",
44    "aft_safety",
45    "aft_search",
46    "aft_zoom",
47    "apply_patch",
48    "ast_grep_replace",
49    "ast_grep_search",
50    "bash",
51    "bash_kill",
52    "bash_status",
53    "bash_watch",
54    "bash_write",
55    "edit",
56    "glob",
57    "grep",
58    "read",
59    "write",
60];
61
62/// The seven host tool slots AFT takes over.
63pub const HOST_TOOL_NAMES: [&str; 7] = [
64    "apply_patch",
65    "bash",
66    "edit",
67    "glob",
68    "grep",
69    "read",
70    "write",
71];
72
73/// Disables applied when the user's base configuration makes no registration
74/// choice at all: move and delete stay opt-in.
75pub const DEFAULT_DISABLED_TOOLS: [&str; 2] = ["aft_delete", "aft_move"];
76
77/// Historical prefixed tool names that disabled lists may still contain,
78/// mapped to the canonical host name they now mean.
79pub const LEGACY_TOOL_ALIASES: [(&str, &str); 7] = [
80    ("aft_read", "read"),
81    ("aft_write", "write"),
82    ("aft_edit", "edit"),
83    ("aft_apply_patch", "apply_patch"),
84    ("aft_grep", "grep"),
85    ("aft_glob", "glob"),
86    ("aft_bash", "bash"),
87];
88
89/// Names removed by the historical `bash` registration gate (bash turned
90/// off), expressed with canonical names.
91pub const BASH_GATE_DISABLES: [&str; 5] = [
92    "bash",
93    "bash_kill",
94    "bash_status",
95    "bash_watch",
96    "bash_write",
97];
98
99/// Identity of the migration policy that retires the keys below.
100pub const MIGRATION_POLICY_ID: &str = "feature-config-v1";
101/// First minor release that translates the retired keys.
102pub const POLICY_INTRODUCED_MINOR: (u64, u64) = (0, 58);
103
104pub const REMOVED_OPENCODE_PATHS: [(&str, &str); 2] = [
105    ("opencode.server_url", "permission.assert"),
106    ("opencode.server_password_env", "permission.assert"),
107];
108
109/// Keys the per-repository data store leaves with nothing to do. User config
110/// refuses them; project config drops them with their existing no-effect notice.
111/// Mirrors the TypeScript `REMOVED_DATA_LAYER_PATHS`.
112pub const REMOVED_DATA_LAYER_PATHS: [&str; 3] = [
113    "views.callgraph_copies",
114    "views.enabled",
115    "worktree.ram_overlay",
116];
117
118/// `views.idle_checkout_hours` and the key that replaces it. It is translated
119/// like any retired key (and the user file rewritten) until
120/// [`DATA_LAYER_KEYS_REFUSED_FROM`], then refused.
121pub const RETIRED_IDLE_CHECKOUT_HOURS: (&str, &str) =
122    ("views.idle_checkout_hours", "idle.checkout_hours");
123
124/// First release, as (major, minor), that refuses the keys in
125/// [`DATA_LAYER_RETIRED_PATHS`] with `removed_config_key`. Earlier releases
126/// translate or keep them, with a notice. Mirrors the TypeScript
127/// `DATA_LAYER_KEYS_REFUSED_FROM`.
128pub const DATA_LAYER_KEYS_REFUSED_FROM: (u64, u64) = (0, 65);
129
130pub const CALLGRAPH_CHUNK_KEY: &str = "callgraph_chunk_size";
131pub const CALLGRAPH_CHUNK_REFUSED_FROM: (u64, u64) = (0, 67);
132pub const CALLGRAPH_CHUNK_NOTE: &str = "callgraph_chunk_size never had an effect, so the setting can be removed. From 0.67.0 AFT refuses a user config file that still sets it; run npx @cortexkit/aft doctor --fix.";
133
134/// The remaining version-gated data-layer rename. The removed no-effect keys
135/// already follow [`REFUSED_RETIRED_PATHS`]' user-only refusal policy.
136pub const DATA_LAYER_RETIRED_PATHS: [&str; 1] = ["views.idle_checkout_hours"];
137
138/// The (major, minor) release a version string names, ignoring the patch and
139/// any pre-release or build suffix.
140fn parse_release(version: &str) -> Option<(u64, u64)> {
141    let mut parts = version.split('.');
142    let major = parts.next()?.parse().ok()?;
143    let minor = parts.next()?.parse().ok()?;
144    Some((major, minor))
145}
146
147/// The (major, minor) release of this build, from the crate version.
148pub fn running_release() -> (u64, u64) {
149    #[cfg(any(test, feature = "test-support"))]
150    if let Some(release) = RUNNING_RELEASE_OVERRIDE_FOR_TEST.with(|value| value.get()) {
151        return release;
152    }
153    parse_release(env!("CARGO_PKG_VERSION")).unwrap_or((0, 0))
154}
155
156#[cfg(any(test, feature = "test-support"))]
157thread_local! {
158    static RUNNING_RELEASE_OVERRIDE_FOR_TEST: std::cell::Cell<Option<(u64, u64)>> = const {
159        std::cell::Cell::new(None)
160    };
161}
162
163/// Pin release-sensitive tests on this thread; dropping the guard restores the prior release.
164#[cfg(any(test, feature = "test-support"))]
165#[cfg_attr(not(test), allow(dead_code))]
166pub(crate) fn override_running_release_for_test(release: (u64, u64)) -> impl Drop {
167    struct Reset {
168        previous: Option<(u64, u64)>,
169        _not_send: std::marker::PhantomData<std::rc::Rc<()>>,
170    }
171    impl Drop for Reset {
172        fn drop(&mut self) {
173            RUNNING_RELEASE_OVERRIDE_FOR_TEST.with(|value| value.set(self.previous));
174        }
175    }
176    Reset {
177        previous: RUNNING_RELEASE_OVERRIDE_FOR_TEST.with(|value| value.replace(Some(release))),
178        _not_send: std::marker::PhantomData,
179    }
180}
181
182/// `0.65.0` for [`DATA_LAYER_KEYS_REFUSED_FROM`], as notices print it.
183fn refused_from_version() -> String {
184    let (major, minor) = DATA_LAYER_KEYS_REFUSED_FROM;
185    format!("{major}.{minor}.0")
186}
187
188/// Removed settings fail only in the base and first-level harness blocks.
189pub fn removed_config_key_errors(map: &Map<String, Value>) -> Vec<String> {
190    removed_config_key_errors_at(map, running_release())
191}
192
193/// [`removed_config_key_errors`] for one config file. Retired names in
194/// [`REFUSED_RETIRED_PATHS`] and the prefixed tool names refuse
195/// only the user file, which AFT rewrites itself. A project file belongs to
196/// its repository, where a refusal would leave everyone who opens it without
197/// AFT until a tracked file is edited, so those names are translated with a
198/// notice there. Settings removed outright still refuse either file. Mirrors
199/// the plugins' `removedConfigKeyErrors(..., refuseRetired)`.
200pub fn removed_config_key_errors_for_file(
201    map: &Map<String, Value>,
202    user_file: bool,
203) -> Vec<String> {
204    removed_errors(map, running_release(), user_file)
205}
206
207/// [`removed_config_key_errors`] as the release `release` judges it: the
208/// data-layer keys fail only from [`DATA_LAYER_KEYS_REFUSED_FROM`].
209pub fn removed_config_key_errors_at(map: &Map<String, Value>, release: (u64, u64)) -> Vec<String> {
210    removed_errors(map, release, true)
211}
212
213fn removed_errors(
214    map: &Map<String, Value>,
215    release: (u64, u64),
216    refuse_retired: bool,
217) -> Vec<String> {
218    let mut errors = removed_block_key_errors(map, release, refuse_retired);
219    if let Some(harnesses) = map.get("harnesses").and_then(Value::as_object) {
220        for (name, block) in harnesses {
221            if let Some(block) = block.as_object() {
222                for error in removed_block_key_errors(block, release, refuse_retired) {
223                    errors.push(error.replacen(
224                        "removed_config_key:",
225                        &format!("removed_config_key:harnesses.{name}."),
226                        1,
227                    ));
228                }
229            }
230        }
231    }
232    errors
233}
234
235fn removed_block_key_errors(
236    map: &Map<String, Value>,
237    release: (u64, u64),
238    refuse_retired: bool,
239) -> Vec<String> {
240    let mut errors = removed_opencode_key_errors(map);
241    if refuse_retired {
242        errors.extend(
243            refused_retired_names(map).into_iter().map(|name| {
244                format!("removed_config_key:{name}; run npx @cortexkit/aft doctor --fix")
245            }),
246        );
247    }
248    if refuse_retired && release >= DATA_LAYER_KEYS_REFUSED_FROM {
249        for path in DATA_LAYER_RETIRED_PATHS {
250            if has_path(map, path) {
251                errors.push(format!(
252                    "removed_config_key:{path}; run npx @cortexkit/aft doctor --fix"
253                ));
254            }
255        }
256    }
257    if refuse_retired
258        && release >= CALLGRAPH_CHUNK_REFUSED_FROM
259        && map.contains_key(CALLGRAPH_CHUNK_KEY)
260    {
261        errors.push(format!(
262            "removed_config_key:{CALLGRAPH_CHUNK_KEY}; run npx @cortexkit/aft doctor --fix"
263        ));
264    }
265    errors
266}
267
268fn removed_opencode_key_errors(map: &Map<String, Value>) -> Vec<String> {
269    let Some(opencode) = map.get("opencode").and_then(Value::as_object) else {
270        return Vec::new();
271    };
272    let mut errors = Vec::new();
273    for (path, _) in REMOVED_OPENCODE_PATHS {
274        if opencode.contains_key(path.strip_prefix("opencode.").unwrap()) {
275            errors.push(format!(
276                "removed_config_key:{path}; run npx @cortexkit/aft doctor --fix"
277            ));
278        }
279    }
280    errors
281}
282
283/// Retired names refused in user config, in the order a
284/// refusal lists them. A config that still sets one is refused with
285/// `removed_config_key`; `doctor --fix` (or the automatic rewrite of the user
286/// file) replaces it with its current equivalent or deletes it. Names retired
287/// more recently (`bridge.hang_threshold`) are not
288/// listed: they are still translated, with a notice. Mirrors the TypeScript
289/// `REFUSED_RETIRED_PATHS`.
290pub const REFUSED_RETIRED_PATHS: [&str; 23] = [
291    "sandbox.enabled",
292    "tool_surface",
293    "hoist_builtin_tools",
294    "enabled",
295    "search_index",
296    "experimental_search_index",
297    "semantic_search",
298    "experimental_semantic_search",
299    "callgraph_store",
300    "github.enabled",
301    "gh_read",
302    "gh_shim.enabled",
303    "experimental_lsp_ty",
304    "experimental_bash_rewrite",
305    "experimental_bash_compress",
306    "experimental_bash_background",
307    "experimental.bash",
308    "idle.lsp_ttl_minutes",
309    "inspect.tier2_soft_deadline_ms",
310    "inspect.max_drill_down_items",
311    "views.callgraph_copies",
312    "views.enabled",
313    "worktree.ram_overlay",
314];
315
316/// The refused retired names one block sets: the paths in
317/// [`REFUSED_RETIRED_PATHS`], then each prefixed tool name
318/// ([`LEGACY_TOOL_ALIASES`]) its `disabled_tools` list contains, once each and
319/// by its bare name, as the retired-key notices list it.
320fn refused_retired_names(map: &Map<String, Value>) -> Vec<String> {
321    let mut names: Vec<String> = REFUSED_RETIRED_PATHS
322        .iter()
323        .filter(|path| has_path(map, path))
324        .map(|path| (*path).to_string())
325        .collect();
326    if let Some(Value::Array(entries)) = map.get("disabled_tools") {
327        for name in entries.iter().filter_map(Value::as_str) {
328            if legacy_tool_alias(name).is_some() && !names.iter().any(|known| known == name) {
329                names.push(name.to_string());
330            }
331        }
332    }
333    names
334}
335
336/// Retired top-level (or nested) config paths and their replacement.
337pub const RETIRED_PATHS: [(&str, &str); 15] = [
338    ("sandbox.enabled", "sandbox.profile"),
339    ("tool_surface", "disabled_tools"),
340    ("hoist_builtin_tools", "disabled_tools"),
341    ("enabled", "disabled_tools"),
342    ("search_index", "indexes.trigram"),
343    ("experimental_search_index", "indexes.trigram"),
344    ("semantic_search", "indexes.semantic"),
345    ("experimental_semantic_search", "indexes.semantic"),
346    ("callgraph_store", "indexes.callgraph"),
347    ("github.enabled", "github.read,github.write,github.shim"),
348    ("experimental_lsp_ty", "experimental.lsp_ty"),
349    ("experimental_bash_rewrite", "bash.rewrite"),
350    ("experimental_bash_compress", "bash.compress"),
351    ("experimental_bash_background", "bash.background"),
352    ("experimental.bash", "bash"),
353];
354
355/// Retired inspect/LSP paths and their replacement. `idle.lsp_ttl_minutes`
356/// moves to `lsp.idle_minutes`; the two inspect keys never had an effect and
357/// are dropped.
358pub const REMOVED_INSPECT_LSP_PATHS: [(&str, &str); 3] = [
359    ("idle.lsp_ttl_minutes", "lsp.idle_minutes"),
360    (
361        "inspect.tier2_soft_deadline_ms",
362        "inspect.tier2_pass_timeout_ms",
363    ),
364    ("inspect.max_drill_down_items", "aft_inspect.topK"),
365];
366
367/// Retired paths that no longer do anything and have no replacement. They are
368/// dropped on load and removed by `doctor --fix`, and the notice says so.
369/// `bridge.hang_threshold` counted request timeouts toward restarting the
370/// bridge; a timeout now fails only its own request, and the bridge's hang
371/// watchdog judges a stuck child by its silence instead.
372/// `inspect.tier2_idle_minutes` delayed the whole-repository analyses the
373/// OpenCode plugin started when a session went idle; those analyses now run
374/// only when `aft_inspect` is called.
375pub const REMOVED_NO_EFFECT_PATHS: [(&str, &str); 2] = [
376    ("bridge.hang_threshold", ""),
377    ("inspect.tier2_idle_minutes", ""),
378];
379
380/// Notice sentence for a retired `bridge.hang_threshold`. Mirrors the
381/// TypeScript `RETIRED_HANG_THRESHOLD_NOTE`.
382pub const RETIRED_HANG_THRESHOLD_NOTE: &str = "bridge.hang_threshold no longer does anything: a timed-out request no longer restarts AFT, so the setting can be removed.";
383
384/// Index leaf, its immediate legacy key and (when one exists) the older
385/// experimental alias, in precedence order after the canonical leaf.
386pub const INDEX_INPUTS: [(&str, &str, Option<&str>); 3] = [
387    ("trigram", "search_index", Some("experimental_search_index")),
388    (
389        "semantic",
390        "semantic_search",
391        Some("experimental_semantic_search"),
392    ),
393    ("callgraph", "callgraph_store", None),
394];
395
396/// Whether a raw tool name is a protected slot a project config may not disable.
397pub fn is_project_protected_tool(name: &str) -> bool {
398    name == "aft_safety" || HOST_TOOL_NAMES.contains(&name)
399}
400
401/// Whether a name belongs to the complete canonical tool inventory.
402pub fn is_known_tool(name: &str) -> bool {
403    CANONICAL_TOOLS.contains(&name)
404}
405
406/// Canonical name for a historical prefixed alias, if `name` is one.
407pub fn legacy_tool_alias(name: &str) -> Option<&'static str> {
408    LEGACY_TOOL_ALIASES
409        .iter()
410        .find(|(alias, _)| *alias == name)
411        .map(|(_, canonical)| *canonical)
412}
413
414/// Literal disabled set a legacy `tool_surface` value translates to. The sets
415/// are the canonical inventory minus what that surface registered on OpenCode
416/// with hoisting and every gate on.
417pub fn surface_disables(surface: &str) -> Option<Vec<&'static str>> {
418    match surface {
419        "all" => Some(Vec::new()),
420        "recommended" => Some(vec!["aft_callgraph", "aft_delete", "aft_move"]),
421        "minimal" => Some(
422            CANONICAL_TOOLS
423                .iter()
424                .copied()
425                .filter(|name| !matches!(*name, "aft_outline" | "aft_zoom" | "aft_safety"))
426                .collect(),
427        ),
428        _ => None,
429    }
430}
431
432/// A non-fatal translation notice.
433#[derive(Debug, Clone, PartialEq, Eq)]
434pub struct TranslationWarning {
435    pub code: &'static str,
436    pub key: String,
437    pub message: String,
438}
439
440/// Result of translating one raw configuration document.
441#[derive(Debug, Clone, Default, PartialEq, Eq)]
442pub struct DocumentTranslation {
443    pub warnings: Vec<TranslationWarning>,
444    /// True when any retired key or alias was supplied (a migration notice applies).
445    pub legacy_input: bool,
446    /// Every retired key the document supplied, sorted and de-duplicated. A
447    /// key inside a harness block carries its `harnesses.<id>.` prefix; a
448    /// prefixed tool name inside `disabled_tools` is listed by that name.
449    pub retired_keys: Vec<String>,
450}
451
452/// Record one supplied retired key of the block whose key prefix is `prefix`.
453fn record_retired(out: &mut DocumentTranslation, prefix: &str, key: &str) {
454    out.legacy_input = true;
455    out.retired_keys.push(format!("{prefix}{key}"));
456}
457
458fn superseded(out: &mut DocumentTranslation, key: String, message: String) {
459    out.warnings.push(TranslationWarning {
460        code: "superseded_legacy_config",
461        key,
462        message,
463    });
464}
465
466fn nested_bool(map: &Map<String, Value>, container: &str, leaf: &str) -> Option<bool> {
467    map.get(container)?.as_object()?.get(leaf)?.as_bool()
468}
469
470fn has_path(map: &Map<String, Value>, path: &str) -> bool {
471    match path.split_once('.') {
472        Some((container, leaf)) => map
473            .get(container)
474            .and_then(Value::as_object)
475            .is_some_and(|inner| inner.contains_key(leaf)),
476        None => map.contains_key(path),
477    }
478}
479
480/// Whether a false retained runtime gate (backup/inspect/bash) is supplied.
481fn false_runtime_gates(map: &Map<String, Value>) -> Vec<&'static str> {
482    let mut gates = Vec::new();
483    if nested_bool(map, "backup", "enabled") == Some(false) {
484        gates.push("backup.enabled");
485    }
486    if nested_bool(map, "inspect", "enabled") == Some(false) {
487        gates.push("inspect.enabled");
488    }
489    match map.get("bash") {
490        Some(Value::Bool(false)) => gates.push("bash"),
491        Some(Value::Object(bash)) if bash.get("enabled") == Some(&Value::Bool(false)) => {
492            gates.push("bash.enabled");
493        }
494        _ => {}
495    }
496    gates
497}
498
499/// Translate the GitHub enable aliases (`gh_read.enabled`, `gh_shim.enabled`)
500/// of one block into `github.read` / `github.shim`, exactly as `doctor --fix`
501/// rewrites them. Precedence: the canonical leaf, then the `false` that a
502/// `github.enabled: false` in the same block sets for every leaf, then the
503/// alias. The aliases are removed; `gh_shim.binary_path` is kept.
504fn translate_github_aliases(
505    map: &mut Map<String, Value>,
506    prefix: &str,
507    out: &mut DocumentTranslation,
508) {
509    let master_off = nested_bool(map, "github", "enabled") == Some(false);
510    for (alias, leaf, retired_key) in [
511        ("gh_read", "read", "gh_read"),
512        ("gh_shim", "shim", "gh_shim.enabled"),
513    ] {
514        let supplied = if alias == "gh_read" {
515            map.contains_key(alias)
516        } else {
517            map.get(alias)
518                .and_then(Value::as_object)
519                .is_some_and(|shim| shim.contains_key("enabled"))
520        };
521        if !supplied {
522            continue;
523        }
524        record_retired(out, prefix, retired_key);
525        let alias_value = map
526            .get(alias)
527            .and_then(|value| value.get("enabled"))
528            .and_then(Value::as_bool);
529        if let Some(value) = alias_value {
530            match nested_bool(map, "github", leaf) {
531                Some(canonical) => {
532                    if canonical != value {
533                        superseded(
534                            out,
535                            format!("{prefix}{retired_key}"),
536                            format!("{alias}.enabled={value} is ignored because github.{leaf}={canonical} is set"),
537                        );
538                    }
539                }
540                None if master_off => {
541                    if value {
542                        superseded(
543                            out,
544                            format!("{prefix}{retired_key}"),
545                            format!("{alias}.enabled=true is ignored because github.enabled=false switches github.{leaf} off"),
546                        );
547                    }
548                }
549                None => {
550                    let github = map
551                        .entry("github".to_string())
552                        .or_insert_with(|| Value::Object(Map::new()));
553                    if let Value::Object(github) = github {
554                        github.insert(leaf.to_string(), Value::Bool(value));
555                    }
556                }
557            }
558        }
559        if alias == "gh_read" {
560            map.remove(alias);
561        } else if let Some(Value::Object(shim)) = map.get_mut(alias) {
562            shim.remove("enabled");
563            if shim.is_empty() {
564                map.remove(alias);
565            }
566        }
567    }
568}
569
570/// Remove `container.leaf` when present, dropping the container if that left
571/// it empty. Returns the removed value.
572fn take_nested(map: &mut Map<String, Value>, container: &str, leaf: &str) -> Option<Value> {
573    let inner = map.get_mut(container)?.as_object_mut()?;
574    let value = inner.remove(leaf)?;
575    if inner.is_empty() {
576        map.remove(container);
577    }
578    Some(value)
579}
580
581/// Largest integer a JSON number keeps exactly in JavaScript
582/// (`Number.MAX_SAFE_INTEGER`).
583const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
584
585/// The whole number a JSON value spells, the way JavaScript's
586/// `Number.isSafeInteger` reads the parsed value: `12` and `12.0` are both 12,
587/// while `12.5`, non-numbers and integers beyond the exactly representable
588/// range are not whole numbers. Keeps the Rust and TypeScript translations
589/// equal, since JavaScript cannot tell `12.0` from `12`.
590fn safe_whole_number(value: &Value) -> Option<i64> {
591    if let Some(number) = value.as_i64() {
592        return (number.unsigned_abs() <= MAX_SAFE_INTEGER as u64).then_some(number);
593    }
594    let number = value.as_f64()?;
595    (number.is_finite() && number.fract() == 0.0 && number.abs() <= MAX_SAFE_INTEGER as f64)
596        .then_some(number as i64)
597}
598
599/// The `lsp.idle_minutes` value a retired `idle.lsp_ttl_minutes` value
600/// becomes: a whole number clamped to the current range, or the default for
601/// anything else. Shared by load-time translation and `doctor --fix`; mirrors
602/// the TypeScript translation.
603pub fn retired_lsp_idle_minutes(value: &Value) -> i64 {
604    safe_whole_number(value)
605        .unwrap_or(i64::from(crate::config::DEFAULT_LSP_IDLE_MINUTES))
606        .clamp(
607            i64::from(crate::config::MIN_LSP_IDLE_MINUTES),
608            i64::from(crate::config::MAX_LSP_IDLE_MINUTES),
609        )
610}
611
612/// Translate the retired inspect/LSP keys of one block, exactly as
613/// `doctor --fix` rewrites them: `idle.lsp_ttl_minutes` becomes
614/// `lsp.idle_minutes` (clamped to its range) unless that is already set, and
615/// the two inspect keys that never had an effect are dropped.
616fn translate_inspect_lsp_paths(
617    map: &mut Map<String, Value>,
618    prefix: &str,
619    out: &mut DocumentTranslation,
620) {
621    if let Some(value) = take_nested(map, "idle", "lsp_ttl_minutes") {
622        record_retired(out, prefix, "idle.lsp_ttl_minutes");
623        if map
624            .get("lsp")
625            .and_then(|lsp| lsp.get("idle_minutes"))
626            .is_some()
627        {
628            superseded(
629                out,
630                format!("{prefix}idle.lsp_ttl_minutes"),
631                "idle.lsp_ttl_minutes is ignored because lsp.idle_minutes is set".to_string(),
632            );
633        } else {
634            let minutes = retired_lsp_idle_minutes(&value);
635            let lsp = map
636                .entry("lsp".to_string())
637                .or_insert_with(|| Value::Object(Map::new()));
638            if let Value::Object(lsp) = lsp {
639                lsp.insert("idle_minutes".to_string(), Value::from(minutes));
640            }
641        }
642    }
643    for leaf in ["tier2_soft_deadline_ms", "max_drill_down_items"] {
644        if take_nested(map, "inspect", leaf).is_some() {
645            record_retired(out, prefix, &format!("inspect.{leaf}"));
646        }
647    }
648}
649
650/// Drop the retired keys that no longer do anything
651/// ([`REMOVED_NO_EFFECT_PATHS`]), exactly as `doctor --fix` removes them.
652fn drop_no_effect_paths(map: &mut Map<String, Value>, prefix: &str, out: &mut DocumentTranslation) {
653    for (path, _) in REMOVED_NO_EFFECT_PATHS {
654        if let Some((container, leaf)) = path.split_once('.') {
655            if take_nested(map, container, leaf).is_some() {
656                record_retired(out, prefix, path);
657            }
658        }
659    }
660}
661
662/// The `idle.checkout_hours` value a retired `views.idle_checkout_hours`
663/// value becomes: a whole number clamped to the current range, or the default
664/// for anything else. Shared by load-time translation and `doctor --fix`;
665/// mirrors the TypeScript translation.
666pub fn retired_idle_checkout_hours(value: &Value) -> i64 {
667    safe_whole_number(value)
668        .unwrap_or(i64::from(crate::config::DEFAULT_IDLE_CHECKOUT_HOURS))
669        .clamp(
670            i64::from(crate::config::MIN_IDLE_CHECKOUT_HOURS),
671            i64::from(crate::config::MAX_IDLE_CHECKOUT_HOURS),
672        )
673}
674
675/// Translate the keys the data-layer cutover retires in one block:
676/// `views.idle_checkout_hours` becomes `idle.checkout_hours` (clamped to its
677/// range) unless that is already set, exactly as `doctor --fix` rewrites it.
678/// Removed no-effect keys are dropped before strict schema validation.
679fn translate_data_layer_paths(
680    map: &mut Map<String, Value>,
681    prefix: &str,
682    out: &mut DocumentTranslation,
683) {
684    if map.remove(CALLGRAPH_CHUNK_KEY).is_some() {
685        record_retired(out, prefix, CALLGRAPH_CHUNK_KEY);
686    }
687    let (retired, replacement) = RETIRED_IDLE_CHECKOUT_HOURS;
688    if let Some(value) = take_nested(map, "views", "idle_checkout_hours") {
689        record_retired(out, prefix, retired);
690        if map
691            .get("idle")
692            .and_then(|idle| idle.get("checkout_hours"))
693            .is_some()
694        {
695            superseded(
696                out,
697                format!("{prefix}{retired}"),
698                format!("{retired} is ignored because {replacement} is set"),
699            );
700        } else {
701            let hours = retired_idle_checkout_hours(&value);
702            let idle = map
703                .entry("idle".to_string())
704                .or_insert_with(|| Value::Object(Map::new()));
705            if let Value::Object(idle) = idle {
706                idle.insert("checkout_hours".to_string(), Value::from(hours));
707            }
708        }
709    }
710    for path in REMOVED_DATA_LAYER_PATHS {
711        let (container, leaf) = path.split_once('.').unwrap();
712        if take_nested(map, container, leaf).is_some() {
713            record_retired(out, prefix, path);
714        }
715    }
716}
717
718/// What a retired `enabled: false` no longer does. The translation only hides
719/// tools; indexing continues, so a user who relied on it to keep AFT out of a
720/// repository must also switch the indexes off. Mirrors the TypeScript
721/// `RETIRED_ENABLED_FALSE_INDEXES_NOTE`.
722pub const RETIRED_ENABLED_FALSE_INDEXES_NOTE: &str = "enabled: false no longer turns AFT off: it is translated to disabling every tool, but the trigram, semantic and callgraph indexes still build. To keep AFT from indexing this repository, also set indexes.trigram, indexes.semantic and indexes.callgraph to false.";
723
724/// Translate flat experimental aliases to nested settings and move the
725/// `experimental.bash` block to top-level `bash`. Graduating a block that sets
726/// a feature flag explicitly sets its omitted flags to false; otherwise the
727/// current default-on bash settings would silently enable them.
728fn translate_experimental_paths(
729    map: &mut Map<String, Value>,
730    prefix: &str,
731    out: &mut DocumentTranslation,
732) {
733    for (old_key, leaf) in [
734        ("experimental_lsp_ty", "lsp_ty"),
735        ("experimental_bash_rewrite", "rewrite"),
736        ("experimental_bash_compress", "compress"),
737        ("experimental_bash_background", "background"),
738    ] {
739        let Some(value) = map.remove(old_key) else {
740            continue;
741        };
742        record_retired(out, prefix, old_key);
743        let experimental = map
744            .entry("experimental")
745            .or_insert_with(|| Value::Object(Map::new()));
746        if !experimental.is_object() {
747            *experimental = Value::Object(Map::new());
748        }
749        let experimental = experimental.as_object_mut().unwrap();
750        let destination = if leaf == "lsp_ty" {
751            experimental
752        } else {
753            let bash = experimental
754                .entry("bash")
755                .or_insert_with(|| Value::Object(Map::new()));
756            if !bash.is_object() {
757                *bash = Value::Object(Map::new());
758            }
759            bash.as_object_mut().unwrap()
760        };
761        if destination.contains_key(leaf) {
762            let path = if leaf == "lsp_ty" {
763                leaf.to_string()
764            } else {
765                format!("bash.{leaf}")
766            };
767            superseded(
768                out,
769                old_key.to_string(),
770                format!("{old_key} is ignored because experimental.{path} is already set"),
771            );
772        } else {
773            destination.insert(leaf.to_string(), value);
774        }
775    }
776
777    let Some(experimental) = map.get("experimental").and_then(Value::as_object) else {
778        return;
779    };
780    let Some(legacy) = experimental.get("bash") else {
781        return;
782    };
783    if let Some(legacy) = legacy.as_object() {
784        if legacy.is_empty() {
785            record_retired(out, prefix, "experimental.bash");
786        }
787        for leaf in legacy.keys() {
788            record_retired(out, prefix, &format!("experimental.bash.{leaf}"));
789        }
790        if map.contains_key("bash") {
791            superseded(
792                out,
793                "experimental.bash".to_string(),
794                "experimental.bash is ignored because top-level \"bash\" is already set"
795                    .to_string(),
796            );
797        } else {
798            let mut bash = Map::new();
799            // A block with only reminder settings never opted into the
800            // feature flags, so they keep their current defaults instead of
801            // being written as false.
802            if ["rewrite", "compress", "background"]
803                .iter()
804                .any(|leaf| legacy.contains_key(*leaf))
805            {
806                for leaf in ["rewrite", "compress", "background"] {
807                    bash.insert(
808                        leaf.to_string(),
809                        Value::Bool(legacy.get(leaf) == Some(&Value::Bool(true))),
810                    );
811                }
812            }
813            for leaf in [
814                "long_running_reminder_enabled",
815                "long_running_reminder_interval_ms",
816            ] {
817                if let Some(value) = legacy.get(leaf) {
818                    bash.insert(leaf.to_string(), value.clone());
819                }
820            }
821            if !bash.is_empty() {
822                map.insert("bash".to_string(), Value::Object(bash));
823            }
824        }
825    } else {
826        record_retired(out, prefix, "experimental.bash");
827    }
828    let experimental = map
829        .get_mut("experimental")
830        .unwrap()
831        .as_object_mut()
832        .unwrap();
833    experimental.remove("bash");
834    if experimental.is_empty() {
835        map.remove("experimental");
836    }
837}
838
839/// Translate the retired keys of one tier/harness block in place.
840///
841/// The false runtime gates (`backup.enabled`, `inspect.enabled`, `bash`,
842/// `bash.enabled`) are current keys and only switch their behaviour off; they
843/// never remove a tool registration. Only `disabled_tools` does that.
844fn translate_block(
845    map: &mut Map<String, Value>,
846    // True only for the user file's base block, the one place the
847    // absent-base default disables may be added.
848    user_base: bool,
849    block_label: &str,
850    out: &mut DocumentTranslation,
851) {
852    let prefix = if block_label == "base" {
853        String::new()
854    } else {
855        format!("{block_label}.")
856    };
857    translate_github_aliases(map, &prefix, out);
858    translate_inspect_lsp_paths(map, &prefix, out);
859    translate_data_layer_paths(map, &prefix, out);
860    drop_no_effect_paths(map, &prefix, out);
861    translate_experimental_paths(map, &prefix, out);
862    if let Some(Value::Object(sandbox)) = map.get_mut("sandbox") {
863        if let Some(enabled) = sandbox.remove("enabled") {
864            record_retired(out, &prefix, "sandbox.enabled");
865            match enabled.as_bool() {
866                Some(enabled) => {
867                    let profile = sandbox
868                        .entry("profile")
869                        .or_insert_with(|| Value::Object(Map::new()));
870                    if let Value::Object(profile) = profile {
871                        for (role, mode) in [
872                            ("worker", if enabled { "strict" } else { "relaxed" }),
873                            ("head", if enabled { "strict" } else { "off" }),
874                        ] {
875                            if profile.get(role).is_some_and(|value| value != mode) {
876                                superseded(out, format!("{prefix}sandbox.enabled"), format!("sandbox.profile.{role} takes precedence over sandbox.enabled"));
877                            }
878                            profile
879                                .entry(role)
880                                .or_insert_with(|| Value::String(mode.to_string()));
881                        }
882                    }
883                }
884                None => out.warnings.push(TranslationWarning {
885                    code: "invalid_legacy_config",
886                    key: format!("{prefix}sandbox.enabled"),
887                    message: "Ignoring non-boolean sandbox.enabled; use sandbox.profile"
888                        .to_string(),
889                }),
890            }
891        }
892    }
893
894    // Canonicalize the retired `aft_`-prefixed host tool names (for example
895    // `aft_read` -> `read`) inside the disabled list.
896    let mut explicit_list = None;
897    if let Some(Value::Array(entries)) = map.get("disabled_tools") {
898        if entries.iter().all(Value::is_string) {
899            let mut canonical = Vec::with_capacity(entries.len());
900            let mut aliases = Vec::new();
901            for name in entries.iter().filter_map(Value::as_str) {
902                match legacy_tool_alias(name) {
903                    Some(host) => {
904                        aliases.push(name.to_string());
905                        canonical.push(host.to_string());
906                    }
907                    None => canonical.push(name.to_string()),
908                }
909            }
910            for alias in aliases {
911                record_retired(out, &prefix, &alias);
912            }
913            explicit_list = Some(canonical);
914        }
915    }
916
917    // `experimental.bash` was already recorded, leaf by leaf, and removed by
918    // `translate_experimental_paths`.
919    for (path, _) in RETIRED_PATHS {
920        if has_path(map, path) {
921            record_retired(out, &prefix, path);
922        }
923    }
924    let gates = false_runtime_gates(map);
925
926    if let Some(list) = &explicit_list {
927        map.insert(
928            "disabled_tools".to_string(),
929            Value::Array(list.iter().cloned().map(Value::String).collect()),
930        );
931    }
932
933    // Index switches: canonical leaf, then immediate legacy name, then the
934    // older experimental alias.
935    for (leaf, legacy, experimental) in INDEX_INPUTS {
936        let canonical = map
937            .get("indexes")
938            .and_then(Value::as_object)
939            .and_then(|indexes| indexes.get(leaf))
940            .and_then(Value::as_bool);
941        let legacy_value = map.remove(legacy);
942        let experimental_value = experimental.and_then(|key| map.remove(key));
943        let mut chosen = None;
944        for (key, value) in [
945            (Some(legacy), legacy_value),
946            (experimental, experimental_value),
947        ] {
948            let (Some(key), Some(value)) = (key, value) else {
949                continue;
950            };
951            let Some(value) = value.as_bool() else {
952                out.warnings.push(TranslationWarning {
953                    code: "invalid_legacy_config",
954                    key: key.to_string(),
955                    message: format!("Ignoring non-boolean {key}; use indexes.{leaf}"),
956                });
957                continue;
958            };
959            if let Some(canonical) = canonical {
960                if canonical != value {
961                    superseded(
962                        out,
963                        key.to_string(),
964                        format!(
965                            "{key}={value} is ignored because indexes.{leaf}={canonical} is set"
966                        ),
967                    );
968                }
969            } else if let Some(previous) = chosen {
970                if previous != value {
971                    superseded(
972                        out,
973                        key.to_string(),
974                        format!(
975                            "{key}={value} is ignored because {legacy}={previous} takes precedence"
976                        ),
977                    );
978                }
979            } else {
980                chosen = Some(value);
981            }
982        }
983        if canonical.is_none() {
984            if let Some(value) = chosen {
985                let indexes = map
986                    .entry("indexes".to_string())
987                    .or_insert_with(|| Value::Object(Map::new()));
988                if let Value::Object(indexes) = indexes {
989                    indexes.insert(leaf.to_string(), Value::Bool(value));
990                }
991            }
992        }
993    }
994
995    // github.enabled: false switches every leaf off unless the leaf is explicit.
996    if let Some(Value::Object(github)) = map.get_mut("github") {
997        if let Some(master) = github.remove("enabled") {
998            if master == Value::Bool(false) {
999                let mut notes = Vec::new();
1000                for leaf in ["read", "write", "shim"] {
1001                    match github.get(leaf) {
1002                        None => {
1003                            github.insert(leaf.to_string(), Value::Bool(false));
1004                        }
1005                        Some(Value::Bool(true)) => notes.push(format!(
1006                            "github.enabled=false is ignored for github.{leaf} because github.{leaf}=true is set"
1007                        )),
1008                        Some(_) => {}
1009                    }
1010                }
1011                for note in notes {
1012                    superseded(out, "github.enabled".to_string(), note);
1013                }
1014            }
1015        }
1016    }
1017
1018    // Registration generators.
1019    let surface = map.remove("tool_surface");
1020    let hoist = map.remove("hoist_builtin_tools");
1021    let enabled = map.remove("enabled");
1022    let mut generated: BTreeSet<String> = BTreeSet::new();
1023    let mut explicit_surface = false;
1024    if let Some(surface) = surface {
1025        match surface.as_str().and_then(surface_disables) {
1026            Some(names) => {
1027                explicit_surface = true;
1028                generated.extend(names.into_iter().map(str::to_string));
1029            }
1030            None => out.warnings.push(TranslationWarning {
1031                code: "invalid_legacy_config",
1032                key: "tool_surface".to_string(),
1033                message: "Ignoring unknown tool_surface value; use disabled_tools".to_string(),
1034            }),
1035        }
1036    }
1037    if hoist == Some(Value::Bool(false)) {
1038        generated.extend(HOST_TOOL_NAMES.iter().map(|name| (*name).to_string()));
1039    }
1040    if enabled == Some(Value::Bool(false)) {
1041        generated.extend(CANONICAL_TOOLS.iter().map(|name| (*name).to_string()));
1042        out.warnings.push(TranslationWarning {
1043            code: "legacy_enabled_false_indexes_still_build",
1044            key: if block_label == "base" {
1045                "enabled".to_string()
1046            } else {
1047                format!("{block_label}.enabled")
1048            },
1049            message: RETIRED_ENABLED_FALSE_INDEXES_NOTE.to_string(),
1050        });
1051    }
1052
1053    if !gates.is_empty() && explicit_list.is_none() {
1054        out.warnings.push(TranslationWarning {
1055            code: "legacy_runtime_gate_runtime_only",
1056            key: block_label.to_string(),
1057            message: format!(
1058                "{} now restricts runtime behavior only and no longer removes tool registrations; list tools in disabled_tools to unregister them",
1059                gates.join(", ")
1060            ),
1061        });
1062    }
1063
1064    if explicit_list.is_some() {
1065        if explicit_surface || !generated.is_empty() {
1066            superseded(
1067                out,
1068                block_label.to_string(),
1069                "disabled_tools is set explicitly, so legacy tool_surface/hoist_builtin_tools/enabled do not change registration".to_string(),
1070            );
1071        }
1072        return;
1073    }
1074
1075    let list = if user_base {
1076        if explicit_surface {
1077            Some(generated)
1078        } else if !generated.is_empty() {
1079            let mut with_default = generated;
1080            with_default.extend(
1081                DEFAULT_DISABLED_TOOLS
1082                    .iter()
1083                    .map(|name| (*name).to_string()),
1084            );
1085            Some(with_default)
1086        } else {
1087            None
1088        }
1089    } else {
1090        (!generated.is_empty()).then_some(generated)
1091    };
1092    if let Some(list) = list {
1093        map.insert(
1094            "disabled_tools".to_string(),
1095            Value::Array(list.into_iter().map(Value::String).collect()),
1096        );
1097    }
1098}
1099
1100/// Which trust tier a raw document belongs to.
1101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1102pub enum DocumentTier {
1103    User,
1104    Project,
1105}
1106
1107/// Translate every block (base plus each `harnesses.<id>` object) of one raw
1108/// configuration document, in place.
1109///
1110/// Only the user file's base block receives the absent-base default
1111/// (`aft_move`/`aft_delete`) when its legacy keys generate disables: that
1112/// default applies once, at user-base resolution. A project file's base block
1113/// contributes only the names its own legacy keys imply, so a legacy key in a
1114/// repository can never re-disable tools the user enabled. The translated
1115/// values are current keys, so the resolver's project-tier rules apply to them
1116/// exactly as if the file had spelled them out.
1117pub fn translate_document(map: &mut Map<String, Value>, tier: DocumentTier) -> DocumentTranslation {
1118    let mut out = DocumentTranslation::default();
1119    translate_runon_enabled(map, tier, "", &mut out);
1120    translate_block(map, tier == DocumentTier::User, "base", &mut out);
1121    translate_shapes(map, tier, "", &mut out);
1122    if let Some(Value::Object(harnesses)) = map.get_mut("harnesses") {
1123        for (name, block) in harnesses.iter_mut() {
1124            if let Value::Object(block) = block {
1125                translate_runon_enabled(block, tier, &format!("harnesses.{name}."), &mut out);
1126                translate_block(block, false, &format!("harnesses.{name}"), &mut out);
1127                translate_shapes(block, tier, &format!("harnesses.{name}."), &mut out);
1128            }
1129        }
1130    }
1131    out.retired_keys.sort();
1132    out.retired_keys.dedup();
1133    out
1134}
1135
1136fn translate_shapes(
1137    map: &mut Map<String, Value>,
1138    tier: DocumentTier,
1139    prefix: &str,
1140    out: &mut DocumentTranslation,
1141) {
1142    for edit in settings_shape::edits(map, tier, prefix.is_empty()) {
1143        record_retired(out, prefix, edit.notice);
1144        edit.apply(map);
1145    }
1146}
1147
1148/// The retired bash gate was user-only. Projects drop it without changing
1149/// their current remote-run setting; an explicit false in a user block keeps
1150/// that block's remote runs off. Absence already uses the current setting.
1151fn translate_runon_enabled(
1152    map: &mut Map<String, Value>,
1153    tier: DocumentTier,
1154    prefix: &str,
1155    out: &mut DocumentTranslation,
1156) {
1157    // Keep an empty bash object: its normal defaults still take precedence
1158    // over retired experimental bash flags, unlike an absent bash setting.
1159    if let Some(value) = map
1160        .get_mut("bash")
1161        .and_then(Value::as_object_mut)
1162        .and_then(|bash| bash.remove("runon_enabled"))
1163    {
1164        record_retired(out, prefix, "bash.runon_enabled");
1165        if tier == DocumentTier::User && value == Value::Bool(false) {
1166            let remote = map
1167                .entry("remote_exec".to_string())
1168                .or_insert_with(|| Value::Object(Map::new()));
1169            if let Value::Object(remote) = remote {
1170                remote.insert("enabled".to_string(), Value::Bool(false));
1171            }
1172        }
1173    }
1174}
1175
1176/// Whether a translation carries the retired `enabled: false` note.
1177fn has_enabled_false_note(translation: &DocumentTranslation) -> bool {
1178    translation
1179        .warnings
1180        .iter()
1181        .any(|warning| warning.code == "legacy_enabled_false_indexes_still_build")
1182}
1183
1184/// Retired keys that no longer do anything, each with the notice sentence that
1185/// says so. Nothing is applied for them, so a notice never counts them among
1186/// the keys whose "current equivalents" were applied. Kept in key order;
1187/// mirrors the TypeScript `NO_EFFECT_RETIRED_NOTES`.
1188pub const NO_EFFECT_RETIRED_NOTES: [(&str, &str); 4] = [
1189    ("bridge.hang_threshold", RETIRED_HANG_THRESHOLD_NOTE),
1190    (
1191        "inspect.max_drill_down_items",
1192        "inspect.max_drill_down_items never had an effect, so the setting can be removed.",
1193    ),
1194    (
1195        "inspect.tier2_idle_minutes",
1196        "inspect.tier2_idle_minutes no longer does anything: AFT runs whole-repository analyses only when aft_inspect is called, so the setting can be removed.",
1197    ),
1198    (
1199        "inspect.tier2_soft_deadline_ms",
1200        "inspect.tier2_soft_deadline_ms never had an effect, so the setting can be removed.",
1201    ),
1202];
1203
1204/// The no-effect sentence for a retired key, which may carry a
1205/// `harnesses.<id>.` prefix.
1206fn no_effect_note(key: &str) -> Option<&'static str> {
1207    if names_path(key, CALLGRAPH_CHUNK_KEY) {
1208        return Some(CALLGRAPH_CHUNK_NOTE);
1209    }
1210    NO_EFFECT_RETIRED_NOTES
1211        .iter()
1212        .chain(REMOVED_DATA_LAYER_NOTES.iter())
1213        .find(|(path, _)| names_path(key, path))
1214        .map(|(_, note)| *note)
1215}
1216
1217/// Whether `key`, which may carry a `harnesses.<id>.` prefix, is `path`.
1218fn names_path(key: &str, path: &str) -> bool {
1219    key == path
1220        || key
1221            .strip_suffix(path)
1222            .is_some_and(|prefix| prefix.ends_with('.'))
1223}
1224
1225/// Why each removed data-layer key no longer does anything, in
1226/// [`REMOVED_DATA_LAYER_PATHS`] order. Mirrors the TypeScript
1227/// `REMOVED_DATA_LAYER_NOTES`.
1228pub const REMOVED_DATA_LAYER_NOTES: [(&str, &str); 3] = [
1229    (
1230        "views.callgraph_copies",
1231        "views.callgraph_copies is gone because no checkout borrows another checkout's call graph any more.",
1232    ),
1233    (
1234        "views.enabled",
1235        "views.enabled is gone because AFT now keeps one index store per repository and always uses it.",
1236    ),
1237    (
1238        "worktree.ram_overlay",
1239        "worktree.ram_overlay is gone because every worktree now has its own index state, so there is no borrowed index to patch in memory.",
1240    ),
1241];
1242
1243/// The sentence saying a user file that still names `views.idle_checkout_hours`
1244/// will be refused. Mirrors the TypeScript `retiredIdleCheckoutHoursNote`.
1245pub fn retired_idle_checkout_hours_note() -> String {
1246    let (retired, replacement) = RETIRED_IDLE_CHECKOUT_HOURS;
1247    format!(
1248        "{retired} is now {replacement}; from {} AFT refuses a user config file that still sets {retired}.",
1249        refused_from_version()
1250    )
1251}
1252
1253/// Build a retired-key notice. `with_equivalents` renders the sentence about
1254/// keys whose current equivalents were applied, given those keys joined by
1255/// ", "; it is used only when there are such keys. The sentences for keys
1256/// that no longer do anything follow, once each. A file whose only retired
1257/// keys have no effect gets just those sentences. `still_in_file` is true
1258/// when the file keeps the retired keys (it was not rewritten), so the notice
1259/// warns about keys a later release refuses.
1260fn retired_keys_notice(
1261    translation: &DocumentTranslation,
1262    still_in_file: bool,
1263    with_equivalents: impl FnOnce(&str) -> String,
1264) -> String {
1265    let mut equivalents = Vec::new();
1266    let mut notes: Vec<&str> = Vec::new();
1267    for key in &translation.retired_keys {
1268        match no_effect_note(key) {
1269            Some(note) => {
1270                if !notes.contains(&note) {
1271                    notes.push(note);
1272                }
1273            }
1274            None => equivalents.push(key.as_str()),
1275        }
1276    }
1277    notes.sort_by_key(|note| {
1278        NO_EFFECT_RETIRED_NOTES
1279            .iter()
1280            .chain(REMOVED_DATA_LAYER_NOTES.iter())
1281            .position(|(_, known)| known == note)
1282    });
1283    let mut parts = Vec::new();
1284    if !equivalents.is_empty() {
1285        parts.push(with_equivalents(&equivalents.join(", ")));
1286        if has_enabled_false_note(translation) {
1287            parts.push(RETIRED_ENABLED_FALSE_INDEXES_NOTE.to_string());
1288        }
1289        if still_in_file
1290            && equivalents
1291                .iter()
1292                .any(|key| names_path(key, RETIRED_IDLE_CHECKOUT_HOURS.0))
1293        {
1294            parts.push(retired_idle_checkout_hours_note());
1295        }
1296    }
1297    parts.extend(notes.into_iter().map(str::to_string));
1298    parts.join(" ")
1299}
1300
1301/// Notice for a project config file whose retired keys were translated in
1302/// memory. The file itself is never written: it is shared through the repository. Mirrors the
1303/// TypeScript `legacyConfigNoticeMessage`.
1304pub fn project_retired_keys_notice(path: &str, translation: &DocumentTranslation) -> String {
1305    retired_keys_notice(translation, true, |keys| {
1306        format!(
1307            "{path} uses retired keys ({keys}); AFT applied their current equivalents, with the same limits a project config has for those keys. Run `npx @cortexkit/aft doctor --fix` to update the file."
1308        )
1309    })
1310}
1311
1312/// Notice for the user config file after AFT rewrote its retired keys. It
1313/// names only the keys the rewrite replaced. Removed data-layer keys remain
1314/// in the file for the loader to refuse until an explicit doctor fix removes them.
1315pub fn user_config_migrated_notice(
1316    path: &str,
1317    backup: &str,
1318    translation: &DocumentTranslation,
1319) -> String {
1320    retired_keys_notice(translation, false, |keys| {
1321        format!(
1322            "AFT updated {path}: its retired keys ({keys}) now use their current equivalents. The previous file is saved as {backup}."
1323        )
1324    })
1325}
1326
1327/// Notice for the user config file when AFT could not rewrite it and applied
1328/// the current equivalents in memory instead.
1329pub fn user_config_not_migrated_notice(
1330    path: &str,
1331    reason: &str,
1332    translation: &DocumentTranslation,
1333) -> String {
1334    retired_keys_notice(translation, true, |keys| {
1335        format!(
1336            "{path} uses retired keys ({keys}); AFT applied their current equivalents but could not update the file ({reason}). Run `npx @cortexkit/aft doctor --fix` to update it."
1337        )
1338    })
1339}
1340
1341/// Sorted, de-duplicated disabled list.
1342pub fn normalize_tool_list<I, S>(names: I) -> Vec<String>
1343where
1344    I: IntoIterator<Item = S>,
1345    S: Into<String>,
1346{
1347    names
1348        .into_iter()
1349        .map(Into::into)
1350        .collect::<BTreeSet<_>>()
1351        .into_iter()
1352        .collect()
1353}
1354
1355/// Distinct unknown names in a resolved disabled list, sorted.
1356pub fn unknown_disabled_tools(disabled: &[String]) -> Vec<String> {
1357    normalize_tool_list(disabled.iter().filter(|name| !is_known_tool(name)).cloned())
1358}
1359
1360/// Validate a resolved configuration object before anything consumes it.
1361///
1362/// A resolved configuration must carry the registration choice and every index
1363/// switch explicitly: a missing field must never be silently replaced by a
1364/// serde or historical default. Missing containers are reported instead of
1365/// their children. Errors are sorted by path.
1366pub fn validate_resolved_config(value: &Value) -> Result<(), Vec<String>> {
1367    let mut errors = Vec::new();
1368    let Some(object) = value.as_object() else {
1369        return Err(vec!["invalid_resolved_config:type:$".to_string()]);
1370    };
1371    match object.get("disabled_tools") {
1372        None => errors.push("invalid_resolved_config:missing:disabled_tools".to_string()),
1373        Some(Value::Array(entries)) if entries.iter().all(Value::is_string) => {}
1374        Some(_) => errors.push("invalid_resolved_config:type:disabled_tools".to_string()),
1375    }
1376    match object.get("indexes") {
1377        None => errors.push("invalid_resolved_config:missing:indexes".to_string()),
1378        Some(Value::Object(indexes)) => {
1379            for leaf in ["callgraph", "semantic", "trigram"] {
1380                match indexes.get(leaf) {
1381                    None => errors.push(format!("invalid_resolved_config:missing:indexes.{leaf}")),
1382                    Some(Value::Bool(_)) => {}
1383                    Some(_) => errors.push(format!("invalid_resolved_config:type:indexes.{leaf}")),
1384                }
1385            }
1386        }
1387        Some(_) => errors.push("invalid_resolved_config:type:indexes".to_string()),
1388    }
1389    errors.sort_by(|left, right| {
1390        let path = |error: &String| error.rsplit(':').next().unwrap_or_default().to_string();
1391        path(left).cmp(&path(right))
1392    });
1393    if errors.is_empty() {
1394        Ok(())
1395    } else {
1396        Err(errors)
1397    }
1398}
1399
1400/// Explicit absent marker used by the notice projection.
1401fn absent() -> Value {
1402    let mut marker = Map::new();
1403    marker.insert("absent".to_string(), Value::Bool(true));
1404    Value::Object(marker)
1405}
1406
1407fn project_block(block: &Map<String, Value>) -> Value {
1408    let mut projected = Map::new();
1409
1410    let mut legacy_paths = Map::new();
1411    // Retired keys with no replacement are projected too: otherwise adding one
1412    // to a file whose notice was already acknowledged would keep the old
1413    // digest and the saved record would hide the new notice. The data-layer
1414    // keys are projected for the same reason.
1415    for path in RETIRED_PATHS
1416        .into_iter()
1417        .chain(REMOVED_NO_EFFECT_PATHS)
1418        .map(|(path, _)| path)
1419        .chain(DATA_LAYER_RETIRED_PATHS)
1420        .chain(["bash.runon_enabled"])
1421        .chain(REMOVED_DATA_LAYER_PATHS)
1422        .chain([CALLGRAPH_CHUNK_KEY])
1423    {
1424        let value = match path.split_once('.') {
1425            Some((container, leaf)) => block
1426                .get(container)
1427                .and_then(Value::as_object)
1428                .and_then(|inner| inner.get(leaf)),
1429            None => block.get(path),
1430        };
1431        if let Some(value) = value {
1432            legacy_paths.insert(path.to_string(), value.clone());
1433        }
1434    }
1435    projected.insert("legacy_paths".to_string(), Value::Object(legacy_paths));
1436
1437    let mut gates = Map::new();
1438    if let Some(value) = block
1439        .get("backup")
1440        .and_then(Value::as_object)
1441        .and_then(|backup| backup.get("enabled"))
1442    {
1443        gates.insert("backup.enabled".to_string(), value.clone());
1444    }
1445    if let Some(value) = block
1446        .get("inspect")
1447        .and_then(Value::as_object)
1448        .and_then(|inspect| inspect.get("enabled"))
1449    {
1450        gates.insert("inspect.enabled".to_string(), value.clone());
1451    }
1452    match block.get("bash") {
1453        Some(Value::Bool(value)) => {
1454            gates.insert("bash".to_string(), Value::Bool(*value));
1455        }
1456        Some(Value::Object(bash)) => {
1457            if let Some(value) = bash.get("enabled") {
1458                gates.insert("bash.enabled".to_string(), value.clone());
1459            }
1460        }
1461        _ => {}
1462    }
1463    projected.insert("runtime_gates".to_string(), Value::Object(gates));
1464    // The notice identity records which shapes changed, not the potentially
1465    // sensitive initialization options. Bash booleans are projected above.
1466    let shapes: std::collections::BTreeSet<_> =
1467        settings_shape::edits(block, DocumentTier::Project, false)
1468            .into_iter()
1469            .filter(|edit| edit.path[0] != "bash")
1470            .map(|edit| edit.notice)
1471            .collect();
1472    if !shapes.is_empty() {
1473        projected.insert("legacy_shapes".into(), serde_json::json!(shapes));
1474    }
1475
1476    let (aliases, disabled) = match block.get("disabled_tools") {
1477        Some(Value::Array(entries)) => {
1478            let names: Vec<String> = entries
1479                .iter()
1480                .filter_map(Value::as_str)
1481                .map(str::to_string)
1482                .collect();
1483            let aliases = normalize_tool_list(
1484                names
1485                    .iter()
1486                    .filter(|name| legacy_tool_alias(name).is_some())
1487                    .cloned(),
1488            );
1489            (
1490                aliases,
1491                Value::Array(
1492                    normalize_tool_list(names)
1493                        .into_iter()
1494                        .map(Value::String)
1495                        .collect(),
1496                ),
1497            )
1498        }
1499        Some(other) => (Vec::new(), other.clone()),
1500        None => (Vec::new(), absent()),
1501    };
1502    projected.insert(
1503        "legacy_disabled_entries".to_string(),
1504        Value::Array(aliases.into_iter().map(Value::String).collect()),
1505    );
1506    projected.insert("disabled_tools".to_string(), disabled);
1507
1508    let mut github = Map::new();
1509    for leaf in ["read", "shim", "write"] {
1510        let value = block
1511            .get("github")
1512            .and_then(Value::as_object)
1513            .and_then(|github| github.get(leaf))
1514            .cloned()
1515            .unwrap_or_else(absent);
1516        github.insert(leaf.to_string(), value);
1517    }
1518    projected.insert("github".to_string(), Value::Object(github));
1519
1520    let mut indexes = Map::new();
1521    for (leaf, legacy, experimental) in INDEX_INPUTS {
1522        let mut inputs = Map::new();
1523        inputs.insert(
1524            "canonical".to_string(),
1525            block
1526                .get("indexes")
1527                .and_then(Value::as_object)
1528                .and_then(|indexes| indexes.get(leaf))
1529                .cloned()
1530                .unwrap_or_else(absent),
1531        );
1532        inputs.insert(
1533            legacy.to_string(),
1534            block.get(legacy).cloned().unwrap_or_else(absent),
1535        );
1536        if let Some(experimental) = experimental {
1537            inputs.insert(
1538                experimental.to_string(),
1539                block.get(experimental).cloned().unwrap_or_else(absent),
1540            );
1541        }
1542        indexes.insert(leaf.to_string(), Value::Object(inputs));
1543    }
1544    projected.insert("indexes".to_string(), Value::Object(indexes));
1545    Value::Object(projected)
1546}
1547
1548/// Build the `notice_projection_v1` object for one raw (untranslated) config
1549/// document. Only inputs that influence translation are projected, so
1550/// comments, formatting, key order and unrelated settings never change it.
1551pub fn notice_projection(raw: Option<&Map<String, Value>>) -> Value {
1552    let mut blocks = Map::new();
1553    if let Some(raw) = raw {
1554        blocks.insert("base".to_string(), project_block(raw));
1555        if let Some(Value::Object(harnesses)) = raw.get("harnesses") {
1556            for (name, block) in harnesses {
1557                if let Value::Object(block) = block {
1558                    blocks.insert(format!("harnesses.{name}"), project_block(block));
1559                }
1560            }
1561        }
1562    }
1563    let mut projection = Map::new();
1564    projection.insert(
1565        "projection".to_string(),
1566        Value::String("notice_projection_v1".to_string()),
1567    );
1568    projection.insert("file_absent".to_string(), Value::Bool(raw.is_none()));
1569    projection.insert("blocks".to_string(), Value::Object(blocks));
1570    Value::Object(projection)
1571}
1572
1573/// Compact JSON with object keys sorted at every level.
1574pub fn canonical_json(value: &Value) -> String {
1575    match value {
1576        Value::Object(map) => {
1577            let mut keys: Vec<&String> = map.keys().collect();
1578            keys.sort();
1579            let body = keys
1580                .into_iter()
1581                .map(|key| {
1582                    format!(
1583                        "{}:{}",
1584                        serde_json::to_string(key).unwrap_or_default(),
1585                        canonical_json(&map[key])
1586                    )
1587                })
1588                .collect::<Vec<_>>()
1589                .join(",");
1590            format!("{{{body}}}")
1591        }
1592        Value::Array(items) => format!(
1593            "[{}]",
1594            items
1595                .iter()
1596                .map(canonical_json)
1597                .collect::<Vec<_>>()
1598                .join(",")
1599        ),
1600        other => serde_json::to_string(other).unwrap_or_default(),
1601    }
1602}
1603
1604/// SHA-256 hex digest of the canonical projection.
1605pub fn notice_digest(projection: &Value) -> String {
1606    let digest = Sha256::digest(canonical_json(projection).as_bytes());
1607    digest.iter().map(|byte| format!("{byte:02x}")).collect()
1608}
1609
1610#[cfg(test)]
1611mod tests {
1612    use super::*;
1613    use serde_json::json;
1614
1615    fn translate(doc: Value) -> (Value, DocumentTranslation) {
1616        let Value::Object(mut map) = doc else {
1617            panic!("object")
1618        };
1619        let out = translate_document(&mut map, DocumentTier::User);
1620        (Value::Object(map), out)
1621    }
1622
1623    fn translate_project(doc: Value) -> Value {
1624        let Value::Object(mut map) = doc else {
1625            panic!("object")
1626        };
1627        translate_document(&mut map, DocumentTier::Project);
1628        Value::Object(map)
1629    }
1630
1631    #[test]
1632    fn removed_config_key_errors_match_shared_rust_typescript_fixtures() {
1633        let fixture: Value = serde_json::from_str(include_str!(
1634            "../../aft/tests/fixtures/feature_config/removed_config_key_errors.json"
1635        ))
1636        .unwrap();
1637        for case in fixture["cases"].as_array().unwrap() {
1638            let doc = case["doc"].as_object().unwrap();
1639            let release = parse_release(case["release"].as_str().unwrap()).unwrap();
1640            let tier = match case["tier"].as_str().unwrap() {
1641                "user" => DocumentTier::User,
1642                "project" => DocumentTier::Project,
1643                other => panic!("unknown fixture tier: {other}"),
1644            };
1645            let errors = match tier {
1646                DocumentTier::User => removed_config_key_errors_at(doc, release),
1647                DocumentTier::Project => removed_errors(doc, release, false),
1648            };
1649            let expected = case["errors"]
1650                .as_array()
1651                .unwrap()
1652                .iter()
1653                .map(|error| error.as_str().unwrap())
1654                .collect::<Vec<_>>();
1655            assert_eq!(errors, expected, "fixture {}", case["name"]);
1656            if let Some(translated) = case.get("translated") {
1657                assert!(errors.is_empty(), "only accepted files translate");
1658                let mut map = doc.clone();
1659                let out = translate_document(&mut map, tier);
1660                assert_eq!(Value::Object(map), *translated, "fixture {}", case["name"]);
1661                if let Some(notice) = case.get("notice") {
1662                    assert_eq!(
1663                        project_retired_keys_notice("/project/aft.jsonc", &out),
1664                        notice.as_str().unwrap(),
1665                        "fixture {}",
1666                        case["name"]
1667                    );
1668                }
1669            }
1670        }
1671    }
1672
1673    #[test]
1674    fn legacy_enabled_false_warns_that_indexes_still_build() {
1675        let (doc, out) = translate(json!({"enabled": false}));
1676        assert!(
1677            doc.get("indexes").is_none(),
1678            "indexes stay at their defaults"
1679        );
1680        let warning = out
1681            .warnings
1682            .iter()
1683            .find(|warning| warning.code == "legacy_enabled_false_indexes_still_build")
1684            .expect("enabled:false notice");
1685        assert_eq!(warning.key, "enabled");
1686        assert!(warning.message.contains("indexes still build"));
1687        assert!(warning.message.contains("indexes.trigram"));
1688    }
1689
1690    /// A project block contributes only what its own legacy keys imply; the
1691    /// move/delete default belongs to the user base alone.
1692    #[test]
1693    fn project_base_blocks_never_receive_the_default_disables() {
1694        assert_eq!(
1695            translate_project(json!({"hoist_builtin_tools": false}))["disabled_tools"],
1696            json!([
1697                "apply_patch",
1698                "bash",
1699                "edit",
1700                "glob",
1701                "grep",
1702                "read",
1703                "write"
1704            ])
1705        );
1706        assert_eq!(translate_project(json!({"tool_surface": "all"})), json!({}));
1707        assert_eq!(
1708            translate_project(json!({"tool_surface": "recommended"}))["disabled_tools"],
1709            json!(["aft_callgraph", "aft_delete", "aft_move"])
1710        );
1711    }
1712
1713    /// A false runtime gate only switches its behaviour off: it never removes
1714    /// a registration, alone or beside a retired key, and the translation
1715    /// warns `legacy_runtime_gate_runtime_only` so the user knows to list the
1716    /// tool in `disabled_tools`.
1717    #[test]
1718    fn false_runtime_gates_never_generate_disables() {
1719        for doc in [
1720            json!({"backup": {"enabled": false}}),
1721            json!({"inspect": {"enabled": false}}),
1722            json!({"bash": false}),
1723            json!({"bash": {"enabled": false}}),
1724        ] {
1725            let (value, out) = translate(doc.clone());
1726            assert!(value.get("disabled_tools").is_none(), "{doc}");
1727            assert_eq!(out.legacy_input, doc["bash"] == false, "{doc}");
1728            assert!(
1729                out.warnings
1730                    .iter()
1731                    .any(|warning| warning.code == "legacy_runtime_gate_runtime_only"),
1732                "{doc}"
1733            );
1734            assert!(translate_project(doc.clone())
1735                .get("disabled_tools")
1736                .is_none());
1737        }
1738        let (value, _) = translate(json!({"bash": false, "hoist_builtin_tools": false}));
1739        assert_eq!(
1740            value["disabled_tools"],
1741            json!([
1742                "aft_delete",
1743                "aft_move",
1744                "apply_patch",
1745                "bash",
1746                "edit",
1747                "glob",
1748                "grep",
1749                "read",
1750                "write"
1751            ]),
1752            "only the retired hoist key generates disables"
1753        );
1754    }
1755
1756    #[test]
1757    fn policy_constants_match_the_shared_artifact() {
1758        let path = std::path::Path::new(crate::test_support::manifest_dir())
1759            .join("../../spec/feature-config/migration-policy.json");
1760        let Ok(text) = std::fs::read_to_string(path) else {
1761            return;
1762        };
1763        let artifact: Value = serde_json::from_str(&text).unwrap();
1764        assert_eq!(artifact["id"], MIGRATION_POLICY_ID);
1765        assert_eq!(artifact["introduced_minor"], "0.58");
1766        assert!(
1767            artifact.get("reject_from_minor").is_none(),
1768            "retired keys are never rejected"
1769        );
1770        for (path, replacement) in RETIRED_PATHS {
1771            assert_eq!(artifact["paths"][path], replacement, "{path}");
1772        }
1773        for (alias, canonical) in LEGACY_TOOL_ALIASES {
1774            assert_eq!(artifact["disabled_list_names"][alias], canonical);
1775        }
1776    }
1777
1778    #[test]
1779    fn surfaces_translate_to_literal_sets() {
1780        let (all, _) = translate(json!({"tool_surface": "all"}));
1781        assert_eq!(all, json!({"disabled_tools": []}));
1782        let (recommended, _) = translate(json!({"tool_surface": "recommended"}));
1783        assert_eq!(
1784            recommended["disabled_tools"],
1785            json!(["aft_callgraph", "aft_delete", "aft_move"])
1786        );
1787        let (minimal, _) = translate(json!({"tool_surface": "minimal"}));
1788        assert_eq!(minimal["disabled_tools"].as_array().unwrap().len(), 20);
1789    }
1790
1791    #[test]
1792    fn retired_base_key_unions_with_default_and_explicit_empty_wins() {
1793        let (hoist, out) = translate(json!({"hoist_builtin_tools": false}));
1794        assert_eq!(
1795            hoist["disabled_tools"],
1796            json!([
1797                "aft_delete",
1798                "aft_move",
1799                "apply_patch",
1800                "bash",
1801                "edit",
1802                "glob",
1803                "grep",
1804                "read",
1805                "write"
1806            ])
1807        );
1808        assert!(out.legacy_input);
1809        assert_eq!(out.retired_keys, vec!["hoist_builtin_tools"]);
1810        let (explicit, _) = translate(json!({"hoist_builtin_tools": false, "disabled_tools": []}));
1811        assert_eq!(explicit["disabled_tools"], json!([]));
1812    }
1813
1814    /// Every retired key translates; none is ever refused, and the translation
1815    /// names each one (harness keys with their block prefix).
1816    #[test]
1817    fn retired_keys_translate_and_are_listed() {
1818        let (value, out) = translate(json!({
1819            "disabled_tools": ["aft_glob"],
1820            "search_index": true,
1821            "harnesses": {"pi": {"semantic_search": false}}
1822        }));
1823        assert_eq!(
1824            value,
1825            json!({
1826                "disabled_tools": ["glob"],
1827                "indexes": {"trigram": true},
1828                "harnesses": {"pi": {"indexes": {"semantic": false}}}
1829            })
1830        );
1831        assert!(out.legacy_input);
1832        assert_eq!(
1833            out.retired_keys,
1834            vec!["aft_glob", "harnesses.pi.semantic_search", "search_index"]
1835        );
1836    }
1837
1838    #[test]
1839    fn index_precedence_is_canonical_then_legacy_then_experimental() {
1840        let (value, _) =
1841            translate(json!({"experimental_search_index": false, "search_index": true}));
1842        assert_eq!(value, json!({"indexes": {"trigram": true}}));
1843        let (value, out) =
1844            translate(json!({"indexes": {"semantic": false}, "semantic_search": true}));
1845        assert_eq!(value, json!({"indexes": {"semantic": false}}));
1846        assert_eq!(out.warnings[0].code, "superseded_legacy_config");
1847    }
1848
1849    /// The GitHub enable aliases translate to the canonical leaves with the
1850    /// same precedence `doctor --fix` uses: canonical leaf, then a
1851    /// `github.enabled: false` in the same block, then the alias.
1852    #[test]
1853    fn retired_github_aliases_translate_like_doctor_fix() {
1854        let (value, out) = translate(json!({
1855            "gh_read": {"enabled": true},
1856            "gh_shim": {"enabled": false, "binary_path": "/opt/aft"}
1857        }));
1858        assert_eq!(
1859            value,
1860            json!({
1861                "github": {"read": true, "shim": false},
1862                "gh_shim": {"binary_path": "/opt/aft"}
1863            })
1864        );
1865        assert_eq!(out.retired_keys, vec!["gh_read", "gh_shim.enabled"]);
1866
1867        let (value, out) =
1868            translate(json!({"gh_read": {"enabled": true}, "github": {"read": false}}));
1869        assert_eq!(value, json!({"github": {"read": false}}));
1870        assert_eq!(out.warnings[0].code, "superseded_legacy_config");
1871
1872        let (value, _) = translate(json!({
1873            "harnesses": {"pi": {"gh_shim": {"enabled": true}, "github": {"enabled": false}}}
1874        }));
1875        assert_eq!(
1876            value,
1877            json!({"harnesses": {"pi": {"github": {"read": false, "write": false, "shim": false}}}})
1878        );
1879
1880        let (value, out) = translate(json!({"gh_shim": {"binary_path": "/opt/aft"}}));
1881        assert_eq!(value, json!({"gh_shim": {"binary_path": "/opt/aft"}}));
1882        assert!(!out.legacy_input);
1883    }
1884
1885    #[test]
1886    fn retired_inspect_and_lsp_keys_translate_like_doctor_fix() {
1887        let (value, out) = translate(json!({
1888            "idle": {"lsp_ttl_minutes": 3, "root_ttl_minutes": 20},
1889            "inspect": {"tier2_soft_deadline_ms": 50, "max_drill_down_items": 20}
1890        }));
1891        assert_eq!(
1892            value,
1893            json!({"idle": {"root_ttl_minutes": 20}, "lsp": {"idle_minutes": 5}})
1894        );
1895        assert_eq!(
1896            out.retired_keys,
1897            vec![
1898                "idle.lsp_ttl_minutes",
1899                "inspect.max_drill_down_items",
1900                "inspect.tier2_soft_deadline_ms"
1901            ]
1902        );
1903        let (value, _) = translate(json!({"idle": {"lsp_ttl_minutes": "x"}}));
1904        assert_eq!(value, json!({"lsp": {"idle_minutes": 60}}));
1905        // A whole number written as a float is that number, as JavaScript
1906        // (and so the TypeScript translation) reads it; anything else is the
1907        // default.
1908        for (text, minutes) in [
1909            ("12.0", 12),
1910            ("12", 12),
1911            ("1e3", 1000),
1912            ("12.5", 60),
1913            ("1e20", 60),
1914            ("9007199254740993", 60),
1915        ] {
1916            let doc: Value =
1917                serde_json::from_str(&format!(r#"{{"idle": {{"lsp_ttl_minutes": {text}}}}}"#))
1918                    .unwrap();
1919            let (value, _) = translate(doc);
1920            assert_eq!(value, json!({"lsp": {"idle_minutes": minutes}}), "{text}");
1921        }
1922        let (value, out) = translate(json!({
1923            "idle": {"lsp_ttl_minutes": 10},
1924            "lsp": {"idle_minutes": "never"}
1925        }));
1926        assert_eq!(value, json!({"lsp": {"idle_shutdown": false}}));
1927        assert_eq!(out.warnings[0].code, "superseded_legacy_config");
1928    }
1929
1930    #[test]
1931    fn github_master_false_fills_absent_leaves() {
1932        let (value, _) = translate(json!({"github": {"enabled": false, "shim": true}}));
1933        assert_eq!(
1934            value,
1935            json!({"github": {"shim": true, "read": false, "write": false}})
1936        );
1937    }
1938
1939    #[test]
1940    fn notices_name_the_file_and_the_retired_keys() {
1941        let (_, out) = translate(json!({"search_index": false, "hoist_builtin_tools": true}));
1942        let project = project_retired_keys_notice("/repo/.cortexkit/aft.jsonc", &out);
1943        assert!(project.starts_with(
1944            "/repo/.cortexkit/aft.jsonc uses retired keys (hoist_builtin_tools, search_index); AFT applied their current equivalents"
1945        ));
1946        assert!(project.contains("npx @cortexkit/aft doctor --fix"));
1947        let migrated = user_config_migrated_notice("/u/aft.jsonc", "/u/aft.jsonc.bak-1", &out);
1948        assert!(migrated.contains("/u/aft.jsonc.bak-1"));
1949        let (_, out) = translate(json!({"enabled": false}));
1950        assert!(
1951            user_config_not_migrated_notice("/u/aft.jsonc", "read-only", &out)
1952                .ends_with(RETIRED_ENABLED_FALSE_INDEXES_NOTE)
1953        );
1954    }
1955
1956    #[test]
1957    fn retired_hang_threshold_is_dropped_and_the_notice_says_it_does_nothing() {
1958        let (value, out) = translate(json!({
1959            "bridge": {"hang_threshold": 3, "request_timeout_ms": 45000},
1960            "harnesses": {"pi": {"bridge": {"hang_threshold": 5}}}
1961        }));
1962        assert_eq!(
1963            value,
1964            json!({"bridge": {"request_timeout_ms": 45000}, "harnesses": {"pi": {}}})
1965        );
1966        assert!(out.legacy_input);
1967        assert_eq!(
1968            out.retired_keys,
1969            vec![
1970                "bridge.hang_threshold",
1971                "harnesses.pi.bridge.hang_threshold"
1972            ]
1973        );
1974        // Nothing is applied for a key that no longer does anything, so a
1975        // file whose only retired keys are such keys gets just their sentence.
1976        for notice in [
1977            project_retired_keys_notice("/repo/.cortexkit/aft.jsonc", &out),
1978            user_config_migrated_notice("/u/aft.jsonc", "/u/aft.jsonc.bak-1", &out),
1979            user_config_not_migrated_notice("/u/aft.jsonc", "read-only", &out),
1980        ] {
1981            assert_eq!(notice, RETIRED_HANG_THRESHOLD_NOTE);
1982        }
1983        let (_, out) = translate(json!({
1984            "inspect": {"tier2_soft_deadline_ms": 50, "max_drill_down_items": 20}
1985        }));
1986        assert_eq!(
1987            project_retired_keys_notice("/p", &out),
1988            "inspect.max_drill_down_items never had an effect, so the setting can be removed. inspect.tier2_soft_deadline_ms never had an effect, so the setting can be removed."
1989        );
1990
1991        // Mixed with keys that have equivalents: the generic sentence names
1992        // only those keys, and the no-effect sentence follows.
1993        let (_, out) = translate(json!({
1994            "search_index": false,
1995            "bridge": {"hang_threshold": 3},
1996            "harnesses": {"pi": {"bridge": {"hang_threshold": 5}}}
1997        }));
1998        assert_eq!(
1999            project_retired_keys_notice("/repo/.cortexkit/aft.jsonc", &out),
2000            format!("/repo/.cortexkit/aft.jsonc uses retired keys (search_index); AFT applied their current equivalents, with the same limits a project config has for those keys. Run `npx @cortexkit/aft doctor --fix` to update the file. {RETIRED_HANG_THRESHOLD_NOTE}")
2001        );
2002        assert_eq!(
2003            user_config_migrated_notice("/u/aft.jsonc", "/u/aft.jsonc.bak-1", &out),
2004            format!("AFT updated /u/aft.jsonc: its retired keys (search_index) now use their current equivalents. The previous file is saved as /u/aft.jsonc.bak-1. {RETIRED_HANG_THRESHOLD_NOTE}")
2005        );
2006        assert_eq!(
2007            user_config_not_migrated_notice("/u/aft.jsonc", "read-only", &out),
2008            format!("/u/aft.jsonc uses retired keys (search_index); AFT applied their current equivalents but could not update the file (read-only). Run `npx @cortexkit/aft doctor --fix` to update it. {RETIRED_HANG_THRESHOLD_NOTE}")
2009        );
2010        let (_, out) = translate(json!({"enabled": false, "bridge": {"hang_threshold": 3}}));
2011        assert!(project_retired_keys_notice("/p", &out).ends_with(&format!(
2012            "{RETIRED_ENABLED_FALSE_INDEXES_NOTE} {RETIRED_HANG_THRESHOLD_NOTE}"
2013        )));
2014
2015        // Only the retired leaf goes; an emptied bridge block goes with it.
2016        let (value, _) = translate(json!({"bridge": {"hang_threshold": 2}}));
2017        assert_eq!(value, json!({}));
2018        let (_, out) = translate(json!({"search_index": false}));
2019        assert!(!project_retired_keys_notice("/p", &out).contains("hang_threshold"));
2020    }
2021    #[test]
2022    fn resolved_validation_reports_sorted_paths_and_containers_only() {
2023        assert_eq!(
2024            validate_resolved_config(&json!({})).unwrap_err(),
2025            vec![
2026                "invalid_resolved_config:missing:disabled_tools",
2027                "invalid_resolved_config:missing:indexes"
2028            ]
2029        );
2030        assert_eq!(
2031            validate_resolved_config(&json!({
2032                "disabled_tools": "x",
2033                "indexes": {"trigram": 1, "semantic": true}
2034            }))
2035            .unwrap_err(),
2036            vec![
2037                "invalid_resolved_config:type:disabled_tools",
2038                "invalid_resolved_config:missing:indexes.callgraph",
2039                "invalid_resolved_config:type:indexes.trigram"
2040            ]
2041        );
2042        assert!(validate_resolved_config(&json!({
2043            "disabled_tools": [],
2044            "indexes": {"trigram": true, "semantic": false, "callgraph": true}
2045        }))
2046        .is_ok());
2047    }
2048
2049    #[test]
2050    fn adding_a_no_effect_key_changes_the_notice_identity_and_nothing_else_does() {
2051        let digest = |doc: Value| notice_digest(&notice_projection(doc.as_object()));
2052        let acknowledged = digest(json!({"search_index": false}));
2053        // Nothing a notice depends on changed: same identity, no repeat.
2054        assert_eq!(acknowledged, digest(json!({"search_index": false})));
2055        assert_eq!(
2056            acknowledged,
2057            digest(json!({"search_index": false, "bridge": {"request_timeout_ms": 45000}}))
2058        );
2059        // Adding the retired key, in the base or a harness block, is a new
2060        // identity, so a saved record for the old one cannot hide it.
2061        let added = json!({"search_index": false, "bridge": {"hang_threshold": 3}});
2062        assert_ne!(acknowledged, digest(added.clone()));
2063        assert_ne!(
2064            acknowledged,
2065            digest(
2066                json!({"search_index": false, "harnesses": {"pi": {"bridge": {"hang_threshold": 5}}}})
2067            )
2068        );
2069        // The notice for the new identity names it.
2070        let Value::Object(mut map) = added else {
2071            panic!("object")
2072        };
2073        let out = translate_document(&mut map, DocumentTier::Project);
2074        assert_eq!(
2075            project_retired_keys_notice("/p", &out),
2076            format!("/p uses retired keys (search_index); AFT applied their current equivalents, with the same limits a project config has for those keys. Run `npx @cortexkit/aft doctor --fix` to update the file. {RETIRED_HANG_THRESHOLD_NOTE}")
2077        );
2078    }
2079
2080    #[test]
2081    fn notice_digests_match_the_shared_fixtures() {
2082        let path = std::path::Path::new(crate::test_support::manifest_dir())
2083            .join("../aft/tests/fixtures/feature_config/notice_projection.json");
2084        let fixtures: Value =
2085            serde_json::from_str(&std::fs::read_to_string(path).expect("fixture")).unwrap();
2086        for case in fixtures["cases"].as_array().unwrap() {
2087            let doc = case.get("doc").and_then(Value::as_object);
2088            let projection = notice_projection(doc);
2089            assert_eq!(
2090                notice_digest(&projection),
2091                case["digest"].as_str().unwrap(),
2092                "{}",
2093                case["name"]
2094            );
2095        }
2096    }
2097
2098    #[test]
2099    fn release_parsing_reads_major_and_minor_only() {
2100        assert_eq!(parse_release("0.65.0"), Some((0, 65)));
2101        assert_eq!(parse_release("0.64.12-beta.1"), Some((0, 64)));
2102        assert_eq!(parse_release("1.2"), Some((1, 2)));
2103        assert_eq!(parse_release("latest"), None);
2104        assert_eq!(
2105            running_release(),
2106            parse_release(env!("CARGO_PKG_VERSION")).unwrap()
2107        );
2108    }
2109
2110    #[test]
2111    fn config_test_release_override_is_thread_local_and_restored() {
2112        let actual = running_release();
2113        {
2114            let _outer = override_running_release_for_test((0, 64));
2115            assert_eq!(running_release(), (0, 64));
2116            {
2117                let _inner = override_running_release_for_test((0, 65));
2118                assert_eq!(running_release(), (0, 65));
2119            }
2120            assert_eq!(running_release(), (0, 64));
2121            assert_eq!(std::thread::spawn(running_release).join().unwrap(), actual);
2122        }
2123        assert_eq!(running_release(), actual);
2124    }
2125
2126    /// The idle-checkout rename keeps its existing version-gated policy.
2127    #[test]
2128    fn each_data_layer_key_is_refused_only_from_the_refusing_release() {
2129        assert_eq!(DATA_LAYER_KEYS_REFUSED_FROM, (0, 65));
2130        for path in DATA_LAYER_RETIRED_PATHS {
2131            let (container, leaf) = path.split_once('.').unwrap();
2132            let base = json!({ container: { leaf: 1 } });
2133            let harness = json!({ "harnesses": { "pi": { container: { leaf: 1 } } } });
2134            for doc in [&base, &harness] {
2135                let doc = doc.as_object().unwrap();
2136                assert!(
2137                    removed_config_key_errors_at(doc, (0, 64)).is_empty(),
2138                    "{path}"
2139                );
2140            }
2141            assert_eq!(
2142                removed_config_key_errors_at(base.as_object().unwrap(), (0, 65)),
2143                vec![format!(
2144                    "removed_config_key:{path}; run npx @cortexkit/aft doctor --fix"
2145                )]
2146            );
2147            assert_eq!(
2148                removed_config_key_errors_at(harness.as_object().unwrap(), (0, 65)),
2149                vec![format!(
2150                    "removed_config_key:harnesses.pi.{path}; run npx @cortexkit/aft doctor --fix"
2151                )]
2152            );
2153            assert_eq!(
2154                removed_config_key_errors_at(base.as_object().unwrap(), (1, 0)).len(),
2155                1,
2156                "{path}"
2157            );
2158            for doc in [&base, &harness] {
2159                assert!(removed_errors(doc.as_object().unwrap(), (0, 65), false).is_empty());
2160            }
2161        }
2162    }
2163
2164    #[test]
2165    fn callgraph_chunk_size_config_refuses_user_only_from_067() {
2166        for (doc, prefix) in [
2167            (json!({"callgraph_chunk_size":100}), ""),
2168            (
2169                json!({"harnesses":{"pi":{"callgraph_chunk_size":100}}}),
2170                "harnesses.pi.",
2171            ),
2172        ] {
2173            let map = doc.as_object().unwrap();
2174            assert!(removed_errors(map, (0, 66), true).is_empty());
2175            assert_eq!(removed_errors(map, (0, 67), true), vec![format!("removed_config_key:{prefix}callgraph_chunk_size; run npx @cortexkit/aft doctor --fix")]);
2176            assert!(removed_errors(map, (0, 67), false).is_empty());
2177            let mut translated = map.clone();
2178            let out = translate_document(&mut translated, DocumentTier::Project);
2179            assert!(out.legacy_input);
2180            assert!(!serde_json::to_string(&translated)
2181                .unwrap()
2182                .contains("callgraph_chunk_size"));
2183            assert_eq!(
2184                project_retired_keys_notice("/project/aft.jsonc", &out),
2185                CALLGRAPH_CHUNK_NOTE
2186            );
2187        }
2188    }
2189
2190    #[test]
2191    fn removed_data_layer_keys_refuse_only_user_files_including_harness_blocks() {
2192        for path in REMOVED_DATA_LAYER_PATHS {
2193            let (container, leaf) = path.split_once('.').unwrap();
2194            for (doc, prefix) in [
2195                (json!({container: {leaf: false}}), ""),
2196                (
2197                    json!({"harnesses": {"pi": {container: {leaf: false}}}}),
2198                    "harnesses.pi.",
2199                ),
2200            ] {
2201                let map = doc.as_object().unwrap();
2202                assert_eq!(
2203                    removed_errors(map, (0, 65), true),
2204                    vec![format!(
2205                        "removed_config_key:{prefix}{path}; run npx @cortexkit/aft doctor --fix"
2206                    )]
2207                );
2208                assert!(removed_errors(map, (0, 65), false).is_empty(), "{path}");
2209            }
2210        }
2211        assert!(removed_errors(
2212            json!({"inspect": {"tier2_idle_minutes": 5}})
2213                .as_object()
2214                .unwrap(),
2215            (0, 65),
2216            true
2217        )
2218        .is_empty());
2219    }
2220
2221    /// `views.idle_checkout_hours` moves to `idle.checkout_hours`, clamped to
2222    /// its range, unless that is already set; it is listed as a retired key
2223    /// and so triggers the user file's automatic rewrite.
2224    #[test]
2225    fn retired_views_idle_checkout_hours_translates_like_doctor_fix() {
2226        let (value, out) = translate(json!({
2227            "views": {"idle_checkout_hours": 48},
2228            "idle": {"root_ttl_minutes": 20},
2229            "harnesses": {"pi": {"views": {"idle_checkout_hours": 0, "enabled": true}}}
2230        }));
2231        assert_eq!(
2232            value,
2233            json!({
2234                "idle": {"root_ttl_minutes": 20, "checkout_hours": 48},
2235                "harnesses": {"pi": {"idle": {"checkout_hours": 1}}}
2236            })
2237        );
2238        assert!(out.legacy_input);
2239        assert_eq!(
2240            out.retired_keys,
2241            vec![
2242                "harnesses.pi.views.enabled",
2243                "harnesses.pi.views.idle_checkout_hours",
2244                "views.idle_checkout_hours"
2245            ]
2246        );
2247
2248        for (raw, hours) in [
2249            (json!(9000), 8760),
2250            (json!(12.0), 12),
2251            (json!(12.5), 168),
2252            (json!("never"), 168),
2253        ] {
2254            assert_eq!(retired_idle_checkout_hours(&raw), hours, "{raw}");
2255        }
2256
2257        let (value, out) = translate(json!({
2258            "views": {"idle_checkout_hours": 2},
2259            "idle": {"checkout_hours": 5}
2260        }));
2261        assert_eq!(value, json!({"idle": {"checkout_hours": 5}}));
2262        assert_eq!(out.warnings[0].code, "superseded_legacy_config");
2263        assert_eq!(
2264            out.warnings[0].message,
2265            "views.idle_checkout_hours is ignored because idle.checkout_hours is set"
2266        );
2267    }
2268
2269    /// Project translation removes the obsolete settings before strict parsing.
2270    #[test]
2271    fn removed_data_layer_keys_are_dropped_and_listed_as_retired() {
2272        let (value, out) = translate(json!({
2273            "views": {"enabled": true, "callgraph_copies": 2},
2274            "worktree": {"ram_overlay": false},
2275            "harnesses": {"opencode": {"worktree": {"ram_overlay": true}}}
2276        }));
2277        assert_eq!(value, json!({"harnesses": {"opencode": {}}}));
2278        assert!(out.legacy_input);
2279        assert_eq!(
2280            out.retired_keys,
2281            vec![
2282                "harnesses.opencode.worktree.ram_overlay",
2283                "views.callgraph_copies",
2284                "views.enabled",
2285                "worktree.ram_overlay"
2286            ]
2287        );
2288    }
2289
2290    #[test]
2291    fn data_layer_project_notices_reuse_only_existing_no_effect_sentences() {
2292        let (_, removed) = translate(json!({
2293            "views": {"enabled": true, "callgraph_copies": 2},
2294            "worktree": {"ram_overlay": false}
2295        }));
2296        assert_eq!(project_retired_keys_notice("/p", &removed),
2297            "views.callgraph_copies is gone because no checkout borrows another checkout's call graph any more. views.enabled is gone because AFT now keeps one index store per repository and always uses it. worktree.ram_overlay is gone because every worktree now has its own index state, so there is no borrowed index to patch in memory.");
2298        let (_, one) = translate(json!({"harnesses": {"pi": {"worktree": {"ram_overlay": true}}}}));
2299        assert_eq!(
2300            project_retired_keys_notice("/p", &one),
2301            REMOVED_DATA_LAYER_NOTES[2].1
2302        );
2303        assert_eq!(
2304            project_retired_keys_notice("/p", &DocumentTranslation::default()),
2305            ""
2306        );
2307        let (_, both) = translate(json!({"views": {"idle_checkout_hours": 24, "enabled": true}}));
2308        assert_eq!(project_retired_keys_notice("/p", &both),
2309            format!("/p uses retired keys (views.idle_checkout_hours); AFT applied their current equivalents, with the same limits a project config has for those keys. Run `npx @cortexkit/aft doctor --fix` to update the file. {} {}", retired_idle_checkout_hours_note(), REMOVED_DATA_LAYER_NOTES[1].1));
2310    }
2311
2312    /// Adding a data-layer key to a file whose notice was acknowledged is a
2313    /// new notice identity, so the new notice is not hidden.
2314    #[test]
2315    fn adding_a_data_layer_key_changes_the_notice_identity() {
2316        let digest = |doc: Value| notice_digest(&notice_projection(doc.as_object()));
2317        let acknowledged = digest(json!({"search_index": false}));
2318        for path in DATA_LAYER_RETIRED_PATHS {
2319            let (container, leaf) = path.split_once('.').unwrap();
2320            assert_ne!(
2321                acknowledged,
2322                digest(json!({"search_index": false, container: { leaf: 1 }})),
2323                "{path}"
2324            );
2325        }
2326    }
2327}