Files
core/ARCHITECTURE.md
T
terminarandClaude Sonnet 5 da2ec85381 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>
2026-09-20 16:37:30 +02:00

12 KiB

Architecture

This document records the design decisions behind core/paths and core/config, and why, for anyone extending this library later. See README.md for the user-facing API summary and priority tables.

Package split: paths vs. config

core/paths resolves directories. It has no notion of a configuration file, YAML, or file contents. core/config resolves files within those directories, and owns everything about search order, layering/merging, and environment expansion. config depends on paths (it needs directories to look in); paths never depends on, or knows about, config. This split is a hard rule (see the meta-repo's AGENTS.md), not a style preference: a future caller that only needs "where does yasta's cache directory live" should never have to pull in YAML parsing.

Application model: Kind and Scope are orthogonal

ApplicationKind (CLI/Desktop/Service) drives platform-style defaults (most visibly on macOS and Windows). Scope (User/System) drives install-context defaults (which of "the machine" vs. "this user" a path belongs to). They are independent axes on purpose: yasta is a Service whether it happens to be running as a per-user agent or a system-wide daemon; conflating "service" with "system-scoped" would make that impossible to express. Neither axis defaults from the other.

Platform strategy: injectable, not build-tag-per-file

Spec-wise, the natural instinct is paths_linux.go, paths_windows.go, etc., each guarded by a //go:build tag. This library does not do that for the bulk of the logic, and the reason is spec section 32's own requirement: "tests must not assume they're running on the OS under test" -- Windows path logic has to be verifiable on a Linux/macOS CI runner, and vice versa. A build-tag-gated paths_windows.go simply cannot compile, let alone run, anywhere but Windows.

Instead:

  • Every platform's logic lives in a plain .go file, organized by name for readability (unix.go, linux.go, freebsd.go, darwin.go, windows.go) but selected at runtime by Resolver.platform (runtime.GOOS by default, overridable via paths.WithPlatform for tests/simulation).
  • All environment lookups go through the injectable Environment interface (paths.WithEnvironment/WithEnvironmentProvider), never os.Getenv directly.
  • Windows path construction never uses path/filepath (which is host-native and would silently misbehave when simulating Windows on a non-Windows host, or vice versa). It uses the address-family-aware helpers in join.go (unixJoin/windowsJoin/JoinFamily/ JoinDirFile) instead, so a computed Windows path is always backslash-joined and a computed Unix path is always forward-slash- joined, regardless of the host running the test.
  • The one genuine exception is knownfolders_windows.go: an optional, best-effort native lookup via SHGetKnownFolderPath, //go:build windows-gated, consulted only as a fallback below the injectable environment variables and only when actually running on Windows (not merely simulating it). It exists purely as extra fidelity for edge cases (redirected known folders, a service account without APPDATA set) -- correctness of the deterministic test suite never depends on it.

This satisfies spec section 1's "OS-specific implementations... where it makes sense" (sofern sinnvoll) reading: a hand-written syscall wrapper legitimately needs a build tag; a string-joining decision does not, and gating it behind one would break the testability requirement elsewhere in the same spec.

WithRoot: root's family is the real host's, not the simulated one

WithRoot sandboxes real filesystem I/O (for Ensure*, FindFile, Explain) under a directory while WithPlatform simulates a different platform's path logic -- e.g. WithPlatform("linux") with WithRoot(t.TempDir()) on any host, so Linux-shaped path logic can be exercised with real file I/O on whatever host runs the test. The resolved path being rebased (p) is always in r.platform's simulated family, but root itself -- almost always t.TempDir(), or otherwise a literal, real filesystem location the caller chose -- is always in the REAL host's native family, which does not have to match r.platform.

applyRoot (via applyRootRebase in join.go) therefore decomposes p into plain path segments (discarding its own absolute-path root marker) and re-joins them onto root using root's own family, inferred from its content the same way JoinDirFile infers a directory's family -- never from r.platform. This is the only correct choice: root must end up as a single, valid, real path the actual host filesystem can use, regardless of which platform's path shape is being simulated for everything above it.

Two consequences fall out of this and are easy to reintroduce by accident:

  • Any code that joins one more suffix onto an already-rooted value (e.g. logDirUnix building <StateDir>/log, or darwinDesktopStateDir/darwinDesktopRuntimeDir's fallback building <AppDir>/State/<AppDir>/Runtime) must use JoinDirFile, not a hardcoded unixJoin/windowsJoin -- the already-rooted value's family now depends on root's family, not on r.platform.
  • core/config's working-directory layer has the identical concern one level up: r.workdirPath can be a real filesystem path (e.g. under WithRoot's root) whose family may not match r.paths.Platform(). paths.JoinDirFileFamily handles this: it behaves like JoinDirFile whenever dir carries its own separator, falling back to JoinFamily's platform-driven choice only when dir is ambiguous (no separator at all, e.g. the default ".").

This was a real, previously-invisible bug (mixed-separator and, in one override case, outright invalid paths) that macOS/Linux test runs could never surface, because t.TempDir() there happens to already share the simulated Unix family with whatever was under test. It was only found by running this package's own test suite on a real Windows host for the first time (see TODO.md) -- worth remembering next time "verified via GOOS=windows go build/go vet" is mistaken for "verified on Windows."

Canonical directory vs. search directories

This is the single most important distinction in the API (see README.md). It exists because Windows genuinely has three simultaneously-relevant layers (%LOCALAPPDATA%, %APPDATA%, %PROGRAMDATA%) with different semantics -- a new config file should be written to the roaming location (so it follows the user), but an existing file should be found even if it's parked in the machine-local override layer or a system-wide default. Every <Category>Dir()/<Category>SearchDirs() pair in this library follows that same canonical-vs-search split, even on platforms (Linux) where they're less obviously necessary, so the API is uniform.

Scope gates which layers exist, not just which one is canonical

SystemScope excludes the user tier entirely from every search list (Config/Data/Executable), rather than merely changing which layer is canonical. Rationale: a system-scope resolution models an execution context with no meaningful per-user home directory (a system daemon account, SYSTEM on Windows) -- including ~/.config/<app> in its search list would be actively misleading, not just lower priority. UserScope (the default) includes the user tier and the system tier as a lower-priority fallback, which is what makes "a user install overrides a system install" (spec section 36) fall out of the priority model for free, rather than needing special-case code.

BinDir is shared, not namespaced

Every other category joins the application name onto a base directory (~/.config/<app>, %APPDATA%\<app>, ...). BinDir deliberately does not: ~/.local/bin and (the spec's own literal example) %LOCALAPPDATA%\Yetano\bin are shared across every Yetano application, mirroring how a PATH entry is inherently a shared, not per-app, concept. This is appendsAppName in layout.go -- the one category where it's false.

App-specific vs. shared environment tiers: as-is vs. base

YET_CONFIG_HOME=/foo resolves to exactly /foo -- not /foo/yet. YETANO_CONFIG_HOME=/foo (and XDG_CONFIG_HOME, and every platform- native/default tier) resolves to /foo/yet. The reasoning: an app-specific variable's name already names the application, so appending the name again would be surprising and is not how any comparable app-specific override convention (elsewhere in the Unix or Windows world) behaves. A shared variable (Yetano-wide, or XDG, or a Windows known folder) is inherently a base many applications share, so it needs the per-app name appended to stay collision-free. This asymmetry is deliberate and tested (TestAppOverrideWinsOverYetano).

macOS: Config and Data share one directory

A native macOS app's ~/Library/Application Support/<App> commonly holds both preferences-adjacent files and bulk data side by side -- this library's Desktop strategy keeps ConfigDir() and DataDir() pointing at the exact same directory on macOS Desktop, rather than inventing an artificial Config/Data subdirectory split that no native macOS app actually uses. StateDir() gets its own State subdirectory so it doesn't collide with either.

RuntimeDir: no fabricated fallback

Spec section 8 explicitly forbids treating ~/.local/run (or any other invented path) as an XDG_RUNTIME_DIR equivalent, because a runtime directory's real semantics (session-scoped, gone after logout, specific permissions) can't be approximated by just picking a persistent directory. RuntimeDir() on Unix therefore returns paths.ErrRuntimeDirUnavailable rather than a wrong-but-present value when neither an override nor XDG_RUNTIME_DIR is set. Windows and macOS don't have this ambiguity (there's no "session runtime directory that may not exist" convention to get wrong there), so RuntimeDir() always succeeds on those platforms.

macOS Desktop RuntimeDir: $TMPDIR, not a persistent placeholder

Unlike Unix's XDG_RUNTIME_DIR, macOS has no documented per-app ephemeral runtime directory convention -- but it does hand every process a real equivalent: $TMPDIR, the per-user, securely permissioned (0700), OS-managed directory confstr(_CS_DARWIN_USER_TEMP_DIR) resolves and NSTemporaryDirectory() returns. darwinDesktopRuntimeDir() prefers it (joined with the app name) over the previous placeholder, ~/Library/Application Support/<App>/Runtime -- a persistent directory that misrepresented "ephemeral" -- falling back to that placeholder only when TMPDIR is absent from the resolved environment (a simulated/test environment that never set it; a real macOS process always has it set).

LogAliasDir is resolved separately from being created

LogAliasDir() (the optional ~/.local/log/<app> convenience symlink target, spec section 39) stays a pure computation like every other *Dir() method -- resolving it never touches the filesystem. Creating the actual symlink is EnsureLogAlias()'s job, kept separate and explicit for the same reason every other Ensure* method is separate from its *Dir() counterpart (see "No implicit filesystem mutation" in the package doc comment): a caller that only wants to know the path (e.g. to show it in doctor/Explain output) should never risk creating a symlink as a side effect.

Unix system-scope directories follow each OS's own convention

Linux SystemScope uses the FHS layout (/etc, /var/lib, /var/cache, /run, /var/log). FreeBSD does not reuse it wholesale (spec sections 33/56): it uses /usr/local/etc (ports convention) and /var/db (BSD's writable-application-data convention) instead of /etc and /var/lib. Any other Unix-family GOOS this library doesn't specifically tune yet falls back to the Linux flavor (flavor()'s default case) -- a documented, working default, not a silent wrong answer, and addable later (a new <os>.go flavor table) without touching any other file (see TODO.md).

Explain/doctor never mutates the filesystem

Explain() on both paths.Resolver and config.Resolver only ever performs read-only os.Stat calls (existence and a best-effort writability check via the owner-write permission bit -- deliberately not a real access probe, which would require creating and deleting a test file). This is spec section 47's explicit requirement, and it's why Explain and Ensure* are entirely separate code paths: the former must never accidentally gain a side effect by sharing implementation with the latter.