aft-base 0.67.1

Shared foundation for Agent Foundational Toolkit
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
//! Debug builds may inspect the account's store, but must not change it.
//! Unix protects the effective account's passwd home, independent of HOME/XDG.
//! Windows always protects the process token's profile-derived LocalAppData,
//! independent of HOME/USERPROFILE/LOCALAPPDATA. A successful shell known-folder
//! lookup adds another root; that lookup can reflect redirected or expanded
//! environment paths. If neither OS lookup supplies a root, writes fail closed.

use std::ffi::OsString;
use std::io;
use std::path::{Component, Path, PathBuf};

#[rustfmt::skip]
test_support_visibility! {
pub(crate) const CODE: &str = "dev_build_refused_production_migration";
}

// Resolve an existing ancestor as well as the leaf, which may not exist yet.
pub fn canonicalized_with(
    path: &Path,
    canonicalize: &impl Fn(&Path) -> Option<PathBuf>,
) -> PathBuf {
    for ancestor in path.ancestors() {
        if let Some(canonical) = canonicalize(ancestor) {
            if let Ok(tail) = path.strip_prefix(ancestor) {
                return canonical.join(tail);
            }
        }
    }
    path.to_path_buf()
}

pub(crate) fn comparison_key(path: &Path, windows: bool) -> Vec<OsString> {
    if windows {
        crate::windows_path::normalize_windows_path(path)
            .to_string_lossy()
            .trim_end_matches('\\')
            .split('\\')
            .map(|part| OsString::from(part.to_lowercase()))
            .collect()
    } else {
        path.components()
            .map(|part| part.as_os_str().into())
            .collect()
    }
}

pub(crate) fn is_within(path: &Path, parent: &Path) -> bool {
    fn absolute_normalized(path: &Path) -> io::Result<PathBuf> {
        let absolute = if path.is_absolute() {
            path.to_path_buf()
        } else {
            std::env::current_dir()
                .map_err(|error| {
                    io::Error::new(
                        error.kind(),
                        format!("storage fence current-directory lookup failed: {error}"),
                    )
                })?
                .join(path)
        };
        let mut normalized = PathBuf::new();
        for component in absolute.components() {
            match component {
                Component::CurDir => (),
                Component::ParentDir => {
                    normalized.pop();
                }
                _ => normalized.push(component),
            }
        }
        Ok(normalized)
    }
    let canonicalize = |path: &Path| path.canonicalize().ok();
    let Ok(path) = absolute_normalized(&canonicalized_with(path, &canonicalize)) else {
        return true;
    };
    let Ok(parent) = absolute_normalized(&canonicalized_with(parent, &canonicalize)) else {
        return true;
    };
    comparison_key(&path, cfg!(windows)).starts_with(&comparison_key(&parent, cfg!(windows)))
}

#[cfg(unix)]
pub fn account_home() -> io::Result<PathBuf> {
    use std::os::unix::ffi::OsStrExt;
    let mut buffer = vec![0u8; 16384];
    loop {
        let mut entry = std::mem::MaybeUninit::<libc::passwd>::uninit();
        let mut result = std::ptr::null_mut();
        // SAFETY: entry and buffer are writable for the supplied sizes.
        let error = unsafe {
            libc::getpwuid_r(
                libc::geteuid(),
                entry.as_mut_ptr(),
                buffer.as_mut_ptr().cast(),
                buffer.len(),
                &mut result,
            )
        };
        if error == libc::ERANGE {
            if buffer.len() >= 1024 * 1024 {
                return Err(io::Error::other(
                    "getpwuid_r storage fence lookup exceeded its buffer limit",
                ));
            }
            buffer.resize(buffer.len() * 2, 0);
            continue;
        }
        if error != 0 || result.is_null() {
            return Err(io::Error::other(format!(
                "getpwuid_r storage fence lookup failed (status {error}, no entry: {})",
                result.is_null()
            )));
        }
        // SAFETY: getpwuid_r initialized result on success.
        if unsafe { (*result).pw_dir.is_null() } {
            return Err(io::Error::other(
                "getpwuid_r storage fence lookup returned no home",
            ));
        }
        // SAFETY: a successful lookup supplies a NUL-terminated pw_dir in buffer.
        let home = unsafe { std::ffi::CStr::from_ptr((*result).pw_dir) };
        return valid_account_path(
            PathBuf::from(std::ffi::OsStr::from_bytes(home.to_bytes())),
            "getpwuid_r",
        );
    }
}

