Refine macOS/LogAlias platform tuning, fix a real WithRoot bug found on Windows

Platform tuning:
- macOS Desktop's RuntimeDir() now prefers $TMPDIR (the OS-managed,
  per-user ephemeral directory NSTemporaryDirectory() returns) over
  the previous ~/Library/Application Support/<App>/Runtime placeholder.
- Resolver.EnsureLogAlias() creates the optional LogAliasDir() symlink
  to LogDir(), idempotently, leaving any pre-existing entry alone.

Verified the SHGetKnownFolderPath fallback (knownfolders_windows.go)
on a real Windows host for the first time: with APPDATA/LOCALAPPDATA/
PROGRAMDATA all unset, it correctly resolves the real known folders.
go vet's one unsafeptr finding there is a documented, permanent,
unavoidable characteristic of this raw-syscall pattern, not a bug.

That same real-Windows run surfaced a genuine, previously-invisible
bug: WithRoot assumed root's own address family always matched the
*simulated* platform's, which silently broke (mixed separators, or an
outright invalid mid-path drive letter) whenever the real host's
native family differed from what WithPlatform was simulating -- e.g.
WithPlatform("linux") with WithRoot(t.TempDir()) on a real Windows
host. This was invisible on macOS/Linux, where t.TempDir() happens to
already share the simulated Unix family.

