magi-code 0.77.1

Repository-aware CLI coding agent for terminal work
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
use std::{
    env, fs,
    path::{Path, PathBuf},
};

use anyhow::Context;

const MC_HOME_ENV: &str = "MC_HOME";

#[derive(Debug, Clone, Copy)]
enum RootResolutionMode {
    Runtime,
    ReadOnly,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct McPaths {
    pub root: PathBuf,
    pub cache: PathBuf,
    pub state: PathBuf,
    pub sessions: PathBuf,
    pub checkpoints: PathBuf,
    pub skills: PathBuf,
    pub prompts: PathBuf,
    pub subagents: PathBuf,
    pub primary_agents: PathBuf,
    pub user_agents: PathBuf,
    pub settings_file: PathBuf,
    pub project_settings_file: PathBuf,
    pub local_settings_file: Option<PathBuf>,
    pub auth_file: PathBuf,
}

impl McPaths {
    pub fn resolve() -> anyhow::Result<Self> {
        let root = resolve_storage_root(RootResolutionMode::Runtime)?;
        let project_dir = current_project_dir();
        Ok(Self::from_root_and_project_dir(root, project_dir))
    }

    /// Resolves the storage root without migration or runtime directory creation.
    pub(crate) fn resolve_read_only() -> anyhow::Result<Self> {
        let root = resolve_storage_root(RootResolutionMode::ReadOnly)?;
        let project_dir = current_project_dir();
        Ok(Self::from_root_and_project_dir(root, project_dir))
    }

    /// Constructs paths from an explicit storage root and project directory.
    ///
    /// The project settings target is always `<project_dir>/.magi-code/settings.json`.
    /// `local_settings_file` is populated only when that target exists when this method runs.
    pub fn from_root_and_project_dir(root: PathBuf, project_dir: PathBuf) -> Self {
        let project_settings_file = project_settings_file_for(&project_dir);
        let local_settings_file = project_settings_file
            .exists()
            .then_some(project_settings_file.clone());
        Self::from_parts(root, project_settings_file, local_settings_file)
    }

    /// Compatibility wrapper that uses the current process directory as the project directory.
    ///
    /// New internal callers should use [`Self::from_root_and_project_dir`] so path resolution is
    /// deterministic. This wrapper retains the historical `from_root` behavior and does not
    /// detect a local settings file.
    pub fn from_root(root: PathBuf) -> Self {
        let project_settings_file = project_settings_file_for(&current_project_dir());
        Self::from_parts(root, project_settings_file, None)
    }

    fn from_parts(
        root: PathBuf,
        project_settings_file: PathBuf,
        local_settings_file: Option<PathBuf>,
    ) -> Self {
        Self {
            cache: root.join("cache"),
            state: root.join("state"),
            sessions: root.join("sessions"),
            checkpoints: root.join("checkpoints"),
            skills: root.join("skills"),
            prompts: root.join("prompts"),
            subagents: root.join("subagents"),
            primary_agents: root.join("primary-agents"),
            user_agents: root.join("AGENTS.md"),
            settings_file: root.join("settings.json"),
            project_settings_file,
            local_settings_file,
            auth_file: root.join("auth.json"),
            root,
        }
    }

