1use std::collections::BTreeSet;
27
28use serde_json::{Map, Value};
29
30pub(crate) mod settings_shape;
31use sha2::{Digest, Sha256};
32
33pub 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
62pub const HOST_TOOL_NAMES: [&str; 7] = [
64 "apply_patch",
65 "bash",
66 "edit",
67 "glob",
68 "grep",
69 "read",
70 "write",
71];
72
73pub const DEFAULT_DISABLED_TOOLS: [&str; 2] = ["aft_delete", "aft_move"];
76
77pub 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
89pub const BASH_GATE_DISABLES: [&str; 5] = [
92 "bash",
93 "bash_kill",
94 "bash_status",
95 "bash_watch",
96 "bash_write",
97];
98
99pub const MIGRATION_POLICY_ID: &str = "feature-config-v1";
101pub 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
109pub const REMOVED_DATA_LAYER_PATHS: [&str; 3] = [
113 "views.callgraph_copies",
114 "views.enabled",
115 "worktree.ram_overlay",
116];
117
118pub const RETIRED_IDLE_CHECKOUT_HOURS: (&str, &str) =
122 ("views.idle_checkout_hours", "idle.checkout_hours");
123
124pub 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
134pub const DATA_LAYER_RETIRED_PATHS: [&str; 1] = ["views.idle_checkout_hours"];
137
138fn 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
147pub 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#[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
182fn refused_from_version() -> String {
184 let (major, minor) = DATA_LAYER_KEYS_REFUSED_FROM;
185 format!("{major}.{minor}.0")
186}
187
188pub fn removed_config_key_errors(map: &Map<String, Value>) -> Vec<String> {
190 removed_config_key_errors_at(map, running_release())
191}
192
193pub 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
207pub 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
283pub 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
316fn 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
336pub 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
355pub 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
367pub const REMOVED_NO_EFFECT_PATHS: [(&str, &str); 2] = [
376 ("bridge.hang_threshold", ""),
377 ("inspect.tier2_idle_minutes", ""),
378];
379
380pub 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
384pub 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
396pub fn is_project_protected_tool(name: &str) -> bool {
398 name == "aft_safety" || HOST_TOOL_NAMES.contains(&name)
399}
400
401pub fn is_known_tool(name: &str) -> bool {
403 CANONICAL_TOOLS.contains(&name)
404}
405
406pub 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
414pub 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#[derive(Debug, Clone, PartialEq, Eq)]
434pub struct TranslationWarning {
435 pub code: &'static str,
436 pub key: String,
437 pub message: String,
438}
439
440#[derive(Debug, Clone, Default, PartialEq, Eq)]
442pub struct DocumentTranslation {
443 pub warnings: Vec<TranslationWarning>,
444 pub legacy_input: bool,
446 pub retired_keys: Vec<String>,
450}
451
452fn 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
480fn 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
499fn 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
570fn 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
581const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
584
585fn 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
599pub 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
612fn 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
650fn 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
662pub 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
675fn 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
718pub 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
724fn 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 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
839fn translate_block(
845 map: &mut Map<String, Value>,
846 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 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 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1102pub enum DocumentTier {
1103 User,
1104 Project,
1105}
1106
1107pub 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
1148fn translate_runon_enabled(
1152 map: &mut Map<String, Value>,
1153 tier: DocumentTier,
1154 prefix: &str,
1155 out: &mut DocumentTranslation,
1156) {
1157 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
1176fn 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
1184pub 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
1204fn 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
1217fn 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
1225pub 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
1243pub 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
1253fn 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(¬e) {
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
1301pub 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
1312pub 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
1327pub 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
1341pub 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
1355pub fn unknown_disabled_tools(disabled: &[String]) -> Vec<String> {
1357 normalize_tool_list(disabled.iter().filter(|name| !is_known_tool(name)).cloned())
1358}
1359
1360pub 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
1400fn 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 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 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
1548pub 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
1573pub 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
1604pub 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 #[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 #[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 #[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 #[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 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 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 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 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(¬ice_projection(doc.as_object()));
2052 let acknowledged = digest(json!({"search_index": false}));
2053 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 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 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 #[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 #[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 #[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 #[test]
2315 fn adding_a_data_layer_key_changes_the_notice_identity() {
2316 let digest = |doc: Value| notice_digest(¬ice_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}