Fixed applyRoot (now applyRootRebase) to decompose the resolved path
into segments and re-join them onto root using root's own family,
inferred from its content like JoinDirFile already does, not from the
simulated platform. Two call sites chaining onto an already-rooted
value (logDirUnix, darwin.go's State/Runtime fallback) switched from a
hardcoded unixJoin to JoinDirFile for the same reason. core/config's
working-directory layer had the identical bug one level up; fixed via
a new paths.JoinDirFileFamily.

TODO.md/ARCHITECTURE.md/README.md updated accordingly; core/TODO.md's
remaining items are now all explicitly out-of-scope or deliberately
deprioritized, not open work.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
terminarandClaude Sonnet 5 committed 2026-09-20 16:37:30 +02:00
1 parent e6b5324ad3
commit da2ec85381
13 files changed
+515 -70

No files matched your search

+4 -4
View File
@@ -136,10 +136,10 @@ func (r *Resolver) logDirValue() (value, error) {
}
// LogAliasDir returns the optional Unix convenience location
// ~/.local/log/<app> (spec section 39). It is never created
// automatically; nothing else in this package treats it as canonical.
// On Windows and macOS Desktop it is the same as LogDir (there is no
// separate alias convention there).
// ~/.local/log/<app> (spec section 39). Resolving it never creates
// anything -- use EnsureLogAlias for that; nothing else in this package
// treats it as canonical. On Windows and macOS Desktop it is the same as
// LogDir (there is no separate alias convention there).
func (r *Resolver) LogAliasDir() (string, error) {
if r.isWindows() || r.isDarwinDesktop() {
return r.LogDir()
+100 -1
View File
@@ -103,11 +103,110 @@ func TestLogAliasDirWindowsFallsBackToLogDir(t *testing.T) {
}
}
func TestEnsureLogAliasCreatesSymlink(t *testing.T) {
root := t.TempDir()
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env), WithRoot(root))
alias, err := r.EnsureLogAlias()
if err != nil {
t.Fatalf("EnsureLogAlias: %v", err)
}
wantAlias, err := r.LogAliasDir()
if err != nil {
t.Fatalf("LogAliasDir: %v", err)
}
if alias != wantAlias {
t.Errorf("EnsureLogAlias() = %q, want %q", alias, wantAlias)
}
info, err := os.Lstat(alias)
if err != nil {
t.Fatalf("Lstat(%q): %v", alias, err)
}
if info.Mode()&os.ModeSymlink == 0 {
t.Fatalf("%q was not created as a symlink", alias)
}
target, err := os.Readlink(alias)
if err != nil {
t.Fatalf("Readlink(%q): %v", alias, err)
}
logDir, err := r.LogDir()
if err != nil {
t.Fatalf("LogDir: %v", err)
}
if target != logDir {
t.Errorf("symlink target = %q, want %q", target, logDir)
}
// Idempotent: a second call must not fail or touch the existing link.
if _, err := r.EnsureLogAlias(); err != nil {
t.Fatalf("EnsureLogAlias (second call): %v", err)
}
}
func TestEnsureLogAliasLeavesExistingEntryAlone(t *testing.T) {
root := t.TempDir()
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env), WithRoot(root))
alias, err := r.LogAliasDir()
if err != nil {
t.Fatalf("LogAliasDir: %v", err)
}
if err := os.MkdirAll(alias, 0o700); err != nil {
t.Fatalf("MkdirAll(%q): %v", alias, err)
}
got, err := r.EnsureLogAlias()
if err != nil {
t.Fatalf("EnsureLogAlias: %v", err)
}
if got != alias {
t.Errorf("EnsureLogAlias() = %q, want %q", got, alias)
}
info, err := os.Lstat(alias)
if err != nil || !info.IsDir() {
t.Errorf("pre-existing directory at %q was replaced (err=%v)", alias, err)
}
}
func TestEnsureLogAliasWindowsEqualsLogDir(t *testing.T) {
root := t.TempDir()
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(windowsEnv()), WithRoot(root))
alias, err := r.EnsureLogAlias()
if err != nil {
t.Fatalf("EnsureLogAlias: %v", err)
}
logDir, err := r.LogDir()
if err != nil {
t.Fatalf("LogDir: %v", err)
}
if alias != logDir {
t.Errorf("EnsureLogAlias() = %q, want %q (LogDir)", alias, logDir)
}
}
func TestDarwinDesktopRuntimeDirPrefersTMPDIR(t *testing.T) {
env := map[string]string{"HOME": "/Users/test", "TMPDIR": "/var/folders/zz/T/"}
app := core.Application{Name: "yapama", Kind: core.Desktop}
r := mustResolver(t, app, WithPlatform("darwin"), WithEnvironment(env))
if got, err := r.RuntimeDir(); err != nil || got != "/var/folders/zz/T/yapama" {
t.Errorf("RuntimeDir() = (%q, %v), want /var/folders/zz/T/yapama", got, err)
}
}
func TestEnsureAllCategories(t *testing.T) {
root := t.TempDir()
env := map[string]string{"HOME": "/home/test"}
// WithRuntimeDir takes a bare path in the simulated platform's
// family (here Linux/Unix); applyRoot nests it under root exactly
// once -- pre-pending root here too would double-root it (and, on a
// real Windows host where root is itself Windows-native, produce an
// invalid mid-path drive letter).
r := mustResolver(t, yetApp(), WithPlatform("linux"), WithEnvironment(env), WithRoot(root),
WithRuntimeDir(root+"/runtime-override"))
WithRuntimeDir("/runtime-override"))
ensures := []func() (string, error){
r.EnsureConfigDir, r.EnsureDataDir, r.EnsureStateDir,
+19 -2
View File
@@ -80,7 +80,11 @@ func (r *Resolver) darwinDesktopStateDir() (value, error) {
if err != nil {
return value{}, err
}
return value{path: unixJoin(app.path, "State"), source: app.source}, nil
// app.path already applied the root (see applyRootRebase), which can
// be a different address family than this simulated platform -- use
// JoinDirFile, not unixJoin, so the "State" suffix lands in whichever
// family app.path actually ended up in.
return value{path: JoinDirFile(app.path, "State"), source: app.source}, nil
}
func (r *Resolver) darwinDesktopCacheDir() (value, error) {
@@ -113,15 +117,28 @@ func (r *Resolver) darwinDesktopLogDir() (value, error) {
return value{path: r.applyRoot(unixJoin(darwinLogsBase(r.app.Scope, home), r.app.Name)), source: source}, nil
}
// darwinDesktopRuntimeDir prefers $TMPDIR -- the per-user, securely
// permissioned, OS-managed ephemeral directory macOS itself hands every
// process (confstr(_CS_DARWIN_USER_TEMP_DIR), what NSTemporaryDirectory()
// returns), the closest real native equivalent to XDG_RUNTIME_DIR's
// role. It falls back to the previous Application Support-based location
// only when TMPDIR is unset in the resolved environment (e.g. a
// simulated/test environment that never set it) -- see AGENTS.md TODO
// history: this was a placeholder before TMPDIR was wired in here.
func (r *Resolver) darwinDesktopRuntimeDir() (value, error) {
if v, ok := r.overrideValue(RuntimePath); ok {
return value{path: r.applyRoot(v.path), source: v.source}, nil
}
if tmpdir, ok := lookup(r.env, "TMPDIR"); ok {
return value{path: r.applyRoot(unixJoin(tmpdir, r.app.Name)), source: MacOSNative}, nil
}
app, err := r.darwinDesktopAppDir()
if err != nil {
return value{}, err
}
return value{path: unixJoin(app.path, "Runtime"), source: app.source}, nil
// See darwinDesktopStateDir: app.path is already rooted and may be in
// either address family, so JoinDirFile picks the right one.
return value{path: JoinDirFile(app.path, "Runtime"), source: app.source}, nil
}
// darwinDesktopBinDir has no native GUI-app convention; it reuses the
+81 -14
View File
@@ -76,6 +76,22 @@ func JoinFamily(platform string, elems ...string) string {
return unixJoin(elems...)
}
// JoinDirFileFamily joins dir and name like JoinDirFile (inferring the
// family from dir's own content when it contains a separator of either
// kind), falling back to platform's family (as JoinFamily does) only
// when dir is ambiguous -- has no separator of its own to infer from,
// such as a bare "." (core/config's default working-directory layer
// before WithWorkdirPath overrides it). Prefer this over JoinFamily
// whenever dir might come from a real filesystem path (e.g. WithRoot's
// root, or a caller-supplied override) rather than always being a
// hardcoded literal in platform's own family.
func JoinDirFileFamily(platform, dir, name string) string {
if !strings.ContainsRune(dir, '/') && !strings.ContainsRune(dir, '\\') {
return JoinFamily(platform, dir, name)
}
return JoinDirFile(dir, name)
}
// JoinDirFile joins a directory (as produced by ConfigSearchDirs/
// DataSearchDirs/ExecutableSearchDirs, in either address family) with a
// plain file name, picking the join style from the directory's own
@@ -113,24 +129,75 @@ func splitWindowsRoot(p string) (root, rest string, ok bool) {
return "", "", false
}
// applyRootUnix rebases an absolute unix-family path under root, when
// root is set. An empty root leaves p untouched.
func applyRootUnix(root, p string) string {
if root == "" {
return p
}
return unixJoin(root, strings.TrimPrefix(p, "/"))
// isWindowsPath reports whether p looks like a Windows-family path
// (backslash-separated, no forward slash) -- the same content-based
// heuristic JoinDirFile uses, applied here to root rather than to a
// resolved category directory.
func isWindowsPath(p string) bool {
return strings.ContainsRune(p, '\\') && !strings.ContainsRune(p, '/')
}
// applyRootWindows rebases an absolute windows-family path under root,
// when root is set. An empty root leaves p untouched.
func applyRootWindows(root, p string) string {
// pathSegments splits an absolute path p (in the given family) into its
// plain path components, discarding p's own absolute-path root marker
// (a leading "/" for Unix; a drive letter or UNC share for Windows).
func pathSegments(p string, windowsFamily bool) []string {
if windowsFamily {
rest := p
if _, r, ok := splitWindowsRoot(p); ok {
rest = r
}
return splitNonEmpty(rest, '\\')
}
return splitNonEmpty(strings.TrimPrefix(p, "/"), '/')
}
// dirName returns p's parent directory, picking "/"- or "\"-based
// splitting from p's own content (the same heuristic JoinDirFile uses)
// rather than the host OS's path/filepath conventions -- a resolved
// path's family depends on WithRoot's root, not on the host this code
// happens to run on (see applyRootRebase), so path/filepath (or the
// stdlib "path" package) would silently pick the wrong separator, or
// none at all, whenever the two differ.
func dirName(p string) string {
sep := byte('/')
if isWindowsPath(p) {
sep = '\\'
}
if i := strings.LastIndexByte(p, sep); i >= 0 {
return p[:i]
}
return "."
}
func splitNonEmpty(s string, sep byte) []string {
var out []string
for part := range strings.SplitSeq(s, string(sep)) {
if part != "" {
out = append(out, part)
}
}
return out
}
// applyRootRebase rebases p -- an absolute path in the family denoted by
// pIsWindows (r.platform's *simulated* family) -- under root, when root
// is set. root is always in the REAL host's native family (e.g.
// t.TempDir()'s result, or a literal caller-chosen path), which need not
// match pIsWindows: WithRoot exists precisely to sandbox real filesystem
// I/O while a *different* platform's path logic is being simulated (see
// README's "Testing on any host"). p is decomposed into plain segments
// and re-joined onto root using root's own family -- inferred from its
// content via isWindowsPath, not from pIsWindows -- so the result is a
// single, valid, host-usable path regardless of which platform is being
// simulated. An empty root leaves p untouched.
func applyRootRebase(root, p string, pIsWindows bool) string {
if root == "" {
return p
}
_, rest, ok := splitWindowsRoot(p)
if !ok {
return windowsJoin(root, p)
segments := pathSegments(p, pIsWindows)
elems := append([]string{root}, segments...)
if isWindowsPath(root) {
return windowsJoin(elems...)
}
return windowsJoin(root, rest)
return unixJoin(elems...)
}
+53 -12
View File
@@ -58,24 +58,46 @@ func TestSplitWindowsRoot(t *testing.T) {
}
}
func TestApplyRootUnix(t *testing.T) {
if got, want := applyRootUnix("", "/etc/yet"), "/etc/yet"; got != want {
t.Errorf("applyRootUnix(\"\", ...) = %q, want %q", got, want)
func TestApplyRootRebaseUnix(t *testing.T) {
if got, want := applyRootRebase("", "/etc/yet", false), "/etc/yet"; got != want {
t.Errorf("applyRootRebase(\"\", ...) = %q, want %q", got, want)
}
if got, want := applyRootUnix("/tmp/root", "/etc/yet"), "/tmp/root/etc/yet"; got != want {
t.Errorf("applyRootUnix = %q, want %q", got, want)
if got, want := applyRootRebase("/tmp/root", "/etc/yet", false), "/tmp/root/etc/yet"; got != want {
t.Errorf("applyRootRebase = %q, want %q", got, want)
}
}
func TestApplyRootWindows(t *testing.T) {
if got, want := applyRootWindows("", `C:\ProgramData\yet`), `C:\ProgramData\yet`; got != want {
t.Errorf("applyRootWindows(\"\", ...) = %q, want %q", got, want)
func TestApplyRootRebaseWindows(t *testing.T) {
if got, want := applyRootRebase("", `C:\ProgramData\yet`, true), `C:\ProgramData\yet`; got != want {
t.Errorf("applyRootRebase(\"\", ...) = %q, want %q", got, want)
}
if got, want := applyRootWindows(`C:\sandbox`, `C:\ProgramData\yet`), `C:\sandbox\ProgramData\yet`; got != want {
t.Errorf("applyRootWindows = %q, want %q", got, want)
if got, want := applyRootRebase(`C:\sandbox`, `C:\ProgramData\yet`, true), `C:\sandbox\ProgramData\yet`; got != want {
t.Errorf("applyRootRebase = %q, want %q", got, want)
}
if got, want := applyRootWindows(`C:\sandbox`, `\\server\share\yet`), `C:\sandbox\yet`; got != want {
t.Errorf("applyRootWindows(UNC) = %q, want %q", got, want)
if got, want := applyRootRebase(`C:\sandbox`, `\\server\share\yet`, true), `C:\sandbox\yet`; got != want {
t.Errorf("applyRootRebase(UNC) = %q, want %q", got, want)
}
}
// TestApplyRootRebaseMismatchedFamily covers the scenario that motivated
// applyRootRebase's design: root in the REAL host's native family (e.g.
// t.TempDir()'s result on a real Windows host) combined with p in a
// *different*, simulated platform's family (see README's "Testing on
// any host"). Before this was fixed, mismatched families produced a
// mixed-separator (Unix root, Windows-native root) or doubly-drive-
// lettered (Windows root, Unix p incorrectly windows-joined) result.
func TestApplyRootRebaseMismatchedFamily(t *testing.T) {
// Windows-native root (as a real t.TempDir() would return), Unix p
// (a Linux-simulated resolver's unrooted result).
if got, want := applyRootRebase(`C:\Users\test\AppData\Local\Temp\001`, "/home/test/.config/yet", false),
`C:\Users\test\AppData\Local\Temp\001\home\test\.config\yet`; got != want {
t.Errorf("applyRootRebase(windows root, unix p) = %q, want %q", got, want)
}
// Unix-native root, Windows p (a Windows-simulated resolver's
// unrooted result) -- the mirror image, for symmetry.
if got, want := applyRootRebase("/tmp/sandbox", `C:\Users\test\AppData\Roaming\yet`, true),
"/tmp/sandbox/Users/test/AppData/Roaming/yet"; got != want {
t.Errorf("applyRootRebase(unix root, windows p) = %q, want %q", got, want)
}
}
@@ -87,3 +109,22 @@ func TestJoinDirFile(t *testing.T) {
t.Errorf("JoinDirFile(windows) = %q, want %q", got, want)
}
}
func TestJoinDirFileFamily(t *testing.T) {
// dir carries its own family: content wins regardless of platform.
if got, want := JoinDirFileFamily("windows", "/etc/yet", "yet.yaml"), "/etc/yet/yet.yaml"; got != want {
t.Errorf("JoinDirFileFamily(unix dir, windows platform) = %q, want %q", got, want)
}
if got, want := JoinDirFileFamily("linux", `C:\Users\test\workdir`, "yet.yaml"),
`C:\Users\test\workdir\yet.yaml`; got != want {
t.Errorf("JoinDirFileFamily(windows dir, linux platform) = %q, want %q", got, want)
}
// dir is ambiguous (no separator of its own, e.g. the default "."):
// platform decides, same as JoinFamily.
if got, want := JoinDirFileFamily("windows", ".", "yet.yaml"), `.\yet.yaml`; got != want {
t.Errorf("JoinDirFileFamily(ambiguous, windows) = %q, want %q", got, want)
}
if got, want := JoinDirFileFamily("linux", ".", "yet.yaml"), "./yet.yaml"; got != want {
t.Errorf("JoinDirFileFamily(ambiguous, linux) = %q, want %q", got, want)
}
}
+5 -6
View File
@@ -104,11 +104,10 @@ func (r *Resolver) join(elems ...string) string {
func (r *Resolver) isWindows() bool { return r.platform == "windows" }
func (r *Resolver) isDarwin() bool { return r.platform == "darwin" }
// applyRoot rebases an absolute path under the portable root (WithRoot),
// if one is set, using the same address family as r.platform.
// applyRoot rebases an absolute path (in r.platform's simulated address
// family) under the portable root (WithRoot), if one is set -- see
// applyRootRebase for why root's own family, not r.platform's, decides
// the result's family.
func (r *Resolver) applyRoot(p string) string {
if r.isWindows() {
return applyRootWindows(r.root, p)
}
return applyRootUnix(r.root, p)
return applyRootRebase(r.root, p, r.isWindows())
}
+36
View File
@@ -190,3 +190,39 @@ func (r *Resolver) EnsureBinDir() (string, error) {
}
return ensure(dir, 0o755)
}
// EnsureLogAlias creates the optional Unix convenience symlink
// LogAliasDir() -> LogDir() (spec section 39), first ensuring LogDir()
// itself exists, and returns LogAliasDir()'s path. On Windows and macOS
// Desktop, LogAliasDir() already equals LogDir() (there is nothing to
// alias), so this is equivalent to EnsureLogDir() there.
//
// A pre-existing entry at LogAliasDir() -- file, directory, or another
// symlink -- is left untouched and reported as success: this method only
// ever creates a genuinely missing alias, never overwrites one (spec
// section 47's "no implicit destructive mutation").
func (r *Resolver) EnsureLogAlias() (string, error) {
logDir, err := r.EnsureLogDir()
if err != nil {
return "", err
}
alias, err := r.LogAliasDir()
if err != nil {
return "", err
}
if alias == logDir {
return logDir, nil
}
if _, err := os.Lstat(alias); err == nil {
return alias, nil
} else if !os.IsNotExist(err) {
return "", err
}
if err := os.MkdirAll(dirName(alias), 0o700); err != nil {
return "", err
}
if err := os.Symlink(logDir, alias); err != nil {
return "", err
}
return alias, nil
}
+6 -3
View File
@@ -146,9 +146,12 @@ func (r *Resolver) logDirUnix() (value, error) {
if err != nil {
return value{}, err
}
// stateDirUnix already applied the root; join the "log" suffix onto
// the already-rooted path so it isn't rebased twice.
return value{path: unixJoin(state.path, "log"), source: state.source}, nil
// stateDirUnix already applied the root, so joining the "log" suffix
// must use JoinDirFile (not unixJoin) rather than rebasing again:
// WithRoot's root can be in a different address family than this
// simulated platform (see applyRootRebase), so the already-rooted
// state.path may itself be Windows-separated even here.
return value{path: JoinDirFile(state.path, "log"), source: state.source}, nil
}
// logAliasDirUnix is the optional convenience location spec section 39
+23
View File
@@ -164,12 +164,35 @@ func TestWindowsDesktopSimplerLayering(t *testing.T) {
}
func TestWindowsMissingHomeIsCleanError(t *testing.T) {
// windowsBase's native SHGetKnownFolderPath fallback (see
// knownfolders_windows.go) is only consulted when actually running
// on a real Windows host (runtime.GOOS == "windows"), regardless of
// WithPlatform -- deliberately, so it reflects genuine behavior
// there instead of firing under simulation. That means this specific
// scenario (empty environment, no override) resolves a *real*
// known-folder path on an actual Windows host instead of erroring,
// which is correct, intended behavior, not a bug -- but it makes
// this test non-deterministic across hosts. Disable the native
// fallback here so the "no override, no env, no fallback available"
// path is exercised deterministically on every host, including real
// Windows (see the Windows-verification note in TODO.md).
withoutNativeKnownFolder(t)
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(map[string]string{}))
if _, err := r.ConfigDir(); err != ErrNoHomeDirectory {
t.Fatalf("ConfigDir() error = %v, want ErrNoHomeDirectory", err)
}
}
// withoutNativeKnownFolder disables nativeKnownFolder for the duration
// of t, restoring its previous value afterwards.
func withoutNativeKnownFolder(t *testing.T) {
t.Helper()
prev := nativeKnownFolder
nativeKnownFolder = nil
t.Cleanup(func() { nativeKnownFolder = prev })
}
func TestWindowsAPIOverride(t *testing.T) {
r := mustResolver(t, yetApp(), WithPlatform("windows"), WithEnvironment(windowsEnv()), WithConfigDir(`D:\portable\yet-config`))
got, err := r.ConfigDir()