use super::*;
use crate::config_resolve::{resolve_config_for_harness, ConfigTier};
use crate::harness::Harness;
use serde_json::json;
#[test]
fn sandbox_profile_cutover_matches_doctor_and_preserves_explicit_roles() {
for (enabled, worker, head) in [(true, "strict", "strict"), (false, "relaxed", "off")] {
let source = format!("{{\n// operator choice\n\"sandbox\":{{\"enabled\":{enabled},}},\n}}");
let migrated = migrate_config_text(&source, FixTier::User).unwrap();
assert!(migrated.changed);
assert!(migrated.text.contains("// operator choice"));
let value: Value =
serde_json::from_str(&crate::jsonc::strip_jsonc(&migrated.text)).unwrap();
assert_eq!(
value["sandbox"]["profile"],
json!({"worker":worker,"head":head})
);
assert!(value["sandbox"].get("enabled").is_none());
assert!(
!migrate_config_text(&migrated.text, FixTier::User)
.unwrap()
.changed
);
let mut translated: Map<String, Value> =
serde_json::from_str(&crate::jsonc::strip_jsonc(&source)).unwrap();
feature_config::translate_document(&mut translated, feature_config::DocumentTier::User);
let before = resolve_config_for_harness(
&[ConfigTier {
tier: "user".into(),
source: "user".into(),
doc: Value::Object(translated).to_string(),
}],
None,
);
assert_eq!(
serde_json::to_value(before.config.sandbox.profile).unwrap(),
value["sandbox"]["profile"]
);
}
let migrated = migrate_config_text(r#"{"sandbox":{"enabled":true,"profile":{"head":"off"}},"harnesses":{"pi":{"sandbox":{"enabled":false,"profile":{"worker":"strict"}}}}}"#, FixTier::User).unwrap();
let value: Value = serde_json::from_str(&migrated.text).unwrap();
assert_eq!(
value["sandbox"]["profile"],
json!({"worker":"strict","head":"off"})
);
assert_eq!(
value["harnesses"]["pi"]["sandbox"]["profile"],
json!({"worker":"strict","head":"off"})
);
}
#[test]
fn inspect_cleanup_doctor_maps_idle_and_drops_inert_keys() {
for (old, expected) in [(1, 5), (10, 10), (2000, 1440)] {
let doc = json!({"idle":{"root_ttl_minutes":20,"lsp_ttl_minutes":old},"inspect":{"tier2_soft_deadline_ms":50,"max_drill_down_items":20,"enabled":false},"harnesses":{"pi":{"idle":{"lsp_ttl_minutes":old}}}}).to_string();
let migrated = migrate_config_text(&doc, FixTier::User).unwrap();
assert!(migrated.changed);
let value: Value =
serde_json::from_str(&crate::jsonc::strip_jsonc(&migrated.text)).unwrap();
assert_eq!(value["lsp"]["idle_minutes"], expected);
assert_eq!(value["idle"], json!({"root_ttl_minutes":20}));
assert_eq!(value["inspect"], json!({"enabled":false}));
assert_eq!(value["harnesses"]["pi"]["lsp"]["idle_minutes"], expected);
assert!(
!migrate_config_text(&migrated.text, FixTier::User)
.unwrap()
.changed
);
}
let migrated = migrate_config_text(
r#"{"idle":{"lsp_ttl_minutes":10},"lsp":{"idle_minutes":"never"}}"#,
FixTier::User,
)
.unwrap();
let value: Value = serde_json::from_str(&migrated.text).unwrap();
assert_eq!(
value["lsp"],
json!({"idle_shutdown": false}),
"the old canonical `never` beats the older TTL alias"
);
let migrated =
migrate_config_text(r#"{"idle":{"lsp_ttl_minutes":12.0}}"#, FixTier::User).unwrap();
let value: Value = serde_json::from_str(&migrated.text).unwrap();
assert_eq!(value["lsp"]["idle_minutes"], 12);
}
#[test]
fn doctor_fix_removes_retired_hang_threshold() {
let doc = "{\n // bridge tuning\n \"bridge\": {\n \"request_timeout_ms\": 45000,\n \"hang_threshold\": 3\n },\n \"harnesses\": {\"pi\": {\"bridge\": {\"hang_threshold\": 5}, \"edit_mode\": \"hashline\"}}\n}\n";
for tier in [FixTier::User, FixTier::Project] {
let migration = assert_fix_preserves_intent(doc, tier);
assert!(
migration.text.contains("// bridge tuning"),
"{}",
migration.text
);
let value: Value =
serde_json::from_str(&crate::jsonc::strip_jsonc(&migration.text)).unwrap();
assert_eq!(value["bridge"], json!({"request_timeout_ms": 45000}));
assert_eq!(value["harnesses"]["pi"], json!({"edit_mode": "hashline"}));
assert!(!migrate_config_text(&migration.text, tier).unwrap().changed);
}
let migration =
migrate_config_text(r#"{"bridge":{"hang_threshold":2}}"#, FixTier::User).unwrap();
assert!(migration.changed);
assert_eq!(
serde_json::from_str::<Value>(&migration.text).unwrap(),
json!({})
);
}
fn resolved(doc: &str, tier: &str, harness: Option<&Harness>) -> Value {
let mut translated: Map<String, Value> =
serde_json::from_str(&crate::jsonc::strip_jsonc(doc)).unwrap();
let document_tier = if tier == "user" {
feature_config::DocumentTier::User
} else {
feature_config::DocumentTier::Project
};
feature_config::translate_document(&mut translated, document_tier);
let doc = Value::Object(translated).to_string();
let mut tiers = Vec::new();
if tier == "project" {
tiers.push(ConfigTier {
tier: "user".to_string(),
source: "user".to_string(),
doc: "{}".to_string(),
});
}
tiers.push(ConfigTier {
tier: tier.to_string(),
source: tier.to_string(),
doc: doc.to_string(),
});
let result = resolve_config_for_harness(&tiers, harness);
assert!(result.errors.is_empty(), "{doc}: {:?}", result.errors);
let config = result.config;
json!({
"disabled_tools": config.disabled_tools,
"indexes": serde_json::to_value(config.indexes).unwrap(),
"github": serde_json::to_value(&config.github).unwrap(),
"backup": config.backup.enabled,
"bash": config.bash.enabled,
"bash_features": [config.experimental_bash_rewrite, config.experimental_bash_compress, config.experimental_bash_background],
"lsp_ty": config.experimental_lsp_ty,
})
}
fn assert_fix_preserves_intent(doc: &str, tier: FixTier) -> Migration {
let tier_name = if tier == FixTier::User {
"user"
} else {
"project"
};
let migration = migrate_config_text(doc, tier).unwrap();
assert!(migration.changed, "{doc} needed migration");
for harness in [None, Some(Harness::Opencode), Some(Harness::Pi)] {
let before = resolved(doc, tier_name, harness.as_ref());
let after = resolved(&migration.text, tier_name, harness.as_ref());
assert_eq!(before, after, "{doc}\n=>\n{}", migration.text);
}
let value: Value = serde_json::from_str(&crate::jsonc::strip_jsonc(&migration.text)).unwrap();
let mut fixed = value.as_object().unwrap().clone();
let document_tier = if tier == FixTier::User {
feature_config::DocumentTier::User
} else {
feature_config::DocumentTier::Project
};
let check = feature_config::translate_document(&mut fixed, document_tier);
assert!(!check.legacy_input, "{:?}", check.retired_keys);
migration
}
#[test]
fn legacy_registration_and_index_keys_become_canonical() {
for doc in [
r#"{"tool_surface": "recommended"}"#,
r#"{"tool_surface": "all"}"#,
r#"{"tool_surface": "minimal", "disabled_tools": []}"#,
r#"{"hoist_builtin_tools": false}"#,
r#"{"hoist_builtin_tools": false, "bash": false, "backup": {"enabled": false}}"#,
r#"{"enabled": false}"#,
r#"{"disabled_tools": ["aft_glob", "aft_bash", "aft_zoom"]}"#,
r#"{"search_index": false, "experimental_semantic_search": false, "callgraph_store": true}"#,
r#"{"semantic_search": true, "experimental_semantic_search": false, "indexes": {"trigram": false}}"#,
r#"{"github": {"enabled": false, "write": true}}"#,
r#"{"github": {"enabled": true}}"#,
r#"{"harnesses": {"pi": {"tool_surface": "minimal", "search_index": false}, "opencode": {"disabled_tools": ["aft_read"]}}}"#,
] {
let migration = assert_fix_preserves_intent(doc, FixTier::User);
for (retired, _) in RETIRED_PATHS {
let value: Value = serde_json::from_str(&migration.text).unwrap();
let pointer = format!("/{}", retired.replace('.', "/"));
assert!(
value.pointer(&pointer).is_none(),
"{retired} left in {}",
migration.text
);
}
}
}
#[test]
fn an_empty_generated_base_list_is_persisted() {
let migration = assert_fix_preserves_intent(r#"{"tool_surface": "all"}"#, FixTier::User);
let value: Value = serde_json::from_str(&migration.text).unwrap();
assert_eq!(value, json!({"disabled_tools": []}));
}
#[test]
fn comments_and_unrelated_keys_survive_a_fix() {
let doc = "{\n // pick the fast path\n \"edit_mode\": \"hashline\",\n /* old */\n \"search_index\": false,\n \"harnesses\": {\n // pi only\n \"pi\": {\"hoist_builtin_tools\": false}\n }\n}\n";
let migration = assert_fix_preserves_intent(doc, FixTier::User);
for kept in [
"// pick the fast path",
"/* old */",
"// pi only",
"\"edit_mode\": \"hashline\"",
] {
assert!(
migration.text.contains(kept),
"{kept} missing from {}",
migration.text
);
}
}
#[test]
fn files_without_legacy_input_are_left_byte_identical() {
for doc in [
"{\n // nothing to do\n \"disabled_tools\": [\"aft_zoom\"],\n \"indexes\": {\"semantic\": false}\n}\n",
"{}",
r#"{"gh_shim": {"binary_path": "/opt/aft"}}"#,
r#"{"backup": {"enabled": false}}"#,
r#"{"bash": {"enabled": false}, "inspect": {"enabled": false}}"#,
] {
let migration = migrate_config_text(doc, FixTier::User).unwrap();
assert!(!migration.changed, "{doc}");
assert_eq!(migration.text, doc);
}
}
#[test]
fn retired_github_aliases_are_repaired() {
let migration = migrate_config_text(
r#"{"gh_read": {"enabled": true}, "gh_shim": {"enabled": false, "binary_path": "/opt/aft"}}"#,
FixTier::User,
)
.unwrap();
let value: Value = serde_json::from_str(&migration.text).unwrap();
assert_eq!(
value,
json!({"gh_shim": {"binary_path": "/opt/aft"}, "github": {"read": true, "shim": false}})
);
let after = resolved(&migration.text, "user", None);
assert_eq!(
after["github"],
json!({"shim": false, "read": true, "write": false})
);
let migration = migrate_config_text(
r#"{"github": {"read": false}, "gh_read": {"enabled": true}, "gh_shim": {"enabled": true}}"#,
FixTier::User,
)
.unwrap();
let value: Value = serde_json::from_str(&migration.text).unwrap();
assert_eq!(value, json!({"github": {"read": false, "shim": true}}));
assert!(migration
.notes
.iter()
.any(|note| note.contains("gh_read.enabled=true ignored")));
let migration = migrate_config_text(
r#"{"github": {"enabled": false}, "gh_shim": {"enabled": true}}"#,
FixTier::User,
)
.unwrap();
let value: Value = serde_json::from_str(&migration.text).unwrap();
assert_eq!(
value,
json!({"github": {"read": false, "write": false, "shim": false}})
);
assert!(migration
.notes
.iter()
.any(|note| note.contains("gh_shim.enabled=true ignored")));
}
#[test]
fn project_fixes_never_materialize_protected_disables() {
let migration = assert_fix_preserves_intent(r#"{"enabled": false}"#, FixTier::Project);
let value: Value = serde_json::from_str(&migration.text).unwrap();
let list: Vec<&str> = value["disabled_tools"]
.as_array()
.unwrap()
.iter()
.filter_map(Value::as_str)
.collect();
for protected in feature_config::HOST_TOOL_NAMES
.iter()
.chain(["aft_safety"].iter())
{
assert!(!list.contains(protected), "{protected}");
assert!(migration
.notes
.iter()
.any(|note| note.contains(&format!("disable {protected};"))));
}
assert!(list.contains(&"aft_zoom"));
let migration =
assert_fix_preserves_intent(r#"{"hoist_builtin_tools": false}"#, FixTier::Project);
let value: Value = serde_json::from_str(&migration.text).unwrap();
assert_eq!(value, json!({"disabled_tools": []}));
}
#[test]
fn project_fixes_never_materialize_the_default_disables() {
for (doc, want) in [
(r#"{"hoist_builtin_tools": false}"#, json!([])),
(
r#"{"hoist_builtin_tools": false, "bash": false}"#,
json!([]),
),
(
r#"{"search_index": false, "inspect": {"enabled": false}}"#,
Value::Null,
),
] {
let migration = migrate_config_text(doc, FixTier::Project).unwrap();
let value: Value = serde_json::from_str(&migration.text).unwrap();
assert_eq!(value["disabled_tools"], want, "{doc}");
for text in [migration.text.as_str()] {
let tiers = [
ConfigTier {
tier: "user".to_string(),
source: "user".to_string(),
doc: r#"{"disabled_tools": []}"#.to_string(),
},
ConfigTier {
tier: "project".to_string(),
source: "project".to_string(),
doc: text.to_string(),
},
];
let result = resolve_config_for_harness(&tiers, None);
assert!(result.errors.is_empty());
for kept in ["aft_move", "aft_delete"] {
assert!(
!result.config.disabled_tools.iter().any(|name| name == kept),
"{text}: {kept} must stay registered"
);
}
}
}
}
#[test]
fn a_multi_file_run_keeps_successful_repairs_when_another_file_fails() {
let dir = tempfile::tempdir().unwrap();
let good = dir.path().join("user.jsonc");
let bad = dir.path().join("project.jsonc");
std::fs::write(&good, r#"{"search_index": false}"#).unwrap();
std::fs::write(&bad, r#"{"search_index": false"#).unwrap();
let outcomes = fix_files(&[
(good.clone(), FixTier::User),
(bad.clone(), FixTier::Project),
]);
assert_eq!(outcomes[0].status, "rewritten");
assert_eq!(outcomes[1].status, "failed");
let fixed: Value = serde_json::from_str(&std::fs::read_to_string(&good).unwrap()).unwrap();
assert_eq!(fixed, json!({"indexes": {"trigram": false}}));
assert_eq!(
std::fs::read_to_string(&bad).unwrap(),
r#"{"search_index": false"#
);
}
#[test]
fn explicit_fix_repairs_legacy_project_file_in_place_without_relocating() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(".pi/aft.jsonc");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(
&path,
"{\n // committed settings\n \"experimental_bash_compress\": false\n}\n",
)
.unwrap();
let targets = fix_targets(None, dir.path());
assert_eq!(targets, vec![(path.clone(), FixTier::Project)]);
let outcomes = fix_files(&targets);
assert_eq!(outcomes[0].status, "rewritten");
assert!(outcomes[0].error.is_none());
assert!(std::fs::read_to_string(&path)
.unwrap()
.contains("// committed settings"));
assert!(!dir.path().join(".cortexkit/aft.jsonc").exists());
}
#[test]
fn without_a_project_file_only_the_user_file_is_a_target() {
let dir = tempfile::tempdir().unwrap();
let user = dir.path().join("aft.jsonc");
std::fs::write(&user, "{}").unwrap();
let cwd = dir.path().join("elsewhere");
std::fs::create_dir_all(&cwd).unwrap();
assert_eq!(
fix_targets(Some(&user), &cwd),
vec![(user.clone(), FixTier::User)]
);
std::fs::create_dir_all(cwd.join(".cortexkit")).unwrap();
std::fs::write(cwd.join(".cortexkit/aft.jsonc"), "{}").unwrap();
assert_eq!(fix_targets(None, &cwd).len(), 1);
assert_eq!(fix_targets(None, &cwd)[0].1, FixTier::Project);
}
#[test]
fn experimental_keys_doctor_preserves_opt_in_defaults_and_precedence() {
for tier in [FixTier::User, FixTier::Project] {
for (input, expected) in [
(
json!({"experimental_lsp_ty": true}),
json!({"experimental": {"lsp_ty": true}}),
),
(
json!({"experimental_bash_rewrite": true}),
json!({"bash": {"rewrite": true, "compress": false, "background": false}}),
),
(
json!({"experimental_bash_compress": true}),
json!({"bash": {"rewrite": false, "compress": true, "background": false}}),
),
(
json!({"experimental_bash_background": true}),
json!({"bash": {"rewrite": false, "compress": false, "background": true}}),
),
(
json!({"experimental_bash_rewrite": true, "experimental": {"bash": {"rewrite": false, "compress": true}}}),
json!({"bash": {"rewrite": false, "compress": true, "background": false}}),
),
(
json!({"experimental_bash_rewrite": true, "bash": {"compress": true}}),
json!({"bash": {"compress": true}}),
),
(
json!({"experimental_lsp_ty": true, "experimental": {"lsp_ty": false}}),
json!({"experimental": {"lsp_ty": false}}),
),
(
json!({"experimental": {"bash": {"rewrite": true, "long_running_reminder_enabled": false, "long_running_reminder_interval_ms": 1000}}}),
json!({"bash": {"rewrite": true, "compress": false, "background": false, "long_running_reminder_enabled": false, "long_running_reminder_interval_ms": 1000}}),
),
(json!({"experimental": {"bash": true}}), json!({})),
(
json!({"harnesses": {"pi": {"experimental_bash_background": true}, "opencode": {"experimental_lsp_ty": true}}}),
json!({"harnesses": {"pi": {"bash": {"rewrite": false, "compress": false, "background": true}}, "opencode": {"experimental": {"lsp_ty": true}}}}),
),
] {
let migration = assert_fix_preserves_intent(&input.to_string(), tier);
let value: Value = serde_json::from_str(&migration.text).unwrap();
assert_eq!(value, expected, "{input}");
assert!(!migrate_config_text(&migration.text, tier).unwrap().changed);
}
let tuning_only = r#"{"experimental":{"bash":{"long_running_reminder_enabled":false}}}"#;
let migration = assert_fix_preserves_intent(tuning_only, tier);
assert_eq!(
serde_json::from_str::<Value>(&migration.text).unwrap(),
json!({"bash": {"long_running_reminder_enabled": false}})
);
}
}
#[test]
fn experimental_keys_auto_migrate_user_once_via_doctor_mapping() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("aft.jsonc");
let input = "{\n // keep the opt-in settings\n \"experimental_lsp_ty\": true,\n \"experimental_bash_rewrite\": true,\n \"experimental_bash_compress\": false,\n \"experimental_bash_background\": true,\n \"harnesses\": {\"pi\": {\"experimental_bash_background\": false}}\n}\n";
std::fs::write(&path, input).unwrap();
let outcome = auto_migrate_user_config(&path).expect("experimental keys need migration");
let UserConfigMigration::Migrated { backup, notice, .. } = outcome else {
panic!("expected a rewrite, got {outcome:?}");
};
assert_eq!(std::fs::read_to_string(&backup).unwrap(), input);
let text = std::fs::read_to_string(&path).unwrap();
assert!(text.contains("// keep the opt-in settings"));
let value: Value = serde_json::from_str(&crate::jsonc::strip_jsonc(&text)).unwrap();
assert_eq!(
value["bash"],
json!({"rewrite": true, "compress": false, "background": true})
);
assert_eq!(value["experimental"], json!({"lsp_ty": true}));
assert_eq!(
value["harnesses"]["pi"]["bash"],
json!({"rewrite": false, "compress": false, "background": false})
);
assert!(!value
.as_object()
.unwrap()
.contains_key("experimental_lsp_ty"));
assert_eq!(
text,
migrate_config_text(input, FixTier::User).unwrap().text
);
assert!(notice.contains("experimental_lsp_ty"));
assert!(notice.contains("experimental_bash_rewrite"));
assert_eq!(auto_migrate_user_config(&path), None);
assert_eq!(std::fs::read_to_string(&path).unwrap(), text);
assert_eq!(backups(dir.path()).len(), 1);
}
const RETIRED_USER_FILE: &str =
"{\n // my settings\n \"search_index\": false,\n \"hoist_builtin_tools\": false\n}\n";
const TRANSLATED_USER_FILE: &str =
"{\n // my settings\n \"views\": {\"idle_checkout_hours\": 72}\n}\n";
fn auto_migrate_user_config(path: &Path) -> Option<UserConfigMigration> {
with_backup_dir_for_test(path.parent().unwrap(), || {
super::auto_migrate_user_config(path)
})
}
fn auto_migrate_user_config_with_writer(
path: &Path,
write: impl FnOnce(&Path, &str, Permissions, bool) -> io::Result<()>,
) -> Option<UserConfigMigration> {
auto_migrate_user_config_with_reader(
path,
path,
|| path.parent().unwrap().to_path_buf(),
write,
|path| fs::read_to_string(path),
|_| unreachable!("in-place writes do not remove a legacy path"),
)
}
#[test]
fn failed_user_config_migration_at_0_65_leaves_idle_key_for_refusal() {
let _release = feature_config::override_running_release_for_test((0, 65));
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("aft.jsonc");
std::fs::write(&path, TRANSLATED_USER_FILE).unwrap();
let attempted = std::cell::Cell::new(false);
assert_eq!(
auto_migrate_user_config_with_writer(&path, |_, _, _, _| {
attempted.set(true);
Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"rename denied",
))
}),
None
);
assert!(attempted.get(), "the failed rewrite must reach the writer");
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
TRANSLATED_USER_FILE
);
assert!(backups(dir.path()).is_empty());
let result = resolve_config_for_harness(
&[ConfigTier {
tier: "user".to_string(),
source: path.display().to_string(),
doc: TRANSLATED_USER_FILE.to_string(),
}],
None,
);
assert_eq!(
result.errors,
["removed_config_key:views.idle_checkout_hours; run npx @cortexkit/aft doctor --fix"]
);
}
#[test]
fn config_migration_directory_sync_error_is_before_commit() {
let _release = feature_config::override_running_release_for_test((0, 64));
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("aft.jsonc");
std::fs::write(&path, TRANSLATED_USER_FILE).unwrap();
let outcome =
auto_migrate_user_config_with_writer(&path, |target, contents, permissions, relocating| {
crate::durability::FAIL_DIRECTORY_SYNC
.with(|slot| slot.replace(Some(target.parent().unwrap().to_path_buf())));
publish_conversion(target, contents, permissions, relocating)
})
.expect("reported failure");
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
TRANSLATED_USER_FILE
);
assert!(backups(dir.path()).is_empty());
let UserConfigMigration::NotMigrated { reason, .. } = outcome else {
panic!("a failed sync must leave the settings unchanged: {outcome:?}");
};
assert!(
reason.contains("injected directory sync failure"),
"{reason}"
);
}
#[test]
fn config_migration_post_rename_sync_error_keeps_backup() {
let _release = feature_config::override_running_release_for_test((0, 64));
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("aft.jsonc");
fs::write(&path, TRANSLATED_USER_FILE).unwrap();
let outcome =
auto_migrate_user_config_with_writer(&path, |target, contents, permissions, relocating| {
publish_conversion(target, contents, permissions, relocating)?;
crate::durability::FAIL_DIRECTORY_SYNC
.with(|slot| slot.replace(Some(target.parent().unwrap().to_path_buf())));
Ok(())
})
.expect("reported failure");
let UserConfigMigration::NotMigrated { reason, .. } = outcome else {
panic!("an unsynced replacement must not be reported as migrated: {outcome:?}");
};
assert!(
reason.contains("injected directory sync failure"),
"{reason}"
);
let converted = fs::read_to_string(&path).unwrap();
assert_eq!(
parse_document(&converted).unwrap(),
json!({"idle": {"checkout_hours": 72}})
);
let copies = backups(dir.path());
assert_eq!(copies.len(), 1);
assert_eq!(
fs::read_to_string(&copies[0]).unwrap(),
TRANSLATED_USER_FILE
);
}
#[test]
fn settings_editor_error_discards_successful_prior_edits_without_an_old_copy() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("aft.jsonc");
let data = dir.path().join("data");
let original = "{\n // user settings\n \"bash\": {\"runon_enabled\": false},\n \"remote_exec\": false\n}\n";
fs::write(&file, original).unwrap();
let error = migrate_user_config_text(original).unwrap_err();
assert!(
error.contains("set_member at /remote_exec/enabled"),
"{error}"
);
with_backup_dir_for_test(&data, || super::auto_migrate_user_config(&file));
assert_eq!(fs::read(&file).unwrap(), original.as_bytes());
assert!(!data.exists(), "an editor error must not attempt a backup");
assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
}
#[test]
fn settings_conversion_keeps_comments_order_and_private_old_copy() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("aft.jsonc");
let data = dir.path().join("data");
let original = concat!(
"{\r\n",
" // leave the keys in this order\r\n",
" \"storage\": {\r\n",
" // custom storage\r\n",
" \"cache_dir\": \"~/aft-cache\", // keep this cache comment\r\n",
" },\r\n",
" \"bash\": true, // keep this shell comment\r\n",
" \"format_on_edit\": false,\r\n",
"}\r\n",
);
fs::write(&file, original).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
fs::set_permissions(&file, Permissions::from_mode(0o640)).unwrap();
}
let start = || with_backup_dir_for_test(&data, || super::auto_migrate_user_config(&file));
let Some(UserConfigMigration::Migrated { backup, .. }) = start() else {
panic!("both old settings must migrate");
};
assert_eq!(backup.parent(), Some(data.as_path()));
assert_eq!(fs::read(&backup).unwrap(), original.as_bytes());
assert!(backups(dir.path()).is_empty());
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
let mode = |path: &Path| fs::metadata(path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode(&backup), 0o600);
assert_eq!(mode(&file), 0o640);
}
let converted = fs::read_to_string(&file).unwrap();
let value = parse_document(&converted).unwrap();
assert_eq!(
value["storage"]["cache_dir"],
serde_json::json!({"kind":"dir", "path":"~/aft-cache"})
);
assert_eq!(value["bash"]["enabled"], true);
let mut last = 0;
for part in [
"// leave the keys in this order\r\n",
"\"storage\"",
"// custom storage\r\n",
"\"cache_dir\"",
"// keep this cache comment\r\n",
"\"bash\"",
"// keep this shell comment\r\n",
"\"format_on_edit\"",
] {
let next = converted
.find(part)
.unwrap_or_else(|| panic!("{part:?} missing: {converted}"));
assert!(next > last, "{part:?} out of order: {converted}");
last = next;
}
let modified = fs::metadata(&file).unwrap().modified().unwrap();
assert_eq!(start(), None);
assert_eq!(fs::read_to_string(&file).unwrap(), converted);
assert_eq!(fs::metadata(&file).unwrap().modified().unwrap(), modified);
assert_eq!(backups(&data), [backup]);
}
#[test]
fn migration_pre_rename_error_preserves_original_and_removes_backup() {
let _release = feature_config::override_running_release_for_test((0, 64));
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("aft.jsonc");
std::fs::write(&path, TRANSLATED_USER_FILE).unwrap();
let outcome = auto_migrate_user_config_with_writer(&path, |_, _, _, _| {
Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"rename denied",
))
})
.expect("reported failure");
assert!(matches!(outcome, UserConfigMigration::NotMigrated { .. }));
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
TRANSLATED_USER_FILE
);
assert!(backups(dir.path()).is_empty());
}
fn backups(dir: &Path) -> Vec<PathBuf> {
let mut found: Vec<PathBuf> = std::fs::read_dir(dir)
.unwrap()
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
.filter(|path| path.to_string_lossy().contains(".bak-"))
.collect();
found.sort();
found
}
#[test]
fn auto_migration_rewrites_the_user_file_once_and_keeps_a_backup() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("aft.jsonc");
std::fs::write(&path, RETIRED_USER_FILE).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
}
let outcome = auto_migrate_user_config(&path).expect("migrated");
let UserConfigMigration::Migrated { backup, notice, .. } = &outcome else {
panic!("expected a rewrite, got {outcome:?}");
};
let text = std::fs::read_to_string(&path).unwrap();
assert_eq!(
text,
migrate_config_text(RETIRED_USER_FILE, FixTier::User)
.unwrap()
.text
);
assert!(text.contains("// my settings"), "{text}");
assert!(retired_key_translation(&text).is_none(), "{text}");
assert_eq!(std::fs::read_to_string(backup).unwrap(), RETIRED_USER_FILE);
let canonical = |paths: Vec<std::path::PathBuf>| -> Vec<std::path::PathBuf> {
paths
.into_iter()
.map(|path| std::fs::canonicalize(path).unwrap())
.collect()
};
assert_eq!(
canonical(backups(dir.path())),
canonical(vec![backup.clone()])
);
assert!(
notice.contains("hoist_builtin_tools, search_index"),
"{notice}"
);
assert!(notice.contains(&backup.display().to_string()), "{notice}");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600, "the rewrite keeps the file mode");
}
assert_eq!(
auto_migrate_user_config(&path),
None,
"second run is a no-op"
);
assert_eq!(std::fs::read_to_string(&path).unwrap(), text);
assert_eq!(backups(dir.path()).len(), 1);
assert!(
!dir.path().join(".aft.jsonc.migrate.lock").exists(),
"the lock is released"
);
}
#[test]
fn concurrent_auto_migrations_converge() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("aft.jsonc");
std::fs::write(&path, RETIRED_USER_FILE).unwrap();
let barrier = std::sync::Arc::new(std::sync::Barrier::new(8));
let handles: Vec<_> = (0..8)
.map(|_| {
let path = path.clone();
let barrier = barrier.clone();
std::thread::spawn(move || {
barrier.wait();
auto_migrate_user_config(&path)
})
})
.collect();
let outcomes: Vec<_> = handles
.into_iter()
.map(|handle| handle.join().unwrap())
.collect();
let migrated = outcomes
.iter()
.filter(|outcome| matches!(outcome, Some(UserConfigMigration::Migrated { .. })))
.count();
assert_eq!(migrated, 1, "{outcomes:?}");
assert!(
outcomes
.iter()
.all(|outcome| !matches!(outcome, Some(UserConfigMigration::NotMigrated { .. }))),
"{outcomes:?}"
);
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
migrate_config_text(RETIRED_USER_FILE, FixTier::User)
.unwrap()
.text
);
assert_eq!(backups(dir.path()).len(), 1);
}
#[test]
fn a_read_only_user_file_is_left_alone_with_a_notice() {
let _release = feature_config::override_running_release_for_test((0, 64));
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("aft.jsonc");
std::fs::write(&path, TRANSLATED_USER_FILE).unwrap();
let set_readonly = |readonly: bool| {
let mut permissions = std::fs::metadata(&path).unwrap().permissions();
#[allow(clippy::permissions_set_readonly_false)]
permissions.set_readonly(readonly);
std::fs::set_permissions(&path, permissions).unwrap();
};
set_readonly(true);
let outcome = auto_migrate_user_config(&path).expect("reported");
let UserConfigMigration::NotMigrated { reason, notice, .. } = &outcome else {
panic!("expected no rewrite, got {outcome:?}");
};
assert_eq!(reason, "the file is read-only");
assert!(
notice.contains("applied their current equivalents"),
"{notice}"
);
assert!(notice.contains("doctor --fix"), "{notice}");
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
TRANSLATED_USER_FILE
);
assert!(backups(dir.path()).is_empty());
let load = |doc: &str| {
resolve_config_for_harness(
&[ConfigTier {
tier: "user".to_string(),
source: path.display().to_string(),
doc: doc.to_string(),
}],
None,
)
};
let result = load(TRANSLATED_USER_FILE);
assert!(result.errors.is_empty(), "{:?}", result.errors);
assert_eq!(result.config.idle.checkout_hours, 72);
set_readonly(false);
std::fs::write(&path, RETIRED_USER_FILE).unwrap();
set_readonly(true);
assert_eq!(auto_migrate_user_config(&path), None);
assert_eq!(std::fs::read_to_string(&path).unwrap(), RETIRED_USER_FILE);
assert_eq!(
load(RETIRED_USER_FILE).errors,
[
"removed_config_key:hoist_builtin_tools; run npx @cortexkit/aft doctor --fix",
"removed_config_key:search_index; run npx @cortexkit/aft doctor --fix",
]
);
set_readonly(false);
}
#[test]
fn auto_migration_ignores_current_missing_and_unparsable_files() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("aft.jsonc");
assert_eq!(auto_migrate_user_config(&path), None);
for text in [
"{\n \"indexes\": {\"semantic\": false},\n \"bash\": {\"enabled\": false}\n}\n",
"{ \"search_index\": false",
] {
std::fs::write(&path, text).unwrap();
assert_eq!(auto_migrate_user_config(&path), None, "{text}");
assert_eq!(std::fs::read_to_string(&path).unwrap(), text);
}
assert!(backups(dir.path()).is_empty());
}
#[test]
fn a_held_lock_defers_and_a_stale_lock_is_cleared() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("aft.jsonc");
std::fs::write(&path, RETIRED_USER_FILE).unwrap();
let lock = dir.path().join(".aft.jsonc.migrate.lock");
std::fs::write(&lock, "").unwrap();
assert_eq!(auto_migrate_user_config(&path), None);
assert_eq!(std::fs::read_to_string(&path).unwrap(), RETIRED_USER_FILE);
let old = std::time::SystemTime::now() - std::time::Duration::from_secs(120);
std::fs::File::options()
.write(true)
.open(&lock)
.unwrap()
.set_modified(old)
.unwrap();
assert!(matches!(
auto_migrate_user_config(&path),
Some(UserConfigMigration::Migrated { .. })
));
assert!(!lock.exists());
}
#[cfg(unix)]
#[test]
fn a_symlinked_user_file_is_rewritten_at_its_target() {
let dir = tempfile::tempdir().unwrap();
let real = dir.path().join("dotfiles-aft.jsonc");
std::fs::write(&real, RETIRED_USER_FILE).unwrap();
let link_dir = dir.path().join("config");
std::fs::create_dir_all(&link_dir).unwrap();
let link = link_dir.join("aft.jsonc");
std::os::unix::fs::symlink(&real, &link).unwrap();
assert!(matches!(
auto_migrate_user_config(&link),
Some(UserConfigMigration::Migrated { .. })
));
assert!(std::fs::symlink_metadata(&link)
.unwrap()
.file_type()
.is_symlink());
assert!(retired_key_translation(&std::fs::read_to_string(&real).unwrap()).is_none());
}
#[cfg(debug_assertions)]
#[test]
fn a_debug_build_never_rewrites_a_user_file_in_the_account_config_dir() {
let _release = feature_config::override_running_release_for_test((0, 64));
let fixture = tempfile::tempdir().unwrap();
let config_dir = fixture.path().join("account/.config/cortexkit");
std::fs::create_dir_all(&config_dir).unwrap();
let path = config_dir.join("aft.jsonc");
std::fs::write(&path, TRANSLATED_USER_FILE).unwrap();
let modified = std::fs::metadata(&path).unwrap().modified().unwrap();
let outcome = crate::production_storage::with_test_account(&config_dir, false, || {
auto_migrate_user_config(&path)
})
.expect("reported");
let UserConfigMigration::NotMigrated { reason, notice, .. } = &outcome else {
panic!("expected no rewrite, got {outcome:?}");
};
assert!(reason.contains(crate::production_storage::CODE), "{reason}");
assert!(
reason.contains("AFT_ALLOW_PRODUCTION_MIGRATION=1"),
"{reason}"
);
assert!(
notice.contains("applied their current equivalents"),
"{notice}"
);
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
TRANSLATED_USER_FILE
);
assert_eq!(
std::fs::metadata(&path).unwrap().modified().unwrap(),
modified
);
assert_eq!(
std::fs::read_dir(&config_dir).unwrap().count(),
1,
"no backup, lock or temporary file may be created"
);
let opted_in = crate::production_storage::with_test_account(&config_dir, true, || {
auto_migrate_user_config(&path)
});
assert!(
matches!(opted_in, Some(UserConfigMigration::Migrated { .. })),
"{opted_in:?}"
);
}
#[test]
fn doctor_fix_removes_opencode_prompt_transport_keys() {
for tier in [FixTier::User, FixTier::Project] {
let input = r#"{
// Keep unrelated configuration and comments.
"opencode": {"server_url":"http://127.0.0.1:4096","server_password_env":"PW"},
"harnesses": {"opencode": {"opencode": {"server_url":"http://host"}}},
"format_on_edit": false
}"#;
let migrated = migrate_config_text(input, tier).unwrap();
assert!(migrated.changed);
assert!(!migrated.text.contains("server_url"));
assert!(!migrated.text.contains("server_password_env"));
assert!(migrated.text.contains("Keep unrelated"));
assert!(migrated.text.contains("format_on_edit"));
assert!(!migrate_config_text(&migrated.text, tier).unwrap().changed);
let tier_name = if tier == FixTier::User {
"user"
} else {
"project"
};
let mut tiers = Vec::new();
if tier == FixTier::Project {
tiers.push(ConfigTier {
tier: "user".to_string(),
source: "user".to_string(),
doc: "{}".to_string(),
});
}
tiers.push(ConfigTier {
tier: tier_name.to_string(),
source: tier_name.to_string(),
doc: migrated.text.clone(),
});
let loaded = resolve_config_for_harness(&tiers, Some(&Harness::Opencode));
assert!(
loaded.errors.is_empty(),
"fixed file did not load: {:?}",
loaded.errors
);
}
}
const DATA_LAYER_FILE: &str = "{\n // index settings\n \"views\": {\"enabled\": true, \"callgraph_copies\": 2, \"idle_checkout_hours\": 9000},\n \"worktree\": {\"ram_overlay\": false},\n \"idle\": {\"root_ttl_minutes\": 20},\n \"harnesses\": {\"pi\": {\"views\": {\"idle_checkout_hours\": 12, \"enabled\": false}, \"edit_mode\": \"hashline\"}}\n}\n";
#[test]
fn retired_runon_user_rewrite_preserves_comments_harnesses_and_backup() {
let input = r#"{
// remote preference
"remote_exec": {"enabled": true, "default_demand": "linux"},
"bash": {"runon_enabled": false, "enabled": true},
"harnesses": {
// pi preference
"pi": {"remote_exec": {"enabled": true}, "bash": {"runon_enabled": true}},
"opencode": {"remote_exec": {"enabled": true}, "bash": {"runon_enabled": false}}
}
}"#;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("aft.jsonc");
std::fs::write(&path, input).unwrap();
let outcome = auto_migrate_user_config(&path).unwrap();
let UserConfigMigration::Migrated { notice, backup, .. } = outcome else {
panic!("expected user migration");
};
assert_eq!(std::fs::read_to_string(backup).unwrap(), input);
let text = std::fs::read_to_string(&path).unwrap();
assert!(text.contains("// remote preference"));
assert!(text.contains("// pi preference"));
assert!(!text.contains("runon_enabled"));
let value: Value = serde_json::from_str(&crate::jsonc::strip_jsonc(&text)).unwrap();
assert_eq!(
value["remote_exec"],
json!({"enabled":false,"default_demand":"linux"})
);
assert_eq!(value["bash"], json!({"enabled":true}));
assert_eq!(value["harnesses"]["pi"]["remote_exec"]["enabled"], true);
assert_eq!(
value["harnesses"]["opencode"]["remote_exec"]["enabled"],
false
);
assert!(notice.contains("AFT updated"), "{notice}");
for key in [
"bash.runon_enabled",
"harnesses.pi.bash.runon_enabled",
"harnesses.opencode.bash.runon_enabled",
] {
assert!(notice.contains(key), "{notice}");
}
assert_eq!(auto_migrate_user_config(&path), None);
let current = r#"{"remote_exec":{"enabled":true}}"#;
assert!(!migrate_user_config_text(current).unwrap().changed);
}
#[test]
fn retired_runon_project_fix_only_drops_the_old_gate() {
let migration = migrate_config_text(
r#"{"remote_exec":{"enabled":true},"bash":{"runon_enabled":false}}"#,
FixTier::Project,
)
.unwrap();
assert_eq!(
serde_json::from_str::<Value>(&migration.text).unwrap(),
json!({"remote_exec":{"enabled":true},"bash":{}})
);
}
#[test]
fn doctor_fix_moves_idle_checkout_hours_and_deletes_removed_data_layer_keys() {
for tier in [FixTier::User, FixTier::Project] {
let migration = migrate_config_text(DATA_LAYER_FILE, tier).unwrap();
assert!(migration.changed);
assert!(migration.text.contains("// index settings"));
let value: Value =
serde_json::from_str(&crate::jsonc::strip_jsonc(&migration.text)).unwrap();
assert_eq!(
value,
json!({
"idle": {"root_ttl_minutes": 20, "checkout_hours": 8760},
"harnesses": {"pi": {"edit_mode": "hashline", "idle": {"checkout_hours": 12}}}
}),
"{}",
migration.text
);
assert!(!migrate_config_text(&migration.text, tier).unwrap().changed);
let mut fixed = value.as_object().unwrap().clone();
let check =
feature_config::translate_document(&mut fixed, feature_config::DocumentTier::Project);
assert!(!check.legacy_input, "{:?}", check.retired_keys);
}
let migration = migrate_config_text(
r#"{"views":{"idle_checkout_hours":2},"idle":{"checkout_hours":5}}"#,
FixTier::Project,
)
.unwrap();
assert_eq!(
serde_json::from_str::<Value>(&migration.text).unwrap(),
json!({"idle": {"checkout_hours": 5}})
);
let migration =
migrate_config_text(r#"{"worktree":{"ram_overlay":true}}"#, FixTier::User).unwrap();
assert!(migration.changed);
assert_eq!(
serde_json::from_str::<Value>(&migration.text).unwrap(),
json!({})
);
}
#[test]
fn doctor_fix_deletes_callgraph_chunk_size_from_base_and_harnesses() {
for tier in [FixTier::User, FixTier::Project] {
let migration = migrate_config_text(r#"{"callgraph_chunk_size":100,"harnesses":{"pi":{"callgraph_chunk_size":1,"memory":"lean"}}}"#, tier).unwrap();
assert!(migration.changed);
let value: Value = serde_json::from_str(&migration.text).unwrap();
assert_eq!(value, json!({"harnesses":{"pi":{"memory":"lean"}}}));
assert!(!migrate_config_text(&migration.text, tier).unwrap().changed);
}
}
#[test]
fn automatic_user_rewrite_moves_idle_checkout_hours_but_keeps_removed_keys() {
let _release = feature_config::override_running_release_for_test((0, 64));
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("aft.jsonc");
std::fs::write(&path, DATA_LAYER_FILE).unwrap();
let outcome = auto_migrate_user_config(&path).expect("views.idle_checkout_hours migrates");
let UserConfigMigration::Migrated { notice, .. } = outcome else {
panic!("expected a rewrite, got {outcome:?}");
};
let text = std::fs::read_to_string(&path).unwrap();
let value: Value = serde_json::from_str(&crate::jsonc::strip_jsonc(&text)).unwrap();
assert_eq!(
value,
json!({
"views": {"enabled": true, "callgraph_copies": 2},
"worktree": {"ram_overlay": false},
"idle": {"root_ttl_minutes": 20, "checkout_hours": 8760},
"harnesses": {"pi": {"views": {"enabled": false}, "edit_mode": "hashline", "idle": {"checkout_hours": 12}}}
}),
"{text}"
);
assert!(notice.contains("views.idle_checkout_hours"), "{notice}");
assert!(!notice.contains("views.enabled"), "{notice}");
assert!(!notice.contains("ram_overlay"), "{notice}");
assert_eq!(auto_migrate_user_config(&path), None);
let removed_only = dir.path().join("removed.jsonc");
let input = r#"{"views":{"enabled":true},"worktree":{"ram_overlay":false}}"#;
std::fs::write(&removed_only, input).unwrap();
assert_eq!(auto_migrate_user_config(&removed_only), None);
assert_eq!(std::fs::read_to_string(&removed_only).unwrap(), input);
assert!(backups(dir.path()).len() == 1, "{:?}", backups(dir.path()));
}
#[test]
fn storage_cache_dir_rewrites_legacy_user_values_without_changing_resolution() {
use crate::config_resolve::{resolve_config, ConfigTier};
use serde_json::json;
let temp = tempfile::tempdir().unwrap();
let user = temp.path().join("aft.jsonc");
let home = std::env::var_os("HOME")
.or_else(|| std::env::var_os("USERPROFILE"))
.map(std::path::PathBuf::from)
.unwrap();
let resolve = |doc: &str| {
resolve_config(&[ConfigTier {
tier: "user".into(),
source: user.display().to_string(),
doc: doc.into(),
}])
};
for (legacy, choice, expected_dir, opt_out, replacement) in [
(
"null",
json!({"kind": "main_disk"}),
None,
true,
"storage.cache_dir null → storage.cache_dir main_disk",
),
(
r#""~/aft-cache""#,
json!({"kind": "dir", "path": "~/aft-cache"}),
Some(home.join("aft-cache")),
false,
"storage.cache_dir string → storage.cache_dir dir",
),
] {
let legacy = format!(r#"{{"storage":{{"cache_dir":{legacy}}}}}"#);
std::fs::write(&user, &legacy).unwrap();
let Some(UserConfigMigration::Migrated { backup, notice, .. }) =
auto_migrate_user_config(&user)
else {
panic!("legacy cache choice should be rewritten: {legacy}");
};
assert!(notice.contains(replacement), "{notice}");
assert_eq!(std::fs::read_to_string(backup).unwrap(), legacy);
let rewritten = std::fs::read_to_string(&user).unwrap();
let raw: Value = serde_json::from_str(&rewritten).unwrap();
assert_eq!(raw["storage"]["cache_dir"], choice);
for doc in [&legacy, &rewritten] {
let result = resolve(doc);
assert!(result.errors.is_empty(), "{doc}: {:?}", result.errors);
assert_eq!(result.config.cache_dir, expected_dir);
assert_eq!(result.config.cache_dir_opt_out, opt_out);
assert!(result.config.cache_config_unknown.is_none());
}
assert!(auto_migrate_user_config(&user).is_none());
}
for doc in [
r#"{"storage":{}}"#,
r#"{"storage":{"cache_dir":{"kind":"default"}}}"#,
] {
std::fs::write(&user, doc).unwrap();
assert!(auto_migrate_user_config(&user).is_none());
assert_eq!(std::fs::read_to_string(&user).unwrap(), doc);
let result = resolve(doc);
assert!(result.errors.is_empty());
assert!(result.config.cache_dir.is_none());
assert!(!result.config.cache_dir_opt_out);
}
}
#[test]
fn settings_shapes_rewrite_user_with_backup_and_project_with_notice() {
use serde_json::json;
let temp = tempfile::tempdir().unwrap();
let user = temp.path().join("aft.jsonc");
let legacy = r#"{
// Keep this note.
"bash": false,
"lsp": {"idle_minutes": "never", "servers": {"rust": {"initialization_options": {"checkOnSave": true, "other": null}}}},
"inspect": {"duplicates": {"expected_mirrors": [["src/**", "mirror/**"]]}},
"harnesses": {"pi": {"bash": true}}
}"#;
std::fs::write(&user, legacy).unwrap();
let Some(UserConfigMigration::Migrated { backup, notice, .. }) =
auto_migrate_user_config(&user)
else {
panic!("the user file should be rewritten");
};
assert_eq!(std::fs::read_to_string(backup).unwrap(), legacy);
let migrated = std::fs::read_to_string(&user).unwrap();
assert!(migrated.contains("// Keep this note."));
let migrated: Value = serde_json::from_str(&crate::jsonc::strip_jsonc(&migrated)).unwrap();
assert_eq!(
migrated["bash"],
json!({"enabled": false, "rewrite": false, "compress": false, "background": false})
);
assert_eq!(
migrated["harnesses"]["pi"]["bash"],
json!({"enabled": true,"rewrite": true,"compress": true,"background": true})
);
assert_eq!(migrated["lsp"]["idle_shutdown"], false);
assert!(!migrated["lsp"]
.as_object()
.unwrap()
.contains_key("idle_minutes"));
assert_eq!(
migrated["inspect"]["duplicates"]["expected_mirrors"],
json!([{"source":"src/**","mirror":"mirror/**"}])
);
let options: Value = serde_json::from_str(
migrated["lsp"]["servers"]["rust"]["initialization_options"]
.as_str()
.unwrap(),
)
.unwrap();
assert_eq!(options, json!({"checkOnSave": true, "other": null}));
assert!(auto_migrate_user_config(&user).is_none());
let mut project: Value = serde_json::from_str(&crate::jsonc::strip_jsonc(legacy)).unwrap();
let translated = feature_config::translate_document(
project.as_object_mut().unwrap(),
feature_config::DocumentTier::Project,
);
let mut expected_project = migrated.clone();
expected_project["harnesses"]["pi"]["bash"]
.as_object_mut()
.unwrap()
.remove("enabled");
assert_eq!(project, expected_project);
let project_notice =
feature_config::project_retired_keys_notice("/project/.cortexkit/aft.jsonc", &translated);
for replacement in [
"bash.enabled",
"lsp.idle_shutdown",
"source and mirror objects",
"initialization_options → JSON text",
] {
assert!(notice.contains(replacement), "user: {notice}");
assert!(
project_notice.contains(replacement),
"project: {project_notice}"
);
}
}