#[cfg(windows)]
pub fn account_home() -> io::Result<PathBuf> {
    use std::os::windows::ffi::OsStringExt;
    use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
    use windows_sys::Win32::Security::TOKEN_QUERY;
    use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
    use windows_sys::Win32::UI::Shell::GetUserProfileDirectoryW;

    struct Token(HANDLE);
    impl Drop for Token {
        fn drop(&mut self) {
            // SAFETY: this handle belongs to the successful OpenProcessToken call.
            unsafe {
                CloseHandle(self.0);
            }
        }
    }
    let mut token = std::ptr::null_mut();
    // SAFETY: the current process pseudo-handle is valid and token is writable.
    if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
        return Err(io::Error::other(format!(
            "OpenProcessToken(TOKEN_QUERY) storage fence lookup failed: {}",
            io::Error::last_os_error()
        )));
    }
    let token = Token(token);
    let mut size = 0;
    // SAFETY: a null buffer queries the required UTF-16 buffer size.
    unsafe {
        GetUserProfileDirectoryW(token.0, std::ptr::null_mut(), &mut size);
    }
    if size == 0 || size > 32768 {
        return Err(io::Error::other(format!(
            "GetUserProfileDirectoryW storage fence size lookup failed (size {size}): {}",
            io::Error::last_os_error()
        )));
    }
    let mut buffer = vec![0u16; size as usize];
    // SAFETY: the buffer has the size supplied by the profile API.
    if unsafe { GetUserProfileDirectoryW(token.0, buffer.as_mut_ptr(), &mut size) } == 0 {
        return Err(io::Error::other(format!(
            "GetUserProfileDirectoryW storage fence lookup failed: {}",
            io::Error::last_os_error()
        )));
    }
    let len = buffer.iter().position(|unit| *unit == 0).ok_or_else(|| {
        io::Error::other("GetUserProfileDirectoryW returned an unterminated path")
    })?;
    valid_account_path(
        PathBuf::from(OsString::from_wide(&buffer[..len])),
        "GetUserProfileDirectoryW",
    )
}

#[cfg(windows)]
pub(crate) fn known_local_app_data() -> io::Result<PathBuf> {
    use std::os::windows::ffi::OsStringExt;
    use windows_sys::Win32::System::Com::CoTaskMemFree;
    use windows_sys::Win32::UI::Shell::{
        FOLDERID_LocalAppData, SHGetKnownFolderPath, KF_FLAG_DONT_VERIFY,
    };
    struct FolderPath(*mut u16);
    impl Drop for FolderPath {
        fn drop(&mut self) {
            // SAFETY: shell paths use the COM allocator; freeing null is allowed.
            unsafe {
                CoTaskMemFree(self.0.cast());
            }
        }
    }
    let mut raw = std::ptr::null_mut();
    // SAFETY: the GUID is valid and raw is writable. Do not require existence:
    // a harness may redirect the shell's expanded profile to a missing folder.
    let status = unsafe {
        SHGetKnownFolderPath(
            &FOLDERID_LocalAppData,
            KF_FLAG_DONT_VERIFY as u32,
            std::ptr::null_mut(),
            &mut raw,
        )
    };
    let path = FolderPath(raw);
    if status < 0 || path.0.is_null() {
        return Err(io::Error::other(format!("SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_DONT_VERIFY) storage fence lookup failed (HRESULT 0x{:08x})", status as u32)));
    }
    let mut len = 0;
    // SAFETY: a successful shell lookup returns an allocated NUL-terminated path.
    while unsafe { *path.0.add(len) } != 0 {
        len += 1;
    }
    // SAFETY: the scan above found the end of the allocated path.
    let units = unsafe { std::slice::from_raw_parts(path.0, len) };
    valid_account_path(
        PathBuf::from(OsString::from_wide(units)),
        "SHGetKnownFolderPath",
    )
}

fn valid_account_path(path: PathBuf, lookup: &str) -> io::Result<PathBuf> {
    if !path.is_absolute() {
        return Err(io::Error::other(format!(
            "{lookup} storage fence lookup returned an empty or relative path"
        )));
    }
    Ok(path)
}

