Files
core/README.md
T

495 lines
21 KiB
Markdown
Raw Normal View History

# yetano.dev/yetano/core
2026-09-19 15:56:59 +02:00
Shared Go library for Yetano applications. `core` defines how a Yetano
application behaves with respect to paths, configuration, runtime data,
and platform integration -- not just a grab-bag of utility functions (see
`AGENTS.md` in the meta-repository root, and [ARCHITECTURE.md](ARCHITECTURE.md)
for the full design rationale).
It covers **platform-independent path, file, and configuration
resolution** (`core/paths`, `core/config`), the **standard commands**
every Yetano program offers (`core/manual`, `core/completion`,
`core/doctor`, `core/configcmd`, `core/version`; see
docs/program-conventions.md in the meta-repository), and secret
references in configuration (`core/secretref`).
Two **separate, nested modules** keep this module at its single
dependency: the native WebView GUI host `yetano.dev/yetano/core/gui`
(tags `gui/vX.Y.Z`, cgo, see [gui/README.md](gui/README.md)) and the
shared terminal-UI kernel `yetano.dev/yetano/core/tui` (tags
`tui/vX.Y.Z`, Charm lipgloss v2, see [tui/README.md](tui/README.md)).
```text
yetano.dev/yetano/core
yetano.dev/yetano/core/paths
yetano.dev/yetano/core/config
yetano.dev/yetano/core/manual
yetano.dev/yetano/core/completion
yetano.dev/yetano/core/doctor
yetano.dev/yetano/core/configcmd
yetano.dev/yetano/core/configfamily
yetano.dev/yetano/core/version
yetano.dev/yetano/core/secretref
yetano.dev/yetano/core/cobracmd (separate module)
yetano.dev/yetano/core/gui (own module, tags gui/vX.Y.Z)
yetano.dev/yetano/core/gui/assets
yetano.dev/yetano/core/gui/document
yetano.dev/yetano/core/gui/bridge
yetano.dev/yetano/core/gui/window
yetano.dev/yetano/core/tui (own module, tags tui/vX.Y.Z)
```
Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions
leak into shared code (see ARCHITECTURE.md's "Platform strategy" section
for how this is achieved without build-tag-per-OS files everywhere).
## Application model
```go
app := core.Application{
Name: "yet",
Kind: core.CLI, // or core.Desktop, core.Service
}
```
`Scope` (`core.UserScope`, the default, or `core.SystemScope`) is a
*separate* concept from `Kind`: the same Service application can run at
either scope, resolving different directories for each.
## core/paths: directories, not files
```go
resolver, err := paths.For(app)
configDir, err := resolver.ConfigDir() // preferred write location
searchDirs, err := resolver.ConfigSearchDirs() // every location to search, priority order
dataDir, err := resolver.DataDir()
stateDir, err := resolver.StateDir()
cacheDir, err := resolver.CacheDir()
runtimeDir, err := resolver.RuntimeDir() // may be ErrRuntimeDirUnavailable, see below
logDir, err := resolver.LogDir()
binDir, err := resolver.BinDir() // shared, not namespaced per app
```
Resolving a path **never** creates it. Use `resolver.EnsureConfigDir()`
etc. to create one explicitly.
### Canonical directory vs. search directories
Every category has two APIs: `<Category>Dir()` (the one preferred
write location) and, for Config/Data/executables,
`<Category>SearchDirs()`/`ExecutableSearchDirs()` (every location to
search, highest priority first). These are not always the same
location -- see "Windows" below.
Without a home directory (`HOME`/`USERPROFILE` unset, and no override
for the user tier), the search lists simply omit the user tier and still
report the system tier -- a system service started without `HOME` keeps
finding `/etc/<app>`. The canonical `<Category>Dir()` methods still
return `paths.ErrNoHomeDirectory` in that case; a write location is never
silently swapped for a different tier.
### Environment variable priority
Every canonical category is resolved through the same chain, highest
priority first:
| Priority | Source | Example |
|---|---|---|
| 1 | Explicit API override | `paths.WithConfigDir("/custom")` |
| 2 | App-specific environment | `YET_CONFIG_HOME` |
| 3 | Shared Yetano environment | `YETANO_CONFIG_HOME` |
| 4 | Platform-native mechanism | `XDG_CONFIG_HOME`, a Windows known folder, native macOS paths |
| 5 | Platform default | `~/.config`, `%APPDATA%`, `~/Library/Application Support` |
Tiers 1-2 (API override, app-specific environment) are used **as-is**:
the value is the final directory, nothing is appended. Tiers 3-4-5 are
treated as a *base* directory that the application name is joined onto
-- except `BinDir`, which is shared across every Yetano application (like
`~/.local/bin`), never namespaced per app, at every tier.
### Linux/Unix (XDG)
```text
~/.config/<app> (XDG_CONFIG_HOME)
~/.local/share/<app> (XDG_DATA_HOME)
~/.local/state/<app> (XDG_STATE_HOME)
~/.cache/<app> (XDG_CACHE_HOME)
$XDG_RUNTIME_DIR/<app> -- or ErrRuntimeDirUnavailable if unset (see below)
~/.local/state/<app>/log
~/.local/bin
```
System scope follows the Filesystem Hierarchy Standard: `/etc/<app>`,
`/var/lib/<app>`, `/var/cache/<app>`, `/run/<app>`, `/var/log/<app>`,
`/usr/local/bin`. FreeBSD uses its own ports-flavored equivalents
(`/usr/local/etc`, `/var/db`, ...) instead of blindly reusing Linux's;
any other Unix-family GOOS falls back to the Linux flavor as a
documented, tunable-later default (see TODO.md).
### macOS: CLI/Service vs. Desktop
CLI and Service applications use the *same* XDG-flavored layout as
Linux, for consistent cross-platform administration. Only Desktop (a
native GUI app) uses `~/Library/...`:
```text
~/Library/Application Support/<App> (Config AND Data -- see ARCHITECTURE.md)
~/Library/Application Support/<App>/State
~/Library/Caches/<App>
~/Library/Logs/<App>
$TMPDIR/<App> (Runtime -- see below)
```
### Windows
Windows is a first-class platform, not XDG-with-backslashes.
`%APPDATA%`, `%LOCALAPPDATA%`, and `%PROGRAMDATA%` have distinct
semantics (roaming user, local-machine user, system-wide) -- see
ARCHITECTURE.md.
For CLI/Service applications, `ConfigDir()` and `ConfigSearchDirs()`
diverge on purpose:
```go
resolver.ConfigDir() // %APPDATA%\<app> (canonical write target)
resolver.ConfigSearchDirs() // %LOCALAPPDATA%\<app> (highest priority: machine override)
// %APPDATA%\<app> (canonical, roaming)
// %PROGRAMDATA%\<app> (lowest priority: system default)
```
Desktop applications use the simpler, native two-tier
`%APPDATA%` (canonical) > `%PROGRAMDATA%` (system fallback), without the
machine-local override layer. Data/State/Cache/Log/Runtime live under
`%LOCALAPPDATA%\<app>\...` for every kind.
### RuntimeDir
`RuntimeDir()` never fabricates a fallback like `~/.local/run`. On
Unix, without an explicit override and without `XDG_RUNTIME_DIR` set, it
returns `paths.ErrRuntimeDirUnavailable` -- callers decide what to do.
Windows and macOS always resolve a runtime directory (no equivalent
"may legitimately not exist" case there; macOS CLI/Service system scope
uses `/var/run/<app>`, since macOS has no `/run`); macOS Desktop resolves it from
`$TMPDIR` (see ARCHITECTURE.md), the same OS-managed ephemeral directory
`NSTemporaryDirectory()` returns.
### LogAliasDir
`LogAliasDir()` resolves the optional Unix convenience symlink target
`~/.local/log/<app>` (spec section 39) without touching the filesystem,
same as every other `*Dir()` method. `EnsureLogAlias()` creates the
actual `LogDir()` symlink there if nothing exists yet, and is a no-op
`EnsureLogDir()` equivalent on Windows/macOS Desktop, where the two
already coincide.
### Explain / doctor
```go
explanation, err := resolver.Explain()
fmt.Println(explanation) // human-readable report
```
Never mutates the filesystem; `Explain` only performs read-only
existence/permission checks.
### Testing on any host
Every platform code path is a plain function of an injectable
`Environment` (env vars) and an injectable platform string
(`paths.WithPlatform("windows")`), not `runtime.GOOS`/`os.Getenv`
directly -- see ARCHITECTURE.md's "Platform strategy" section for why,
and the package's own tests for how Windows/macOS/FreeBSD path logic is
verified while running on any host.
Combine `WithPlatform` with `WithRoot(t.TempDir())` to also sandbox real
filesystem I/O (`Ensure*`, `FindFile`, `Explain`) while simulating a
different platform's path *logic* than the host actually running the
test. `root` there is always in the real host's native address family
(whatever `t.TempDir()` returns), which need not match the simulated
platform's family -- `WithRoot` handles that mismatch correctly (see
ARCHITECTURE.md's "WithRoot: root's family is the real host's"), so the
combination is always safe to use.
## core/config: finding and layering configuration files
```go
cfg, err := config.For(app)
selected, found, err := cfg.Resolve() // highest-priority existing file
all, err := cfg.ResolveAll() // every layer, with metadata
var target MyConfig
err = cfg.LoadMerged(&target) // lowest-to-highest priority merge, then unmarshal
```
### Layer priority
Search order (`Resolve`/`ResolveAll`) and merge order (`LoadMerged`) are
the *same* hierarchy, walked in opposite directions -- there is only one
priority model to keep in sync, not two independently maintained
orderings.
| Priority | Layer | Toggle |
|---|---|---|
| Highest | Working directory (`./<app>.yaml`) | `config.WithWorkingDirectory(false)` |
| User | `paths.ConfigDir()`/`ConfigSearchDirs()` for `app` | (always on) |
| System | `paths.ConfigSearchDirs()`'s system-tier entry | `config.WithSystemConfig(false)` |
| Lowest | Shared Yetano config dir (`~/.config/yetano/`, opt-in) | `config.WithYetanoDefaults(true)` |
On Windows, the "user" tier above expands into the same
LOCALAPPDATA/APPDATA/PROGRAMDATA layering `core/paths` already resolves.
### Merge semantics
- **Scalars**: the higher-priority layer's value replaces the lower one.
- **Maps**: merged recursively, key by key.
- **Lists**: replaced wholesale by the higher-priority layer -- never
concatenated element-by-element.
- **Explicit YAML `null`**: removes the key from the merged result (a
layer can write `key: null` to intentionally unset a lower layer's
value).
### Merging your own layers, with origins
An application whose layers are not one file name per directory (the
yamase family reads a shared `yamase.yaml`, one section of it, and a
per-program file in every tier) builds its own ordered list and merges
it with the same rules:
```go
data, err := config.ReadFile(path) // one file as a mapping
merged, origins := config.Merge(
config.Source{Name: "/etc/app/shared.yaml", Data: shared},
config.Source{Name: "/etc/app/app.yaml", Data: data},
)
// origins["tls.cert-file"] == the Name of the source that set it
```
`Origins` maps every leaf's dotted key to the source it came from (a
list is one leaf), for a "config show" that says where each value is
set. `Resolver.Paths()` returns the underlying `core/paths` resolver,
e.g. for a default derived from `DataDir()`.
### Environment expansion
String values may reference `${VAR}` or `$VAR` (enabled by default,
`config.WithEnvExpansion(false)` to disable). This is **plain variable
substitution, never a shell**: no `$(...)`, no backticks, no command
execution -- the expander's grammar has no way to represent them. An
unset variable is left literally unexpanded (`${MISSING}` stays in the
result, so a typo is visible); a variable set to `""` expands to an
empty string -- these are deliberately different outcomes.
### The shared Yetano config vs. an application's own config
`~/.config/yetano/` (or the platform equivalent) is for
ecosystem-wide, shared settings (`repositories.yaml`, `trust.yaml`,
...) -- it is **not** automatically the same thing as, or automatically
layered into, any one application's own configuration. An application
opts in explicitly with `config.WithYetanoDefaults(true)`.
## core/manual: the "<program> manual" command
Every Yetano program serves its own documentation (ADR-0012), embedded
in the binary. `core/manual` is that command in one shared shape:
```go
// at the module root (go:embed can't reach parent directories):
//go:embed README.md docs
var docsFS embed.FS
var Manual = manual.MustFromFS("yasl", docsFS)
// in the CLI dispatch:
case "manual", "doc":
if err := yasl.Manual.Run(args[1:], os.Stdout); err != nil { ... exit non-zero ... }
```
`FromFS` makes `README.md` the topic `readme` and every `docs/**/*.md`
a topic (slug = path below `docs/` without `.md`, title = first `#`
heading). `Run` serves `manual`, `manual <topic>` and `manual --json
[topic]`; the JSON form (`[{slug,title,path}]` / `{slug,title,path,
markdown}`) is what yet reads to show an installed program's manual
(`yet manual --package`, its TUI and yet-gui).
## core/completion and core/doctor
The other two standard commands of every Yetano program (see
docs/program-conventions.md in the meta-repository):
- `completion.Run(program, tree, args, w)` prints a bash, zsh, fish or
PowerShell completion script generated from a static `completion.Tree`
of the program's commands.
- `doctor.Report` collects the locations the program resolves
(`AddPaths(app)` adds the standard `core/paths` ones) and named checks;
`Run(args, stdout, stderr)` prints a table or `--json` and returns the
exit code (0 all good, 1 a check failed, 2 usage).
## core/configcmd: "<program> config"
`config create [--minimal|--full] [--force] [--output <file>]`,
`config validate`, `config upgrade [--write]` and `config path` for
every program, from one `configcmd.Spec`: the program's name and
`core.Application` (file name and directories), a minimal and a full
template, its `Validate(path)` function and, optionally, its config
struct as `Schema` (unknown-option detection, operator-named maps in
`upgrade`). `Spec.Optional` is for programs that also run without a
file, `Spec.None` for programs without configuration (the command then
says so). `Spec.Find` is the lookup a program should also use at
startup, so `config path` and the program always agree.
```go
spec := configcmd.Spec{
Name: "yasl", App: app,
Minimal: config.MinimalTemplate, Full: config.FullTemplate,
Validate: func(path string) error { _, err := config.Load(path); return err },
Schema: config.Config{},
}
os.Exit(configcmd.Run(spec, configFlag, args, os.Stdout, os.Stderr))
```
A program's tests call `configcmd.UndocumentedKeys(FullTemplate,
config.Config{})` and expect nothing, so every option stays documented
in the full template -- that is what keeps `config upgrade` useful.
`WarnUnknown` (log at startup) and `UnknownCheck` (a doctor check)
report options the program ignores. Taken over from
`yamase-core/pkg/configcmd`, which now wraps it.
`config show [--json] [--show-secrets]` prints the configuration with
the file every value comes from (`Effective.Show`; secrets -- keys
`secrets`, `secret`, `token`, `password` -- are redacted unless
`--show-secrets`, references like `env:X` stay visible), and
`configcmd.Doctor(report, spec, explicit)` is the config part of a
`doctor` command (paths, layers, "config file found", unknown options).
A program whose configuration is merged from more than one file name
per directory -- a family-wide file, a section of it and a per-program
file, as in the yamase family -- sets `Spec.Layered`: `Layers` (what
`config path` lists), `Load` (merge, e.g. with `config.Merge`, into an
`Effective`), optionally `Unknown` (its own unknown-option rules),
`Validate(merged)` and `Used(key)`. `path`, `validate` and `show` then
work on all layers, unknown options become warnings (shared files carry
options of other programs), and `create`/`upgrade` keep working on the
program's own file. `KnownKey(schema, "a.b[0].c")` tells whether a
dotted key is an option of a config struct.
## core/configfamily: one file per program, an optional family file
`core/configfamily` is that layered setup ready-made, for a family of
programs that share one set of config directories (the yamase-* or
yaiam-* programs). Each program is responsible for its own file
(`<program>.yaml`); the family file (`<family>.yaml`) is optional and
holds, at its top level, what several programs share, plus one section
per program (`web:` for `yaiam-web`). Per tier -- system, then user,
then `--config` -- a program merges: family file top level, its section,
its own file. The working directory is never read.
```go
family := configfamily.Family{
Name: "yaiam", Programs: []string{"ctl", "web", "authd"},
Shared: config.Shared{}, SharedTemplate: config.SharedTemplate,
}
spec := configfamily.Spec{
Program: family.Service("yaiam-web"), Optional: true,
Minimal: webMinimal, Full: webFull, Schema: config.WebConfig{},
Validate: func(merged []byte) error { ... },
}
os.Exit(configfamily.Run(spec, configFlag, args, os.Stdout, os.Stderr))
```
`Load(program, explicit)` returns the merged layers (`Loaded.YAML()`
for the program's own parser, `Describe()` for log lines) or
`ErrNotFound`; `Loaded.Unknown(schema)` reports options no layer may
carry -- an option of `Family.Shared` is valid in every layer, other
programs' sections are not this program's business. `Run` adds `config
create --shared` (writes `Family.SharedTemplate`) to core/configcmd's
commands; `Doctor`, `LogLayers` and `WarnUnknown` are the doctor and
startup parts. Defaults that depend on more than the files (yamase's
data-dir and storage roles) stay with the family's own code.
## core/cobracmd: cobra programs (separate module)
`yetano.dev/yetano/core/cobracmd` (own `go.mod`, tags `cobracmd/vX.Y.Z`,
so the main module stays free of cobra) fixes the two places where cobra
behaves differently from the standard: `cobracmd.Completion(root)`
replaces cobra's default `completion` command with one that takes exactly
`bash|zsh|fish|powershell` (cobra's own exits 0 for `completion tcsh`),
and `os.Exit(cobracmd.Execute(root))` maps errors to the standard exit
codes -- 2 for usage errors (unknown command, flag or shell, wrong
argument count, or an error wrapped with `cobracmd.Usage`), 1 otherwise.
## core/version: "<program> version [--json]"
The values stay in each program's `internal/version` (stamped with
`-ldflags -X`); `version.Info{Program, Version, Commit, BuildDate,
Contracts}.Run(args, stdout, stderr)` prints them as text or `--json`
(`program`, `version`, `commit`, `build_date`, `go`, `platform`,
`contracts` for Verse programs). Unstamped builds fall back to the VCS
revision Go embeds; a leading "v" is dropped. `Info.Short()` is the
one-line form for log lines and web UI footers.
## Security
- Environment expansion is variable substitution only -- never shell
evaluation, command substitution, or execution of any kind.
- Every Windows path is built with `path/filepath`-equivalent,
address-family-aware joining (see `paths.JoinFamily`/`JoinDirFile`),
never naive string concatenation -- UNC paths (`\\server\share\...`)
and drive roots are never corrupted by a portable-root rebase.
- No automatic root/administrator operations: `SystemScope` only changes
*which paths are computed*, never elevates privileges or performs a
privileged action on its own.
- Resolving or explaining paths never mutates the filesystem; creating a
directory always requires an explicit `Ensure*` call.
## Versioning
Tagged as plain semver on this repository (`v0.1.0`, ...), per the
meta-repo `AGENTS.md`'s versioning rules: an existing tag is never
force-moved to a different commit. The nested `gui` and `tui` modules
have their own prefixed tags (`gui/v0.1.0`, `tui/v0.1.0`, ...); a change
there needs no main-module tag and vice versa.
## core/secretref
Resolves secret references in a program's configuration, so a token or
password never has to be written into a config file in plain text:
| Form | Value from |
|---|---|
| `secret://<name>` | yaseva (`yaseva [--config <file>] get <name>`, run as a subprocess) |
| `env:<VARIABLE>` | the process environment |
| `file:<path>` | a file (`~` expanded, trailing newline trimmed) |
| `base64:<value>` | the value itself, base64 (standard or URL alphabet) -- out of plain sight, not protected |
```go
r := secretref.New("") // "yaseva" from PATH
token, err := r.ResolveString(ctx, cfg.Token)
log.Print(r.Redact(err.Error())) // resolved values become "***"
```
`Validate` accepts only these forms. A program that must keep reading
plain values it accepted before checks `IsReference` and treats anything
2026-10-12 12:20:07 +02:00
else as a literal. Used by yavebu,
yacry and yadenes.
## core/gui (separate module)
`yetano.dev/yetano/core/gui` is the native WebView host for desktop
programs (macOS: Cocoa + WKWebView; Windows: Win32 + WebView2): embedded
assets served through the WebView's own resource handler, the page's
`fetch`/XHR routed to Go handlers over the native message binding,
streaming, abort and reload handling -- never a local HTTP listener or
port. Packages `assets`, `document`, `bridge`, `window`; extracted from
`prototypes/yetano-webview` (AP1). Details, invariants, measured platform
pitfalls and the yet-gui migration: [gui/README.md](gui/README.md).
## core/tui (separate module)
`yetano.dev/yetano/core/tui` is the kernel the Charm-v2 terminal UIs
(yet, yavebu, yalsh menuconfig) had as hand-kept copies: the themes
`slate`/`dialog`/`midnight` and their lipgloss styles, `Paint`/`Outer`,
`ListState` and text helpers. No app shell or screens yet -- see
[tui/README.md](tui/README.md), which also has the migration steps.