    pub fn ensure_runtime_dirs(&self) -> anyhow::Result<()> {
        fs::create_dir_all(&self.cache)?;
        fs::create_dir_all(&self.state)?;
        crate::sessions::prepare_session_root(&self.sessions)?;
        fs::create_dir_all(&self.checkpoints)?;
        Ok(())
    }
}

fn current_project_dir() -> PathBuf {
    env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
}

fn project_settings_file_for(project_dir: &Path) -> PathBuf {
    project_dir.join(".magi-code").join("settings.json")
}

fn resolve_storage_root(mode: RootResolutionMode) -> anyhow::Result<PathBuf> {
    let root = match env::var_os(MC_HOME_ENV) {
        Some(value) => resolve_explicit_mc_home(value, mode)?,
        None => {
            let home = dirs::home_dir().ok_or_else(|| {
                anyhow::anyhow!("could not resolve home directory for ~/.magi-code")
            })?;
            match mode {
                RootResolutionMode::Runtime => default_root_with_migration(&home)?,
                RootResolutionMode::ReadOnly => home.join(".magi-code"),
            }
        }
    };
    validate_storage_root(&root, mode)?;
    Ok(root)
}

fn resolve_explicit_mc_home(
    value: std::ffi::OsString,
    mode: RootResolutionMode,
) -> anyhow::Result<PathBuf> {
    if value.is_empty() {
        anyhow::bail!("{MC_HOME_ENV} must be an absolute directory path, not empty");
    }
    let root = PathBuf::from(value);
    if !root.is_absolute() {
        match mode {
            RootResolutionMode::Runtime => anyhow::bail!(
                "{MC_HOME_ENV} must be an absolute directory path: {}",
                root.display()
            ),
            RootResolutionMode::ReadOnly => {
                anyhow::bail!("{MC_HOME_ENV} must be an absolute directory path");
            }
        }
    }
    Ok(root)
}

fn validate_storage_root(root: &Path, mode: RootResolutionMode) -> anyhow::Result<()> {
    match mode {
        RootResolutionMode::Runtime => {
            if root.exists() && !root.is_dir() {
                anyhow::bail!(
                    "{MC_HOME_ENV} must point to a directory, not a file: {}",
                    root.display()
                );
            }
            Ok(())
        }
        RootResolutionMode::ReadOnly => validate_read_only_mc_home(root),
    }
}

fn validate_read_only_mc_home(root: &Path) -> anyhow::Result<()> {
    match fs::symlink_metadata(root) {
        Ok(metadata) if metadata.file_type().is_dir() => Ok(()),
        Ok(_) => anyhow::bail!("{MC_HOME_ENV} must point to a directory"),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(_) => anyhow::bail!("{MC_HOME_ENV} could not be inspected"),
    }
}

fn default_root_with_migration(home: &Path) -> anyhow::Result<PathBuf> {
    let new_root = home.join(".magi-code");
    let legacy_root = home.join(".mc");
    if new_root.exists() || !legacy_root.is_dir() {
        return Ok(new_root);
    }
    migrate_legacy_default_root(&legacy_root, &new_root)?;
    Ok(new_root)
}

fn migrate_legacy_default_root(legacy_root: &Path, new_root: &Path) -> anyhow::Result<()> {
    match fs::rename(legacy_root, new_root) {
        Ok(()) => Ok(()),
        Err(_) if migration_already_completed(legacy_root, new_root) => Ok(()),
        Err(rename_error) => copy_legacy_root_via_temp(legacy_root, new_root).with_context(|| {
            format!(
                "failed to rename legacy config root {} to {}; fallback copy also failed after rename error: {rename_error}",
                legacy_root.display(),
                new_root.display()
            )
        }),
    }
}

fn migration_already_completed(legacy_root: &Path, new_root: &Path) -> bool {
    new_root.is_dir() && !legacy_root.exists()
}

fn copy_legacy_root_via_temp(legacy_root: &Path, new_root: &Path) -> anyhow::Result<()> {
    let parent = new_root.parent().ok_or_else(|| {
        anyhow::anyhow!(
            "new config root has no parent directory: {}",
            new_root.display()
        )
    })?;
    let temp_root = parent.join(format!(".magi-code.tmp-{}", std::process::id()));

    if temp_root.exists() {
        fs::remove_dir_all(&temp_root).with_context(|| {
            format!(
                "failed to remove stale temp config dir: {}",
                temp_root.display()
            )
        })?;
    }

    if let Err(error) = copy_dir_all(legacy_root, &temp_root) {
        let _ = fs::remove_dir_all(&temp_root);
        return Err(error).with_context(|| {
            format!(
                "failed to copy legacy config root {} to temp dir {}",
                legacy_root.display(),
                temp_root.display()
            )
        });
    }

    if new_root.exists() {
        let _ = fs::remove_dir_all(&temp_root);
        if migration_already_completed(legacy_root, new_root) {
            return Ok(());
        }
        anyhow::bail!(
            "new config root appeared during migration; refusing to overwrite: {}",
            new_root.display()
        );
    }

    if let Err(error) = fs::rename(&temp_root, new_root) {
        let _ = fs::remove_dir_all(&temp_root);
        return Err(error).with_context(|| {
            format!(
                "failed to finalize migrated config root from {} to {}",
                temp_root.display(),
                new_root.display()
            )
        });
    }

    fs::remove_dir_all(legacy_root).with_context(|| {
        format!(
            "migrated config root to {} but failed to remove legacy config root {}; credentials may be duplicated",
            new_root.display(),
            legacy_root.display()
        )
    })?;
    Ok(())
}

fn copy_dir_all(src: &Path, dst: &Path) -> std::io::Result<()> {
    fs::create_dir_all(dst)?;
    for entry in fs::read_dir(src)? {
        let entry = entry?;
        let file_type = entry.file_type()?;
        let from = entry.path();
        let to = dst.join(entry.file_name());
        if file_type.is_dir() {
            copy_dir_all(&from, &to)?;
        } else {
            fs::copy(&from, &to)?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    struct EnvVarSnapshot {
        key: &'static str,
        value: Option<std::ffi::OsString>,
    }

    impl EnvVarSnapshot {
        fn capture(key: &'static str) -> Self {
            let _guard = crate::test_support::env::env_lock();
            Self {
                key,
                value: env::var_os(key),
            }
        }
    }

    impl Drop for EnvVarSnapshot {
        fn drop(&mut self) {
            let env = crate::test_support::env::env_lock();
            match &self.value {
                Some(value) => env.set_var(self.key, value),
                None => env.remove_var(self.key),
            }
        }
    }

    #[test]
    fn from_root_sets_checkpoint_path_under_mc_home() {
        let temp = TempDir::new().unwrap();

        let paths = McPaths::from_root(temp.path().join("mc"));

        assert_eq!(paths.checkpoints, temp.path().join("mc/checkpoints"));
    }

    #[test]
    fn ensure_runtime_dirs_creates_checkpoints_dir() {
        let temp = TempDir::new().unwrap();
        let paths = McPaths::from_root(temp.path().join("mc"));

        paths.ensure_runtime_dirs().unwrap();

        assert!(paths.checkpoints.is_dir());
    }

    #[test]
    fn from_root_defaults_local_settings_file_to_none() {
        let temp = TempDir::new().unwrap();

        let paths = McPaths::from_root(temp.path().join("mc"));

        assert_eq!(paths.local_settings_file, None);
    }

    #[test]
    fn explicit_project_dir_sets_target_and_detects_existing_local_settings() {
        let temp = TempDir::new().unwrap();
        let project_dir = temp.path().join("project");
        fs::create_dir_all(project_dir.join(".magi-code")).unwrap();
        let project_dir = project_dir.canonicalize().unwrap();
        let local_settings = project_dir.join(".magi-code/settings.json");
        fs::write(&local_settings, "{}").unwrap();

        let paths =
            McPaths::from_root_and_project_dir(temp.path().join("global"), project_dir.clone());

        assert_eq!(paths.project_settings_file, local_settings);
        assert_eq!(
            paths.local_settings_file,
            Some(paths.project_settings_file.clone())
        );
    }

    #[test]
    fn explicit_project_dir_is_stable_after_cwd_changes() {
        let temp = TempDir::new().unwrap();
        let first = temp.path().join("first");
        let second = temp.path().join("second");
        fs::create_dir_all(&first).unwrap();
        fs::create_dir_all(&second).unwrap();
        let mut cwd_guard = crate::test_support::env::CurrentDirGuard::capture();
        cwd_guard.set_current_dir(&second).unwrap();

        let paths = McPaths::from_root_and_project_dir(temp.path().join("global"), first.clone());

        assert_eq!(
            paths.project_settings_file,
            first.join(".magi-code/settings.json")
        );
        cwd_guard.restore().unwrap();
    }

    #[test]
    fn resolve_uses_cwd_local_settings_file_when_present() {
        let _mc_home = EnvVarSnapshot::capture("MC_HOME");
        let env_guard = crate::test_support::env::env_lock();
        let temp = TempDir::new().unwrap();
        let mut cwd_guard = crate::test_support::env::CurrentDirGuard::capture();
        let mc_home = temp.path().join("global");
        let cwd = temp.path().join("project");
        let local_dir = cwd.join(".magi-code");
        let local_settings = local_dir.join("settings.json");
        fs::create_dir_all(&local_dir).unwrap();
        fs::write(&local_settings, "{}").unwrap();
        env_guard.set_var("MC_HOME", &mc_home);
        cwd_guard.set_current_dir(&cwd).unwrap();

        let expected_local_settings = env::current_dir()
            .unwrap()
            .join(".magi-code")
            .join("settings.json");

        let paths = McPaths::resolve().unwrap();

        assert_eq!(
            paths.local_settings_file,
            Some(expected_local_settings.clone())
        );
        assert_eq!(paths.project_settings_file, expected_local_settings);
        cwd_guard.restore().unwrap();
    }

    #[test]
    fn resolve_stores_project_settings_target_when_file_missing() {
        let _mc_home = EnvVarSnapshot::capture("MC_HOME");
        let env_guard = crate::test_support::env::env_lock();
        let temp = TempDir::new().unwrap();
        let cwd = temp.path().join("project");
        fs::create_dir_all(&cwd).unwrap();
        let mut cwd_guard = crate::test_support::env::CurrentDirGuard::capture();
        env_guard.set_var("MC_HOME", temp.path().join("global"));
        cwd_guard.set_current_dir(&cwd).unwrap();

        let expected = env::current_dir().unwrap().join(".magi-code/settings.json");
        let paths = McPaths::resolve().unwrap();

        assert_eq!(paths.local_settings_file, None);
        assert_eq!(paths.project_settings_file, expected);
        cwd_guard.restore().unwrap();
    }

    #[test]
    fn resolved_project_settings_target_is_stable_after_cwd_changes() {
        let _mc_home = EnvVarSnapshot::capture("MC_HOME");
        let env_guard = crate::test_support::env::env_lock();
        let temp = TempDir::new().unwrap();
        let first = temp.path().join("first");
        let second = temp.path().join("second");
        fs::create_dir_all(&first).unwrap();
        fs::create_dir_all(&second).unwrap();
        let mut cwd_guard = crate::test_support::env::CurrentDirGuard::capture();
        env_guard.set_var("MC_HOME", temp.path().join("global"));
        cwd_guard.set_current_dir(&first).unwrap();
        let expected = env::current_dir().unwrap().join(".magi-code/settings.json");
        let paths = McPaths::resolve().unwrap();
        cwd_guard.set_current_dir(&second).unwrap();

        assert_eq!(paths.project_settings_file, expected);
        cwd_guard.restore().unwrap();
    }

    #[test]
    fn resolve_does_not_search_parent_for_local_settings_file() {
        let _mc_home = EnvVarSnapshot::capture("MC_HOME");
        let env_guard = crate::test_support::env::env_lock();
        let temp = TempDir::new().unwrap();
        let parent = temp.path().join("parent");
        let child = parent.join("child");
        fs::create_dir_all(parent.join(".magi-code")).unwrap();
        fs::create_dir_all(&child).unwrap();
        fs::write(parent.join(".magi-code").join("settings.json"), "{}").unwrap();
        let mut cwd_guard = crate::test_support::env::CurrentDirGuard::capture();
        env_guard.set_var("MC_HOME", temp.path().join("global"));
        cwd_guard.set_current_dir(&child).unwrap();

        let paths = McPaths::resolve().unwrap();

        assert_eq!(paths.local_settings_file, None);
        cwd_guard.restore().unwrap();
    }

    #[test]
    fn default_root_with_migration_returns_new_default_without_legacy() {
        let temp = TempDir::new().unwrap();

        let root = default_root_with_migration(temp.path()).unwrap();

        assert_eq!(root, temp.path().join(".magi-code"));
        assert!(!root.exists());
        assert!(!temp.path().join(".mc").exists());
    }

    #[test]
    fn default_root_with_migration_migrates_legacy_when_new_root_missing() {
        let temp = TempDir::new().unwrap();
        let legacy = temp.path().join(".mc");
        fs::create_dir_all(&legacy).unwrap();
        fs::write(legacy.join("settings.json"), "settings").unwrap();
        fs::write(legacy.join("auth.json"), "auth").unwrap();

        let root = default_root_with_migration(temp.path()).unwrap();

        assert_eq!(root, temp.path().join(".magi-code"));
        assert_eq!(
            fs::read_to_string(root.join("settings.json")).unwrap(),
            "settings"
        );
        assert_eq!(fs::read_to_string(root.join("auth.json")).unwrap(), "auth");
        assert!(!legacy.exists());
    }

    #[test]
    fn default_root_with_migration_skips_migration_when_new_root_exists() {
        let temp = TempDir::new().unwrap();
        let legacy = temp.path().join(".mc");
        let new = temp.path().join(".magi-code");
        fs::create_dir_all(&legacy).unwrap();
        fs::create_dir_all(&new).unwrap();
        fs::write(legacy.join("settings.json"), "legacy").unwrap();
        fs::write(new.join("settings.json"), "new").unwrap();

        let root = default_root_with_migration(temp.path()).unwrap();

        assert_eq!(root, new);
        assert_eq!(
            fs::read_to_string(root.join("settings.json")).unwrap(),
            "new"
        );
        assert_eq!(
            fs::read_to_string(legacy.join("settings.json")).unwrap(),
            "legacy"
        );
    }

    #[test]
    fn migrate_treats_existing_new_root_without_legacy_as_already_done() {
        let temp = TempDir::new().unwrap();
        let legacy = temp.path().join(".mc");
        let new = temp.path().join(".magi-code");
        fs::create_dir_all(&new).unwrap();
        fs::write(new.join("settings.json"), "new").unwrap();

        migrate_legacy_default_root(&legacy, &new).unwrap();

        assert_eq!(
            fs::read_to_string(new.join("settings.json")).unwrap(),
            "new"
        );
        assert!(!legacy.exists());
    }

    #[test]
    fn resolve_respects_mc_home_without_migration() {
        let _mc_home = EnvVarSnapshot::capture("MC_HOME");
        let env_guard = crate::test_support::env::env_lock();
        let temp = TempDir::new().unwrap();
        let legacy = temp.path().join(".mc");
        let override_root = temp.path().join("override");
        fs::create_dir_all(&legacy).unwrap();
        fs::write(legacy.join("settings.json"), "legacy").unwrap();
        env_guard.set_var("MC_HOME", &override_root);

        let paths = McPaths::resolve().unwrap();

        assert_eq!(paths.root, override_root);
        assert!(legacy.exists());
        assert!(!temp.path().join(".magi-code").exists());
    }

    #[test]
    fn copy_fallback_uses_temp_and_cleans_up_on_success() {
        let temp = TempDir::new().unwrap();
        let legacy = temp.path().join(".mc");
        let new = temp.path().join(".magi-code");
        let nested_dir = legacy.join("subdir").join("nested");
        fs::create_dir_all(&nested_dir).unwrap();
        fs::write(legacy.join("settings.json"), "settings").unwrap();
        fs::write(nested_dir.join("sentinel.txt"), "sentinel").unwrap();

        copy_legacy_root_via_temp(&legacy, &new).unwrap();

        assert_eq!(
            fs::read_to_string(new.join("settings.json")).unwrap(),
            "settings"
        );
        assert_eq!(
            fs::read_to_string(new.join("subdir/nested/sentinel.txt")).unwrap(),
            "sentinel"
        );
        assert!(
            !temp
                .path()
                .join(format!(".magi-code.tmp-{}", std::process::id()))
                .exists()
        );
        assert!(!legacy.exists());
    }

    #[test]
    fn copy_fallback_failure_leaves_legacy_and_no_partial_new_root() {
        let temp = TempDir::new().unwrap();
        let legacy = temp.path().join(".mc");
        let blocked_parent = temp.path().join("blocked-parent");
        let new = blocked_parent.join(".magi-code");
        fs::create_dir_all(&legacy).unwrap();
        fs::write(legacy.join("settings.json"), "legacy").unwrap();
        fs::write(&blocked_parent, "not a directory").unwrap();

        let error = copy_legacy_root_via_temp(&legacy, &new).unwrap_err();

        assert!(
            error
                .to_string()
                .contains("failed to copy legacy config root")
        );
        assert!(legacy.exists());
        assert!(!new.exists());
        assert!(
            !blocked_parent
                .join(format!(".magi-code.tmp-{}", std::process::id()))
                .exists()
        );
    }
    #[test]
    fn resolve_read_only_rejects_existing_mc_home_file_without_path_leak() {
        let _mc_home = EnvVarSnapshot::capture("MC_HOME");
        let env_guard = crate::test_support::env::env_lock();
        let temp = TempDir::new().unwrap();
        let canary = temp.path().join("mc-home-private-canary");
        fs::write(&canary, "not a directory").unwrap();
        env_guard.set_var("MC_HOME", &canary);

        let error = McPaths::resolve_read_only().unwrap_err().to_string();

        assert_eq!(error, "MC_HOME must point to a directory");
        assert!(!error.contains("mc-home-private-canary"));
    }

    #[test]
    fn resolve_read_only_does_not_create_or_migrate_storage() {
        let _mc_home = EnvVarSnapshot::capture("MC_HOME");
        let env_guard = crate::test_support::env::env_lock();
        let temp = TempDir::new().unwrap();
        let root = temp.path().join("new-root");
        let legacy = temp.path().join(".mc");
        fs::create_dir_all(&legacy).unwrap();
        fs::write(legacy.join("settings.json"), "legacy").unwrap();
        env_guard.set_var("MC_HOME", &root);

        let paths = McPaths::resolve_read_only().unwrap();

        assert_eq!(paths.root, root);
        assert!(!paths.root.exists());
        assert!(legacy.exists());
    }

    #[test]
    fn resolve_read_only_captures_project_target_and_existing_local_settings() {
        let _mc_home = EnvVarSnapshot::capture("MC_HOME");
        let env_guard = crate::test_support::env::env_lock();
        let temp = TempDir::new().unwrap();
        let root = temp.path().join("global");
        let project = temp.path().join("project");
        let local_dir = project.join(".magi-code");
        fs::create_dir_all(&local_dir).unwrap();
        let project = project.canonicalize().unwrap();
        let local = project.join(".magi-code/settings.json");
        fs::write(&local, "{}").unwrap();
        env_guard.set_var("MC_HOME", &root);
        let mut cwd_guard = crate::test_support::env::CurrentDirGuard::capture();
        cwd_guard.set_current_dir(&project).unwrap();

        let paths = McPaths::resolve_read_only().unwrap();

        assert_eq!(paths.root, root);
        assert_eq!(paths.project_settings_file, local);
        assert_eq!(
            paths.local_settings_file,
            Some(paths.project_settings_file.clone())
        );
        cwd_guard.restore().unwrap();
    }
}