pub(crate) fn account_storage_roots() -> io::Result<Vec<PathBuf>> {
    #[cfg(windows)]
    {
        combine_windows_roots(account_home(), known_local_app_data())
    }
    #[cfg(unix)]
    {
        Ok(vec![account_home()?.join(".local/share/cortexkit/aft")])
    }
}

#[cfg(any(windows, any(test, feature = "test-support")))]
#[cfg_attr(not(test), allow(dead_code))]
fn combine_windows_roots(
    profile: io::Result<PathBuf>,
    local_data: io::Result<PathBuf>,
) -> io::Result<Vec<PathBuf>> {
    let mut roots = Vec::new();
    let mut errors = Vec::new();
    match profile {
        Ok(profile) => roots.push(profile.join("AppData/Local/cortexkit/aft")),
        Err(error) => errors.push(error.to_string()),
    }
    match local_data {
        Ok(data) => roots.push(data.join("cortexkit/aft")),
        Err(error) => errors.push(error.to_string()),
    }
    if roots.is_empty() {
        return Err(io::Error::other(format!(
            "no protected account storage root resolved: {}",
            errors.join("; ")
        )));
    }
    Ok(roots)
}

fn migration_opt_in() -> bool {
    let lookup = |name: &str| {
        #[cfg(any(test, feature = "test-support"))]
        if let Some((_, allow)) = TEST_ACCOUNT.with(|slot| slot.borrow().clone()) {
            // Supply an environment lookup, not a policy override: the opt-in
            // test must exercise the same variable name and exact-value check.
            return (allow && name == "AFT_ALLOW_PRODUCTION_MIGRATION")
                .then(|| OsString::from("1"));
        }
        std::env::var_os(name)
    };
    lookup("AFT_ALLOW_PRODUCTION_MIGRATION").as_deref() == Some(std::ffi::OsStr::new("1"))
}

pub fn protected(path: &Path) -> bool {
    protection_status_with(path, account_storage_roots).unwrap_or(true)
}

/// The account's own CortexKit config directories, derived from the OS
/// account record like [`account_storage_roots`] and never from HOME, XDG or
/// USERPROFILE. The user config file AFT reads by default lives under one of
/// them (`~/.config/cortexkit/aft.jsonc`; on Windows the profile's
/// `.config` or roaming `AppData` folder).
pub(crate) fn account_config_roots() -> io::Result<Vec<PathBuf>> {
    let home = account_home()?;
    #[cfg(windows)]
    {
        Ok(vec![
            home.join(".config/cortexkit"),
            home.join("AppData/Roaming/cortexkit"),
        ])
    }
    #[cfg(not(windows))]
    {
        Ok(vec![home.join(".config/cortexkit")])
    }
}

/// Why this build must not rewrite the config file at `path`, or `None` when
/// it may. A debug build (a test run, or the `target/debug/aft` a test spawns)
/// that inherited the operator's real HOME would otherwise rewrite the
/// operator's own config file when it migrates retired keys. Same policy as
/// the storage fence: release builds are never refused,
/// `AFT_ALLOW_PRODUCTION_MIGRATION=1` opts in, and a failed account lookup
/// refuses.
pub(crate) fn config_write_refusal(path: &Path) -> Option<String> {
    match protection_status_with(path, account_config_roots) {
        Ok(false) => None,
        Ok(true) => Some(format!(
            "{CODE}: a dev/test build does not rewrite the account's own config file; set AFT_ALLOW_PRODUCTION_MIGRATION=1 to allow it"
        )),
        Err(error) => Some(format!(
            "{CODE}: a dev/test build could not resolve the account's config directory ({error}), so it does not rewrite config files; set AFT_ALLOW_PRODUCTION_MIGRATION=1 to allow it"
        )),
    }
}

fn protection_status_with(
    path: &Path,
    roots: impl FnOnce() -> io::Result<Vec<PathBuf>>,
) -> io::Result<bool> {
    // Tests and development rigs normally run debug builds (including the
    // target/debug/aft children of Bun tests). Release builds must be allowed
    // automatically: packaging cannot depend on remembering extra opt-ins.
    if !cfg!(debug_assertions) {
        return Ok(false);
    }
    if migration_opt_in() {
        return Ok(false);
    }
    #[cfg(any(test, feature = "test-support"))]
    if let Some((root, _)) = TEST_ACCOUNT.with(|slot| slot.borrow().clone()) {
        return Ok(is_within(path, &root));
    }
    Ok(roots()?.iter().any(|root| is_within(path, root)))
}

