Files
core/ARCHITECTURE.md
T
terminarandClaude Opus 5.5 c11197bb37 configfamily: one config file per program plus an optional family file
The generic part of yamase-core/pkg/configfile (yamase ADR-0074): per
tier a program merges the family file's top level, its section of the
family file and its own <program>.yaml, then --config. Includes
unknown-option rules for shared files, the config command on top of
configcmd.Layered with "create --shared", and doctor/logging helpers.
yaiam is the first user; yamase can move onto it later.

configcmd: a layered Optional program without any file now validates
its defaults and passes doctor instead of failing, as the single-file
path already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 20:26:25 +01:00

289 lines
15 KiB
Markdown

# 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.
## Standard commands: one implementation, program-specific data
`manual`, `completion`, `doctor`, `configcmd` and `version` implement
the commands every Yetano program offers (docs/program-conventions.md in
the meta-repository). Each takes the program's own part as plain data
(an embedded FS, a command tree, a report, a `configcmd.Spec`, a
`version.Info`) and returns an exit code; none depends on cobra or on a
program's flag parser, so a flag-only daemon and a cobra CLI wire them
the same way. They never mutate the filesystem except where the command
exists to do so (`config create`, `config upgrade --write`).
`configcmd` keeps the config schema in the program: core only knows the
YAML tree, the templates and, via reflection on the program's struct,
which keys exist. It started as `yamase-core/pkg/configcmd` and moved
here unchanged in behavior when the other meta-repos needed it.
`configfamily` is the layered configuration of a program family (a
family file, a section of it and a per-program file in every tier) on
top of `configcmd.Layered`. It is the generic part of
`yamase-core/pkg/configfile` (yamase ADR-0074), taken over when yaiam
split into several programs; what is specific to one family -- yamase's
data-dir and storage-role defaults -- stays in that family's code.
## core/gui: a nested module, not a package of this one
The WebView host needs cgo and Cocoa/WebKit on macOS and
`go-webview2`/`x/sys/windows` on Windows; a CLI or daemon importing
`core/paths` must not inherit any of that. So `gui/` has its own
`go.mod` (`yetano.dev/yetano/core/gui`), its own prefixed tags
(`gui/vX.Y.Z`) and its own Go version, while living in the same
repository (one vanity import, one history). It does not import the main
module today; a consumer passes `DataPath` (WebView2 user data) from its
own `core/paths` resolver instead.
Unlike `core/paths`, the GUI host *does* use one build-tagged file per OS
(`window_darwin.go` + `darwin.m`, `window_windows.go`, `window_other.go`):
these are real native bindings that can only be compiled for their OS,
the same exception the root AGENTS.md makes for
`paths/knownfolders_windows.go`. Everything above the window (`assets`,
`document`, `bridge`) is platform-free and unit-tested on any host;
browser behavior is verified by the prototype's in-window selftest.
## core/tui: only what is already identical
`tui/` is a nested module for the same reason as `gui/` (Charm stays out
of the main module's graph). It holds only code that at least two
programs carried byte-identically (themes, styles, paint/outer, list
state, text helpers), not a framework: the app frame, menus and screens
differ per program and move here only once two programs share them. The
long-term `core/ui` (UI-neutral model) / `core/tui` / `core/gui` split of
`docs/yetano-ui/` can grow from this without breaking it.