Skip to main content

aft_base/
config_fix.rs

1//! The retired-key configuration migration behind `aft doctor --fix` and the
2//! automatic rewrite of the user config file.
3//!
4//! Ordinary loading refuses the names retired in 0.62 or earlier
5//! ([`feature_config::REFUSED_RETIRED_PATHS`] and the prefixed `aft_*` host
6//! names) with `removed_config_key`, and translates the more recently retired
7//! `bridge.hang_threshold` and `views.idle_checkout_hours` in memory. This
8//! module rewrites a config file so that it states the same intent with
9//! canonical keys, whichever of those groups its retired names belong to, and
10//! splices the changes into the original text so comments, formatting and
11//! unrelated keys survive.
12//! `doctor --fix` runs it for the user and project files on request, and also
13//! deletes the removed data-layer keys (`views.enabled`,
14//! `views.callgraph_copies`, `worktree.ram_overlay`);
15//! [`auto_migrate_user_config`] runs it for the user file whenever AFT loads
16//! that file, but leaves the removed data-layer keys in place. A project file
17//! is shared through its repository and is never rewritten automatically.
18//!
19//! Every block is repaired: the base object and each embedded
20//! `harnesses.<id>` object. A project file only ever gains disables for
21//! unprotected tools; protected slots (`aft_safety` and the seven host tool
22//! names) are dropped from what it materializes and reported, matching what
23//! the resolver would ignore anyway.
24
25use std::fs::{self, Permissions};
26use std::io::{self, Write as _};
27use std::path::{Path, PathBuf};
28
29use serde::Serialize;
30use serde_json::{Map, Value};
31
32use crate::feature_config::{self, INDEX_INPUTS, RETIRED_PATHS};
33use crate::jsonc_edit;
34
35/// Which trust tier a config file belongs to.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
37#[serde(rename_all = "lowercase")]
38pub enum FixTier {
39    User,
40    Project,
41}
42
43/// The rewritten text of one file and what the rewrite did.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct Migration {
46    pub text: String,
47    pub changed: bool,
48    /// Human-readable notes: conflicts resolved by precedence and ignored
49    /// protected project disables.
50    pub notes: Vec<String>,
51}
52
53struct Document(String);
54
55impl Document {
56    fn value(&self) -> Result<Value, String> {
57        parse_document(&self.0).map_err(|error| format!("parse document at /: {error}"))
58    }
59
60    fn set(&mut self, path: &[&str], value: &Value) -> Result<(), String> {
61        let pointer = jsonc_edit::pointer(path);
62        let current = self.value()?;
63        let old = current.pointer(&pointer);
64        if old == Some(value) {
65            return Ok(());
66        }
67        if let (Some(Value::Array(old)), Value::Array(new)) = (old, value) {
68            for (i, (old, new)) in old.iter().zip(new).enumerate() {
69                if old != new {
70                    subc_jsonc::set_element(&mut self.0, path, i, new)
71                        .map_err(|error| format!("set_element at {pointer}/{i}: {error}"))?;
72                }
73            }
74            for i in (new.len()..old.len()).rev() {
75                subc_jsonc::remove_element(&mut self.0, path, i)
76                    .map_err(|error| format!("remove_element at {pointer}/{i}: {error}"))?;
77            }
78            for element in new.iter().skip(old.len()) {
79                subc_jsonc::push_element(&mut self.0, path, element)
80                    .map_err(|error| format!("push_element at {pointer}: {error}"))?;
81            }
82        } else {
83            subc_jsonc::set_member(&mut self.0, path, value)
84                .map_err(|error| format!("set_member at {pointer}: {error}"))?;
85        }
86        // The editor addresses the first occurrence of a duplicate key; the
87        // resolver uses the last. Refuse an edit that didn't reach its value.
88        if self.value()?.pointer(&pointer) != Some(value) {
89            return Err(format!("verify set at {pointer}: edited value is shadowed"));
90        }
91        Ok(())
92    }
93
94    fn remove(&mut self, path: &[&str]) -> Result<(), String> {
95        let pointer = jsonc_edit::pointer(path);
96        subc_jsonc::remove_member(&mut self.0, path)
97            .map_err(|error| format!("remove_member at {pointer}: {error}"))?;
98        if self.value()?.pointer(&pointer).is_some() {
99            return Err(format!(
100                "verify removal at {pointer}: a duplicate key remains"
101            ));
102        }
103        Ok(())
104    }
105
106    fn remove_if_empty_object(&mut self, path: &[&str]) -> Result<(), String> {
107        if self
108            .value()?
109            .pointer(&jsonc_edit::pointer(path))
110            .and_then(Value::as_object)
111            .is_some_and(Map::is_empty)
112        {
113            self.remove(path)?;
114        }
115        Ok(())
116    }
117}
118
119fn parse_document(text: &str) -> Result<Value, String> {
120    let strict = subc_jsonc::jsonc_to_json(text)?;
121    if strict.trim().is_empty() {
122        return Ok(Value::Object(Map::new()));
123    }
124    let value: Value = serde_json::from_str(&strict).map_err(|error| error.to_string())?;
125    if !value.is_object() {
126        return Err("the root value must be an object".to_string());
127    }
128    Ok(value)
129}
130
131fn block_label(prefix: &[String]) -> String {
132    if prefix.is_empty() {
133        "base".to_string()
134    } else {
135        prefix.join(".")
136    }
137}
138
139fn path_of<'a>(prefix: &'a [String], tail: &[&'a str]) -> Vec<&'a str> {
140    prefix
141        .iter()
142        .map(String::as_str)
143        .chain(tail.iter().copied())
144        .collect()
145}
146
147fn lookup<'a>(value: &'a Value, prefix: &[String]) -> Option<&'a Map<String, Value>> {
148    prefix
149        .iter()
150        .try_fold(value, |node, key| node.get(key))?
151        .as_object()
152}
153
154fn get_bool(block: &Map<String, Value>, container: &str, leaf: &str) -> Option<bool> {
155    block.get(container)?.as_object()?.get(leaf)?.as_bool()
156}
157
158/// Repair the already-retired GitHub enable aliases of one block. Precedence:
159/// canonical leaf, then the value `github.enabled:false` generates, then the
160/// alias. The aliases are removed; `gh_shim.binary_path` is kept.
161fn repair_github_aliases(
162    doc: &mut Document,
163    prefix: &[String],
164    notes: &mut Vec<String>,
165) -> Result<(), String> {
166    let value = doc.value()?;
167    let Some(block) = lookup(&value, prefix) else {
168        return Ok(());
169    };
170    let label = block_label(prefix);
171    let master_off = get_bool(block, "github", "enabled") == Some(false);
172    let aliases = [
173        (
174            "gh_read",
175            "read",
176            block
177                .get("gh_read")
178                .and_then(|v| v.get("enabled"))
179                .and_then(Value::as_bool),
180        ),
181        (
182            "gh_shim",
183            "shim",
184            block
185                .get("gh_shim")
186                .and_then(|v| v.get("enabled"))
187                .and_then(Value::as_bool),
188        ),
189    ];
190    if block.contains_key("gh_read") {
191        doc.remove(&path_of(prefix, &["gh_read"]))?;
192    }
193    if block
194        .get("gh_shim")
195        .and_then(Value::as_object)
196        .is_some_and(|shim| shim.contains_key("enabled"))
197    {
198        doc.remove(&path_of(prefix, &["gh_shim", "enabled"]))?;
199        doc.remove_if_empty_object(&path_of(prefix, &["gh_shim"]))?;
200    }
201    for (alias, leaf, alias_value) in aliases {
202        let canonical = get_bool(block, "github", leaf);
203        if let Some(alias_value) = alias_value {
204            if let Some(canonical) = canonical {
205                if canonical != alias_value {
206                    notes.push(format!(
207                        "{label}: {alias}.enabled={alias_value} ignored because github.{leaf}={canonical} is set"
208                    ));
209                }
210            } else if master_off {
211                if alias_value {
212                    notes.push(format!(
213                        "{label}: {alias}.enabled=true ignored because github.enabled=false switches github.{leaf} off"
214                    ));
215                }
216            } else {
217                doc.set(
218                    &path_of(prefix, &["github", leaf]),
219                    &Value::Bool(alias_value),
220                )?;
221            }
222        }
223    }
224    Ok(())
225}
226
227/// Whether a rewrite also deletes the removed data-layer keys
228/// ([`feature_config::REMOVED_DATA_LAYER_PATHS`]). `doctor --fix` deletes
229/// them; the automatic rewrite keeps them so loading can refuse them until
230/// the user explicitly runs `doctor --fix`.
231#[derive(Debug, Clone, Copy, PartialEq, Eq)]
232enum RemovedKeys {
233    Delete,
234    Keep,
235}
236
237/// Rewrite one block's retired keys to the canonical values ordinary loading
238/// derives from them ([`feature_config::translate_document`]).
239fn migrate_block(
240    doc: &mut Document,
241    prefix: &[String],
242    raw: &Map<String, Value>,
243    translated: &Map<String, Value>,
244    tier: FixTier,
245    removed_keys: RemovedKeys,
246    notes: &mut Vec<String>,
247) -> Result<(), String> {
248    let label = block_label(prefix);
249    let mut emptied = Vec::new();
250    remove_retired_members(doc, prefix, raw, removed_keys, &mut emptied)?;
251    let document_tier = if tier == FixTier::User {
252        feature_config::DocumentTier::User
253    } else {
254        feature_config::DocumentTier::Project
255    };
256    let mut edits = feature_config::settings_shape::edits(raw, document_tier, prefix.is_empty());
257    // Read replacements from the original values, then remove the old names
258    // before writing their replacements into the staged text.
259    edits.sort_by_key(|edit| edit.value.is_some());
260    for edit in edits {
261        let path: Vec<_> = prefix
262            .iter()
263            .chain(&edit.path)
264            .map(String::as_str)
265            .collect();
266        match edit.value {
267            Some(value) => doc.set(&path, &value)?,
268            None => {
269                doc.remove(&path)?;
270            }
271        }
272    }
273    if let Some(profile) = translated
274        .get("sandbox")
275        .and_then(|sandbox| sandbox.get("profile"))
276    {
277        if raw
278            .get("sandbox")
279            .and_then(|sandbox| sandbox.get("profile"))
280            != Some(profile)
281        {
282            doc.set(&path_of(prefix, &["sandbox", "profile"]), profile)?;
283        }
284    }
285
286    // Registration: materialize the translated list when it differs from
287    // what the block spells out (aliases canonicalized, generated disables).
288    if let Some(Value::Array(list)) = translated.get("disabled_tools") {
289        let wanted: Vec<String> = list
290            .iter()
291            .filter_map(Value::as_str)
292            .map(str::to_string)
293            .collect();
294        let current: Option<Vec<String>> =
295            raw.get("disabled_tools")
296                .and_then(Value::as_array)
297                .map(|entries| {
298                    entries
299                        .iter()
300                        .filter_map(Value::as_str)
301                        .map(str::to_string)
302                        .collect()
303                });
304        if current.as_ref() != Some(&wanted) {
305            let mut kept = Vec::new();
306            for name in wanted {
307                if tier == FixTier::Project && feature_config::is_project_protected_tool(&name) {
308                    notes.push(format!(
309                        "{label}: ignored protected disable {name}; a project config cannot disable it"
310                    ));
311                } else if !kept.contains(&name) {
312                    kept.push(name);
313                }
314            }
315            doc.set(
316                &path_of(prefix, &["disabled_tools"]),
317                &Value::Array(kept.into_iter().map(Value::String).collect()),
318            )?;
319        }
320    }
321
322    for (leaf, _, _) in INDEX_INPUTS {
323        let raw_has = raw
324            .get("indexes")
325            .and_then(Value::as_object)
326            .is_some_and(|indexes| indexes.contains_key(leaf));
327        if let (false, Some(value)) = (raw_has, get_bool(translated, "indexes", leaf)) {
328            doc.set(&path_of(prefix, &["indexes", leaf]), &Value::Bool(value))?;
329        }
330    }
331
332    if !raw.contains_key("bash") {
333        if let Some(value) = translated.get("bash") {
334            doc.set(&path_of(prefix, &["bash"]), value)?;
335        }
336    }
337    let raw_lsp_ty = raw
338        .get("experimental")
339        .and_then(|experimental| experimental.get("lsp_ty"));
340    let translated_lsp_ty = translated
341        .get("experimental")
342        .and_then(|experimental| experimental.get("lsp_ty"));
343    if let (None, Some(value)) = (raw_lsp_ty, translated_lsp_ty) {
344        doc.set(&path_of(prefix, &["experimental", "lsp_ty"]), value)?;
345    }
346
347    for leaf in ["read", "write", "shim"] {
348        let raw_has = raw
349            .get("github")
350            .and_then(Value::as_object)
351            .is_some_and(|github| github.contains_key(leaf));
352        if let (false, Some(value)) = (raw_has, get_bool(translated, "github", leaf)) {
353            doc.set(&path_of(prefix, &["github", leaf]), &Value::Bool(value))?;
354        }
355    }
356
357    if let Some(value) = raw.get("idle").and_then(|idle| idle.get("lsp_ttl_minutes")) {
358        if raw
359            .get("lsp")
360            .and_then(|lsp| lsp.get("idle_minutes"))
361            .is_none()
362        {
363            let minutes = feature_config::retired_lsp_idle_minutes(value);
364            doc.set(
365                &path_of(prefix, &["lsp", "idle_minutes"]),
366                &Value::from(minutes),
367            )?;
368        }
369    }
370
371    if let Some(value) = raw
372        .get("views")
373        .and_then(|views| views.get("idle_checkout_hours"))
374    {
375        if raw
376            .get("idle")
377            .and_then(|idle| idle.get("checkout_hours"))
378            .is_none()
379        {
380            let hours = feature_config::retired_idle_checkout_hours(value);
381            doc.set(
382                &path_of(prefix, &["idle", "checkout_hours"]),
383                &Value::from(hours),
384            )?;
385        }
386    }
387
388    if tier == FixTier::User && get_bool(raw, "bash", "runon_enabled") == Some(false) {
389        doc.set(
390            &path_of(prefix, &["remote_exec", "enabled"]),
391            &Value::Bool(false),
392        )?;
393    }
394
395    for container in emptied {
396        doc.remove_if_empty_object(&path_of(prefix, &[container]))?;
397    }
398    Ok(())
399}
400
401fn remove_retired_members(
402    doc: &mut Document,
403    prefix: &[String],
404    raw: &Map<String, Value>,
405    removed_keys: RemovedKeys,
406    emptied: &mut Vec<&'static str>,
407) -> Result<(), String> {
408    let removed_paths: &[&str] = match removed_keys {
409        RemovedKeys::Delete => &feature_config::REMOVED_DATA_LAYER_PATHS,
410        RemovedKeys::Keep => &[],
411    };
412    for (path, _) in RETIRED_PATHS
413        .into_iter()
414        .chain(feature_config::REMOVED_INSPECT_LSP_PATHS)
415        .chain(feature_config::REMOVED_NO_EFFECT_PATHS)
416        .chain(feature_config::REMOVED_OPENCODE_PATHS)
417        .chain([feature_config::RETIRED_IDLE_CHECKOUT_HOURS])
418        .chain([("bash.runon_enabled", "remote_exec.enabled")])
419        .chain(removed_paths.iter().map(|path| (*path, "")))
420        .chain(
421            (removed_keys == RemovedKeys::Delete)
422                .then_some((feature_config::CALLGRAPH_CHUNK_KEY, "")),
423        )
424    {
425        let segments: Vec<&str> = path.split('.').collect();
426        let present = match segments.as_slice() {
427            [key] => raw.contains_key(*key),
428            [container, leaf] => raw
429                .get(*container)
430                .and_then(Value::as_object)
431                .is_some_and(|inner| inner.contains_key(*leaf)),
432            _ => false,
433        };
434        if present {
435            doc.remove(&path_of(prefix, &segments))?;
436            // An empty bash object keeps its precedence over retired
437            // experimental bash defaults after the old remote gate is gone.
438            if segments.len() == 2 && path != "bash.runon_enabled" {
439                emptied.push(segments[0]);
440            }
441        }
442    }
443    Ok(())
444}
445
446/// Migrate one config file's text the way `doctor --fix` does: retired keys
447/// become their current equivalents and the removed data-layer keys are
448/// deleted. `changed` is false (and `text` identical) when the file needs no
449/// migration.
450pub fn migrate_config_text(text: &str, tier: FixTier) -> Result<Migration, String> {
451    migrate_config_text_with(text, tier, RemovedKeys::Delete)
452}
453
454/// The text the automatic rewrite of the user file
455/// ([`auto_migrate_user_config`]) would leave: retired keys become their
456/// current equivalents and the removed data-layer keys stay. Nothing is
457/// written.
458pub fn migrate_user_config_text(text: &str) -> Result<Migration, String> {
459    migrate_config_text_with(text, FixTier::User, RemovedKeys::Keep)
460}
461
462fn migrate_config_text_with(
463    text: &str,
464    tier: FixTier,
465    removed_keys: RemovedKeys,
466) -> Result<Migration, String> {
467    let mut doc = Document(text.to_string());
468    let mut notes = Vec::new();
469
470    let harness_names: Vec<String> = doc
471        .value()?
472        .get("harnesses")
473        .and_then(Value::as_object)
474        .map(|harnesses| {
475            harnesses
476                .iter()
477                .filter(|(_, block)| block.is_object())
478                .map(|(name, _)| name.clone())
479                .collect()
480        })
481        .unwrap_or_default();
482    let mut prefixes: Vec<Vec<String>> = vec![Vec::new()];
483    prefixes.extend(
484        harness_names
485            .iter()
486            .map(|name| vec!["harnesses".to_string(), name.clone()]),
487    );
488
489    for prefix in &prefixes {
490        repair_github_aliases(&mut doc, prefix, &mut notes)?;
491    }
492
493    let raw = doc.value()?;
494    let mut translated = raw.as_object().cloned().unwrap_or_default();
495    let document_tier = match tier {
496        FixTier::User => feature_config::DocumentTier::User,
497        FixTier::Project => feature_config::DocumentTier::Project,
498    };
499    feature_config::translate_document(&mut translated, document_tier);
500    let translated = Value::Object(translated);
501    for prefix in &prefixes {
502        let (Some(raw_block), Some(translated_block)) =
503            (lookup(&raw, prefix), lookup(&translated, prefix))
504        else {
505            continue;
506        };
507        migrate_block(
508            &mut doc,
509            prefix,
510            raw_block,
511            translated_block,
512            tier,
513            removed_keys,
514            &mut notes,
515        )?;
516    }
517
518    let changed = doc.0 != text;
519    Ok(Migration {
520        text: doc.0,
521        changed,
522        notes,
523    })
524}
525
526/// Outcome for one file of a fix run.
527#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
528pub struct FixOutcome {
529    pub path: PathBuf,
530    pub tier: FixTier,
531    /// `rewritten`, `unchanged` or `failed`.
532    pub status: &'static str,
533    pub notes: Vec<String>,
534    pub error: Option<String>,
535}
536
537/// Files a fix run may touch for an invocation in `cwd`: the existing user
538/// file and, when present, the project file at the invocation directory.
539/// A legacy project file is repaired in place when the shared file is absent;
540/// explicit fix never relocates it or creates a shared project file.
541pub fn fix_targets(user_config_path: Option<&Path>, cwd: &Path) -> Vec<(PathBuf, FixTier)> {
542    let mut targets = Vec::new();
543    if let Some(user) = user_config_path.filter(|path| path.is_file()) {
544        targets.push((user.to_path_buf(), FixTier::User));
545    }
546    let project = crate::subc_config::project_config_read_path(cwd, None);
547    if project.is_file() {
548        targets.push((project, FixTier::Project));
549    }
550    targets
551}
552
553/// Repair every target independently. A failure leaves that file unchanged
554/// and does not stop the others.
555pub fn fix_files(targets: &[(PathBuf, FixTier)]) -> Vec<FixOutcome> {
556    targets
557        .iter()
558        .map(|(path, tier)| {
559            let result = crate::config::open_config_file(path)
560                .and_then(|file| std::io::read_to_string(file))
561                .map_err(|error| format!("could not read: {error}"))
562                .and_then(|text| {
563                    let migration = migrate_config_text(&text, *tier)?;
564                    if migration.changed {
565                        jsonc_edit::write_atomic(path, &migration.text)
566                            .map_err(|error| format!("could not write: {error}"))?;
567                    }
568                    Ok(migration)
569                });
570            match result {
571                Ok(migration) => FixOutcome {
572                    path: path.clone(),
573                    tier: *tier,
574                    status: if migration.changed {
575                        "rewritten"
576                    } else {
577                        "unchanged"
578                    },
579                    notes: migration.notes,
580                    error: None,
581                },
582                Err(error) => FixOutcome {
583                    path: path.clone(),
584                    tier: *tier,
585                    status: "failed",
586                    notes: Vec::new(),
587                    error: Some(error),
588                },
589            }
590        })
591        .collect()
592}
593
594/// What the automatic migration of the user config file did.
595#[derive(Debug, Clone, PartialEq, Eq)]
596pub enum UserConfigMigration {
597    /// The file was rewritten to current keys; `backup` holds its previous text.
598    Migrated {
599        path: PathBuf,
600        backup: PathBuf,
601        notice: String,
602    },
603    /// The file still uses retired keys because it could not be rewritten.
604    /// Loading translates the recently retired ones in memory and refuses the
605    /// names retired in 0.62 or earlier.
606    NotMigrated {
607        path: PathBuf,
608        reason: String,
609        notice: String,
610    },
611}
612
613impl UserConfigMigration {
614    /// The user-facing notice for this outcome.
615    pub fn notice(&self) -> &str {
616        match self {
617            Self::Migrated { notice, .. } | Self::NotMigrated { notice, .. } => notice,
618        }
619    }
620}
621
622/// How long another process's migration lock is honoured before it is
623/// treated as left behind by a crash and removed.
624const MIGRATION_LOCK_STALE: std::time::Duration = std::time::Duration::from_secs(30);
625/// How long a loader waits for another process that is migrating the same
626/// file before it gives up and reads the file as it is.
627const MIGRATION_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
628
629/// The retired-key translation of a config text, when it parses as an object
630/// and uses at least one retired key.
631fn retired_key_translation(text: &str) -> Option<feature_config::DocumentTranslation> {
632    let value = parse_document(text).ok()?;
633    let Value::Object(mut map) = value else {
634        return None;
635    };
636    let mut translation =
637        feature_config::translate_document(&mut map, feature_config::DocumentTier::User);
638    // The automatic rewrite leaves these keys untouched. Its notice must name
639    // only the keys it actually rewrites, not claim refused keys were migrated.
640    translation.retired_keys.retain(|key| {
641        !feature_config::REMOVED_DATA_LAYER_PATHS.iter().any(|path| {
642            key == path
643                || key
644                    .strip_suffix(path)
645                    .is_some_and(|prefix| prefix.ends_with('.'))
646        })
647    });
648    translation.legacy_input = !translation.retired_keys.is_empty();
649    translation.legacy_input.then_some(translation)
650}
651
652/// Whether loading refuses a config text for a retired or removed key
653/// ([`feature_config::removed_config_key_errors`]).
654fn names_refused_key(text: &str) -> bool {
655    parse_document(text)
656        .ok()
657        .and_then(|value| {
658            value
659                .as_object()
660                .map(|map| !feature_config::removed_config_key_errors(map).is_empty())
661        })
662        .unwrap_or(false)
663}
664
665/// Exclusive, cross-process right to rewrite one config file, held as a lock
666/// file next to it and removed on drop.
667struct MigrationLock {
668    path: PathBuf,
669}
670
671impl Drop for MigrationLock {
672    fn drop(&mut self) {
673        let _ = std::fs::remove_file(&self.path);
674    }
675}
676
677enum LockAttempt {
678    Acquired(MigrationLock),
679    /// Another process holds the lock and did not release it in time.
680    Busy,
681    Failed(std::io::Error),
682}
683
684fn acquire_migration_lock(target: &Path) -> LockAttempt {
685    let name = target
686        .file_name()
687        .map(|name| name.to_string_lossy().into_owned())
688        .unwrap_or_else(|| "aft.jsonc".to_string());
689    let path = target.with_file_name(format!(".{name}.migrate.lock"));
690    let deadline = std::time::Instant::now() + MIGRATION_LOCK_WAIT;
691    loop {
692        match std::fs::OpenOptions::new()
693            .write(true)
694            .create_new(true)
695            .open(&path)
696        {
697            Ok(_) => return LockAttempt::Acquired(MigrationLock { path }),
698            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
699                let stale = std::fs::metadata(&path)
700                    .and_then(|metadata| metadata.modified())
701                    .ok()
702                    .and_then(|modified| modified.elapsed().ok())
703                    .is_some_and(|age| age > MIGRATION_LOCK_STALE);
704                if stale {
705                    let _ = std::fs::remove_file(&path);
706                    continue;
707                }
708                if std::time::Instant::now() >= deadline {
709                    return LockAttempt::Busy;
710                }
711                std::thread::sleep(std::time::Duration::from_millis(25));
712            }
713            Err(error) => {
714                // Windows refuses to create a file whose previous holder is
715                // still deleting it (a delete-pending name) with
716                // ERROR_ACCESS_DENIED rather than AlreadyExists, so a
717                // concurrent migration releasing the lock looks like a
718                // permission error. Retry it like a held lock until the wait
719                // ends; a real permission problem still fails after that.
720                if cfg!(windows)
721                    && error.kind() == std::io::ErrorKind::PermissionDenied
722                    && std::time::Instant::now() < deadline
723                {
724                    std::thread::sleep(std::time::Duration::from_millis(25));
725                    continue;
726                }
727                return LockAttempt::Failed(error);
728            }
729        }
730    }
731}
732
733/// The old bytes may contain credentials, even if the settings file is public.
734fn write_backup(dir: &Path, text: &str) -> io::Result<PathBuf> {
735    crate::production_storage::refuse_write(dir)?;
736    crate::private_storage::create_dir_all(dir)?;
737    let stamp = std::time::SystemTime::now()
738        .duration_since(std::time::UNIX_EPOCH)
739        .map(|elapsed| elapsed.as_nanos())
740        .unwrap_or_default();
741    let mut backup = tempfile::Builder::new()
742        .prefix(&format!("aft.jsonc.bak-{stamp}-"))
743        .tempfile_in(dir)?;
744    #[cfg(unix)]
745    {
746        use std::os::unix::fs::PermissionsExt as _;
747        backup
748            .as_file()
749            .set_permissions(Permissions::from_mode(0o600))?;
750    }
751    backup.write_all(text.as_bytes())?;
752    crate::durability::sync_file(backup.as_file(), backup.path())?;
753    crate::durability::sync_dir(dir)?;
754    backup
755        .keep()
756        .map(|(_, path)| path)
757        .map_err(|error| error.error)
758}
759
760fn publish_conversion(
761    path: &Path,
762    contents: &str,
763    permissions: Permissions,
764    relocating: bool,
765) -> io::Result<()> {
766    let parent = path
767        .parent()
768        .filter(|path| !path.as_os_str().is_empty())
769        .unwrap_or(Path::new("."));
770    let mut temp = tempfile::Builder::new()
771        .prefix(".aft.jsonc.tmp-")
772        .tempfile_in(parent)?;
773    temp.write_all(contents.as_bytes())?;
774    temp.as_file().set_permissions(permissions)?;
775    crate::durability::sync_file(temp.as_file(), temp.path())?;
776    // Complete fallible preparation before the rename commits new settings.
777    crate::durability::sync_dir(parent)?;
778    if relocating {
779        // The desktop may have created the canonical settings since we checked.
780        temp.persist_noclobber(path)
781    } else {
782        temp.persist(path)
783    }
784    .map(|_| ())
785    .map_err(|error| error.error)
786}
787
788/// Rewrite retired user keys, retaining the old bytes in AFT's data folder.
789pub fn auto_migrate_user_config(path: &Path) -> Option<UserConfigMigration> {
790    auto_migrate_user_config_bounded(path, crate::subc_config::CONFIG_READ_LIMIT)
791        .ok()
792        .flatten()
793}
794
795pub(crate) fn auto_migrate_user_config_bounded(
796    path: &Path,
797    limit: usize,
798) -> io::Result<Option<UserConfigMigration>> {
799    if crate::subc_config::is_legacy_user_config_path(path) {
800        // If startup couldn't relocate the legacy file, read it as-is. An
801        // in-place rewrite would change it without reaching the canonical path.
802        return Ok(None);
803    }
804    migrate_user_config_to(path, path, limit, |path| fs::remove_file(path))
805}
806
807pub(crate) fn migrate_user_config_to(
808    source: &Path,
809    destination: &Path,
810    limit: usize,
811    remove_legacy: impl FnOnce(&Path) -> io::Result<()>,
812) -> io::Result<Option<UserConfigMigration>> {
813    let mut failure = None;
814    let result = auto_migrate_user_config_with_reader(
815        source,
816        destination,
817        migration_backup_dir,
818        publish_conversion,
819        |path| {
820            let read = (|| {
821                let file = crate::config::open_config_file(path)?;
822                crate::subc_config::read_bounded_config(file, limit)
823            })();
824            if let Err(error) = &read {
825                failure = Some(io::Error::new(error.kind(), error.to_string()));
826            }
827            read
828        },
829        remove_legacy,
830    );
831    match failure {
832        Some(error) => Err(error),
833        None => Ok(result),
834    }
835}
836
837fn migration_backup_dir() -> PathBuf {
838    #[cfg(test)]
839    if let Some(path) = TEST_BACKUP_DIR.with(|slot| slot.borrow().clone()) {
840        return path;
841    }
842    crate::storage_path::storage_dir(None)
843}
844
845#[cfg(test)]
846thread_local! {
847    static TEST_BACKUP_DIR: std::cell::RefCell<Option<PathBuf>> = const { std::cell::RefCell::new(None) };
848}
849
850#[cfg(test)]
851pub(crate) fn with_backup_dir_for_test<T>(path: &Path, run: impl FnOnce() -> T) -> T {
852    struct Restore(Option<PathBuf>);
853    impl Drop for Restore {
854        fn drop(&mut self) {
855            TEST_BACKUP_DIR.with(|slot| slot.replace(self.0.take()));
856        }
857    }
858    let _restore = Restore(TEST_BACKUP_DIR.with(|slot| slot.replace(Some(path.to_path_buf()))));
859    run()
860}
861
862fn auto_migrate_user_config_with_reader(
863    source: &Path,
864    destination: &Path,
865    backup_dir: impl FnOnce() -> PathBuf,
866    write: impl FnOnce(&Path, &str, Permissions, bool) -> io::Result<()>,
867    mut read: impl FnMut(&Path) -> io::Result<String>,
868    remove_legacy: impl FnOnce(&Path) -> io::Result<()>,
869) -> Option<UserConfigMigration> {
870    let relocating = source != destination;
871    let text = read(source).ok()?;
872    let translation = retired_key_translation(&text);
873    if translation.is_none() && !relocating {
874        return None;
875    }
876    let not_migrated =
877        |reason: String, translation: Option<&feature_config::DocumentTranslation>, text: &str| {
878            // Loading refuses a file that still names a key retired in 0.62 or
879            // earlier, and that refusal names the key and `doctor --fix`. A notice
880            // saying AFT applied the current equivalents would be wrong for it.
881            let notice = translation
882                .filter(|_| !names_refused_key(text))
883                .map_or_else(String::new, |translation| {
884                    feature_config::user_config_not_migrated_notice(
885                        &source.display().to_string(),
886                        &reason,
887                        translation,
888                    )
889                });
890            if notice.is_empty() {
891                crate::slog_warn!("config user {}: {reason}", source.display());
892                return None;
893            }
894            Some(UserConfigMigration::NotMigrated {
895                path: source.to_path_buf(),
896                notice,
897                reason,
898            })
899        };
900
901    let actual = match fs::canonicalize(source) {
902        Ok(path) => path,
903        Err(error) => {
904            return not_migrated(
905                format!("resolve source at /: {error}"),
906                translation.as_ref(),
907                &text,
908            )
909        }
910    };
911    let target = if relocating {
912        destination
913    } else {
914        actual.as_path()
915    };
916    if actual.ends_with(Path::new(".cortexkit").join("aft.jsonc")) {
917        return not_migrated(
918            "refused to replace a project settings file at /".to_string(),
919            translation.as_ref(),
920            &text,
921        );
922    }
923    if let Some(reason) = crate::production_storage::config_write_refusal(&actual)
924        .or_else(|| crate::production_storage::config_write_refusal(target))
925    {
926        return not_migrated(reason, translation.as_ref(), &text);
927    }
928    let permissions = match fs::metadata(&actual) {
929        Ok(metadata) if metadata.permissions().readonly() => {
930            return not_migrated(
931                "the file is read-only".to_string(),
932                translation.as_ref(),
933                &text,
934            );
935        }
936        Ok(metadata) => metadata.permissions(),
937        Err(error) => {
938            return not_migrated(
939                format!("inspect source at /: {error}"),
940                translation.as_ref(),
941                &text,
942            )
943        }
944    };
945    let _lock = match acquire_migration_lock(&actual) {
946        LockAttempt::Acquired(lock) => lock,
947        // Another loader is rewriting the file and will report it.
948        LockAttempt::Busy => return None,
949        LockAttempt::Failed(error) => {
950            return not_migrated(
951                format!("lock source at /: {error}"),
952                translation.as_ref(),
953                &text,
954            );
955        }
956    };
957
958    if relocating
959        && !matches!(fs::symlink_metadata(target), Err(error) if error.kind() == io::ErrorKind::NotFound)
960    {
961        return None;
962    }
963    // Re-read under the lock: another process may have finished meanwhile.
964    let text = match read(&actual) {
965        Ok(text) => text,
966        Err(error) => {
967            return not_migrated(
968                format!("read source at /: {error}"),
969                translation.as_ref(),
970                &text,
971            )
972        }
973    };
974    let translation = retired_key_translation(&text);
975    if !relocating && translation.is_none() {
976        return None;
977    }
978    let migration = match migrate_user_config_text(&text) {
979        Ok(migration) if migration.changed || relocating => migration,
980        Ok(_) => return None,
981        Err(error) => return not_migrated(error, translation.as_ref(), &text),
982    };
983    let backup = match write_backup(&backup_dir(), &text) {
984        Ok(backup) => backup,
985        Err(error) => {
986            return not_migrated(
987                format!("write old copy at /: {error}"),
988                translation.as_ref(),
989                &text,
990            );
991        }
992    };
993    let parent = target
994        .parent()
995        .filter(|path| !path.as_os_str().is_empty())
996        .unwrap_or(Path::new("."));
997    let publish = || {
998        if relocating {
999            fs::create_dir_all(parent)?;
1000        }
1001        write(target, &migration.text, permissions, relocating)
1002    };
1003    if let Err(error) = publish() {
1004        let cleanup = fs::remove_file(&backup);
1005        let mut reason = format!("publish settings at /: {error}");
1006        if let Err(error) = cleanup {
1007            reason.push_str(&format!("; could not remove {}: {error}", backup.display()));
1008        }
1009        return not_migrated(reason, translation.as_ref(), &text);
1010    }
1011    // The rename has replaced the file, but its directory entry isn't durable
1012    // yet. Keep the backup if syncing fails, and don't remove a legacy source.
1013    if let Err(error) = crate::durability::sync_dir(parent) {
1014        return not_migrated(
1015            format!("publish settings at /: {error}"),
1016            translation.as_ref(),
1017            &text,
1018        );
1019    }
1020    if relocating {
1021        if let Err(error) = remove_legacy(source) {
1022            crate::slog_warn!("config user: could not finish removing legacy settings {} after publishing {}: {error}", source.display(), target.display());
1023        }
1024    }
1025    let notice = translation
1026        .as_ref()
1027        .map_or_else(String::new, |translation| {
1028            feature_config::user_config_migrated_notice(
1029                &destination.display().to_string(),
1030                &backup.display().to_string(),
1031                translation,
1032            )
1033        });
1034    Some(UserConfigMigration::Migrated {
1035        path: destination.to_path_buf(),
1036        notice,
1037        backup,
1038    })
1039}
1040
1041#[cfg(test)]
1042#[path = "config_fix_tests.rs"]
1043mod tests;