pub fn refuse_write(path: &Path) -> io::Result<()> {
    refuse_write_for_status(path, protection_status_with(path, account_storage_roots))
}

fn refuse_write_for_status(path: &Path, status: io::Result<bool>) -> io::Result<()> {
    if !matches!(status, Ok(false)) {
        let reason = status
            .err()
            .map(|error| format!("; unresolved protected-root lookup: {error}"))
            .unwrap_or_default();
        Err(io::Error::new(io::ErrorKind::PermissionDenied, format!(
            "{CODE}: dev/test build refused to migrate production storage or write a versioned record at {}{reason}; use a disposable storage root or explicitly set AFT_ALLOW_PRODUCTION_MIGRATION=1", path.display()
        )))
    } else {
        Ok(())
    }
}

#[cfg(any(test, feature = "test-support"))]
thread_local! {
    static TEST_ACCOUNT: std::cell::RefCell<Option<(PathBuf, bool)>> = const { std::cell::RefCell::new(None) };
}

/// Thread-local OS-directory seam, never available to a spawned binary.
#[cfg(any(test, feature = "test-support"))]
pub fn with_test_account<T>(root: &Path, allow: bool, run: impl FnOnce() -> T) -> T {
    struct Restore(Option<(PathBuf, bool)>);
    impl Drop for Restore {
        fn drop(&mut self) {
            TEST_ACCOUNT.with(|slot| *slot.borrow_mut() = self.0.take());
        }
    }
    let _restore =
        Restore(TEST_ACCOUNT.with(|slot| slot.replace(Some((root.to_path_buf(), allow)))));
    run()
}

pub fn resolve_account_home_dir() -> Option<PathBuf> {
    #[cfg(unix)]
    let home = crate::production_storage::account_home().ok()?;
    #[cfg(windows)]
    let home = resolve_windows_profile_dir().ok()?;

    let canonical = std::fs::canonicalize(home).ok()?;
    canonical.is_dir().then_some(canonical)
}

#[cfg(windows)]
fn resolve_windows_profile_dir() -> std::io::Result<PathBuf> {
    use std::os::windows::ffi::OsStringExt;
    use windows_sys::Win32::System::Com::CoTaskMemFree;
    use windows_sys::Win32::UI::Shell::{
        FOLDERID_Profile, SHGetKnownFolderPath, KF_FLAG_DONT_VERIFY,
    };

    struct FolderPath(*mut u16);
    impl Drop for FolderPath {
        fn drop(&mut self) {
            // SAFETY: SHGetKnownFolderPath allocates its result with the COM allocator.
            unsafe { CoTaskMemFree(self.0.cast()) };
        }
    }

    let mut raw = std::ptr::null_mut();
    // SAFETY: the folder identifier is valid and raw is writable.
    let status = unsafe {
        SHGetKnownFolderPath(
            &FOLDERID_Profile,
            KF_FLAG_DONT_VERIFY as u32,
            std::ptr::null_mut(),
            &mut raw,
        )
    };
    let path = FolderPath(raw);
    if status < 0 || path.0.is_null() {
        return Err(std::io::Error::other(format!(
            "SHGetKnownFolderPath(FOLDERID_Profile) lookup failed (HRESULT 0x{:08x})",
            status as u32
        )));
    }
    let mut len = 0;
    // SAFETY: a successful lookup returns an allocated NUL-terminated path.
    while unsafe { *path.0.add(len) } != 0 {
        len += 1;
    }
    // SAFETY: the scan above found the end of the allocated path.
    let units = unsafe { std::slice::from_raw_parts(path.0, len) };
    Ok(PathBuf::from(std::ffi::OsString::from_wide(units)))
}

#[cfg(any(test, feature = "test-support"))]
#[cfg_attr(not(test), allow(dead_code, unused_imports))]
pub mod tests {
    use super::*;

    pub fn old_database(root: &Path) -> PathBuf {
        std::fs::create_dir_all(root).unwrap();
        let path = root.join("aft.db");
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute_batch("CREATE TABLE schema_version (version INTEGER NOT NULL PRIMARY KEY); INSERT INTO schema_version VALUES (0);").unwrap();
        drop(conn);
        path
    }

    #[test]
    fn windows_root_union_keeps_profile_and_redirected_local_data() {
        let fixture = tempfile::tempdir().unwrap();
        let profile = fixture.path().join("profile");
        let redirected = fixture.path().join("redirected-local");
        let roots = combine_windows_roots(Ok(profile.clone()), Ok(redirected.clone())).unwrap();
        assert_eq!(
            roots,
            vec![
                profile.join("AppData/Local/cortexkit/aft"),
                redirected.join("cortexkit/aft")
            ]
        );
        let fallback = combine_windows_roots(
            Ok(profile.clone()),
            Err(io::Error::other("SHGetKnownFolderPath unavailable")),
        )
        .unwrap();
        assert_eq!(fallback, vec![profile.join("AppData/Local/cortexkit/aft")]);
        let shell_only = combine_windows_roots(
            Err(io::Error::other("GetUserProfileDirectoryW unavailable")),
            Ok(redirected.clone()),
        )
        .unwrap();
        assert_eq!(shell_only, vec![redirected.join("cortexkit/aft")]);
    }

    #[cfg(debug_assertions)]
    #[test]
    fn unresolved_account_roots_refuse_writes_without_panicking() {
        let fixture = tempfile::tempdir().unwrap();
        let path = fixture.path().join("never-created");
        let roots = combine_windows_roots(
            Err(io::Error::other("GetUserProfileDirectoryW lookup failed")),
            Err(io::Error::other("SHGetKnownFolderPath lookup failed")),
        );
        let status = protection_status_with(&path, || roots);
        let error = refuse_write_for_status(&path, status).unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
        let reason = error.to_string();
        assert!(reason.contains(CODE), "{reason}");
        assert!(reason.contains("GetUserProfileDirectoryW"), "{reason}");
        assert!(reason.contains("SHGetKnownFolderPath"), "{reason}");
        assert!(!path.exists());
    }

    #[cfg(debug_assertions)]
    struct RestoreEnvironment(Vec<(&'static str, Option<OsString>)>);
    #[cfg(debug_assertions)]
    impl RestoreEnvironment {
        fn replace(values: &[(&'static str, &Path)]) -> Self {
            let restore = Self(
                values
                    .iter()
                    .map(|(name, _)| (*name, std::env::var_os(name)))
                    .collect(),
            );
            for (name, path) in values {
                std::env::set_var(name, path);
            }
            restore
        }
    }
    #[cfg(debug_assertions)]
    impl Drop for RestoreEnvironment {
        fn drop(&mut self) {
            for (name, value) in &self.0 {
                match value {
                    Some(value) => std::env::set_var(name, value),
                    None => std::env::remove_var(name),
                }
            }
        }
    }

    #[cfg(all(windows, debug_assertions))]
    #[test]
    fn windows_token_profile_is_protected_with_missing_home_environment() {
        use windows_sys::Win32::UI::Shell::{
            SHGetFolderPathW, CSIDL_LOCAL_APPDATA, SHGFP_TYPE_CURRENT,
        };
        let _env = crate::test_env::process_env_lock();
        let profile = account_home().expect("process token supplies the real account profile");
        let fixture = tempfile::tempdir().unwrap();
        let missing_home = fixture.path().join("nonexistent-profile");
        let missing_local = fixture.path().join("nonexistent-local-appdata");
        let _restore = RestoreEnvironment::replace(&[
            ("HOME", &missing_home),
            ("USERPROFILE", &missing_home),
            ("LOCALAPPDATA", &missing_local),
        ]);
        assert_eq!(
            account_home().unwrap(),
            profile,
            "token lookup must ignore substituted environment homes"
        );
        let roots = account_storage_roots()
            .expect("token root must survive failed or redirected shell lookup");
        let expected = profile.join("AppData/Local/cortexkit/aft");
        assert!(
            roots.contains(&expected),
            "token profile root missing: {roots:?}"
        );
        assert!(protected(&expected.join("aft.db")));
        assert!(refuse_write(&expected.join("aft.db"))
            .unwrap_err()
            .to_string()
            .contains(CODE));
        assert!(refuse_write(&fixture.path().join("disposable-storage/aft.db")).is_ok());
        assert!(!missing_home.exists());
        assert!(!missing_local.exists());

        let mut old_buffer = [0u16; 260];
        // SAFETY: the legacy API's MAX_PATH-sized buffer is writable. This probe
        // records its verification failure, never uses it as the fence's root.
        let old_status = unsafe {
            SHGetFolderPathW(
                std::ptr::null_mut(),
                CSIDL_LOCAL_APPDATA as i32,
                std::ptr::null_mut(),
                SHGFP_TYPE_CURRENT as u32,
                old_buffer.as_mut_ptr(),
            )
        };
        eprintln!("legacy SHGetFolderPathW without DONT_VERIFY: HRESULT=0x{:08x}; token-profile roots={roots:?}", old_status as u32);
    }

    #[cfg(all(unix, debug_assertions))]
    #[test]
    fn unix_account_root_is_protected_with_missing_home_environment() {
        let _env = crate::test_env::process_env_lock();
        let home = account_home().expect("passwd supplies the effective account home");
        let fixture = tempfile::tempdir().unwrap();
        let missing = fixture.path().join("nonexistent-home");
        let _restore =
            RestoreEnvironment::replace(&[("HOME", &missing), ("XDG_DATA_HOME", &missing)]);
        assert_eq!(account_home().unwrap(), home);
        let root = home.join(".local/share/cortexkit/aft");
        assert_eq!(account_storage_roots().unwrap(), vec![root.clone()]);
        assert!(protected(&root.join("aft.db")));
        assert!(refuse_write(&root.join("aft.db"))
            .unwrap_err()
            .to_string()
            .contains(CODE));
        assert!(refuse_write(&fixture.path().join("disposable-storage/aft.db")).is_ok());
        assert!(!missing.exists());
    }

    #[cfg(all(unix, debug_assertions))]
    #[test]
    fn production_alias_and_relative_tail_cannot_bypass_fence() {
        let fixture = tempfile::tempdir().unwrap();
        let root = fixture.path().join("production");
        std::fs::create_dir_all(&root).unwrap();
        let alias = fixture.path().join("alias");
        std::os::unix::fs::symlink(&root, &alias).unwrap();
        with_test_account(&root, false, || {
            assert!(refuse_write(&alias.join("uncreated/../aft.db")).is_err());
            assert!(refuse_write(&fixture.path().join("production-sibling/aft.db")).is_ok());
        });
    }

    #[cfg(all(unix, debug_assertions))]
    #[test]
    fn unix_account_config_root_ignores_home_and_xdg() {
        let _env = crate::test_env::process_env_lock();
        let home = account_home().expect("passwd supplies the effective account home");
        let fixture = tempfile::tempdir().unwrap();
        let missing = fixture.path().join("nonexistent-home");
        let _restore =
            RestoreEnvironment::replace(&[("HOME", &missing), ("XDG_CONFIG_HOME", &missing)]);
        let root = home.join(".config/cortexkit");
        assert_eq!(account_config_roots().unwrap(), vec![root.clone()]);
        // Only computes the verdict; nothing under the real directory is touched.
        assert!(config_write_refusal(&root.join("aft.jsonc"))
            .unwrap()
            .contains(CODE));
        assert!(config_write_refusal(&missing.join(".config/cortexkit/aft.jsonc")).is_none());
        assert!(!missing.exists());
    }

    #[test]
    fn config_write_fence_matches_build_debug_assertions() {
        let fixture = tempfile::tempdir().unwrap();
        let path = fixture.path().join("aft.jsonc");
        with_test_account(fixture.path(), false, || {
            assert_eq!(
                config_write_refusal(&path).is_some(),
                cfg!(debug_assertions)
            );
        });
        with_test_account(fixture.path(), true, || {
            assert!(
                config_write_refusal(&path).is_none(),
                "the opt-in allows it"
            );
        });
    }

    #[test]
    fn production_write_fence_matches_build_debug_assertions() {
        let fixture = tempfile::tempdir().unwrap();
        with_test_account(fixture.path(), false, || {
            assert_eq!(
                protected(&fixture.path().join("aft.db")),
                cfg!(debug_assertions)
            );
        });
    }
}