From 1e436e34fb8ef19710893107f3bf966f8db17f94 Mon Sep 17 00:00:00 2001 From: Dan Tsekhanskiy Date: Sun, 12 Apr 2026 17:25:24 +0000 Subject: [PATCH] docs: Fix all documentation review findings Critical: correct Critical/Persist defaults (false not true), replace fake testing example with real BuildGraph pattern. High: README quickstart adds build step and baseline.go link, ptrFalse replaced with inline code, macOS launchd workaround note. Medium: Extensions() list completed, Condition/Dir/Env fields added to tables, CLAUDE.md conditions list links to directory, platform detector step added to extensions guide. Low: //go:build rationale, State table accuracy, distro switch example. Closes #26 --- CLAUDE.md | 2 +- CONTRIBUTING.md | 2 +- README.md | 20 +++++++++++----- docs/design.md | 11 +++------ docs/examples.md | 60 ++++++++++++++++++++++++++++++---------------- docs/extensions.md | 2 ++ dsl/app.go | 6 +++++ 7 files changed, 67 insertions(+), 36 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 6f0345c..dbc9239 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,7 +10,7 @@ Read `docs/design.md` for philosophy and security model, `docs/extensions.md` fo | --- | --- | | DSL (blueprint API) | `dsl/` (platform-specific methods in build-tagged files) | | Extensions | `extensions/` (one subdirectory per resource type, see directory for full list) | -| Conditions | `condition/` (FileExists, MountPoint, NetworkInterface, NetworkReachable, RegistryKeyExists) | +| Conditions | [`condition/`](condition/) (see directory for full list) | | Blueprints | `blueprints/` (baseline, per-OS, CIS benchmarks) | | Internals | `internal/` (daemon, engine, exit, graph, logging, output, platform, version, watch, winreg) | | CLI | `cmd/converge/` | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 964fc05..12332be 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -30,7 +30,7 @@ Short version: implement the [`Extension` interface](extensions/extension.go), d - **Go 1.26** -- use `slices`, `maps`, range-over-int - **Table-driven tests** everywhere -- **Build tags** -- use `_linux`, `_darwin`, `_windows` (not `_unix` or `!windows`) +- **Build tags** -- use `_linux`, `_darwin`, `_windows` (not `_unix` or `!windows`). Go 1.17+ requires the `//go:build` directive for `go vet` and IDE support, even when the `_linux`/`_darwin`/`_windows` suffix also restricts compilation. - **No stubs** -- platform-specific DSL methods live in build-tagged files; if a platform doesn't need an extension, the DSL doesn't expose it - **Native APIs** -- prefer `golang.org/x/sys/windows`, `/proc/sys/`, `howett.net/plist` over shelling out - **Error wrapping** with `fmt.Errorf("...: %w", err)` diff --git a/README.md b/README.md index bc7ab7a..7d6ccbb 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,9 @@ Download latest installer for your platform from the [Releases](https://github.c ## Quick start -**1. Edit a blueprint** (`blueprints/baseline.go`): +**1. Edit a blueprint** ([blueprints/baseline.go](blueprints/baseline.go)): + +Blueprints are Go code compiled into the `converge` binary. Editing a blueprint requires a rebuild. ```go package blueprints @@ -52,15 +54,21 @@ func Baseline(r *dsl.Run) { } ``` -**2. Plan and serve:** +**2. Rebuild:** + +```bash +go build -o bin/converge ./cmd/converge +``` + +**3. Plan and serve:** ```bash -converge plan baseline # dry-run, no root needed -sudo converge serve baseline # run as persistent daemon, re-converge on drift -sudo converge serve baseline --timeout 1s # converge and exit (CI/Packer) +bin/converge plan baseline # dry-run, no root needed +sudo bin/converge serve baseline # run as persistent daemon, re-converge on drift +sudo bin/converge serve baseline --timeout 1s # converge and exit (CI/Packer) ``` -**3. Flags:** +**4. Flags:** ```bash converge plan baseline --out=json # machine-readable output (also: serial) diff --git a/docs/design.md b/docs/design.md index eb4d8c1..0d5118b 100644 --- a/docs/design.md +++ b/docs/design.md @@ -119,14 +119,9 @@ type Extension interface { } ``` -| State | Meaning | -|-------------|----------------------------------------------| -| `OK` | System matches desired state. Nothing to do. | -| `Drifted` | System differs from desired state. | -| `Missing` | Resource doesn't exist yet. | -| `Error` | Can't determine state (permissions, etc.). | +`Check` returns `*State{InSync: true}` when nothing needs to change, or `*State{InSync: false, Changes: [...]}` with specific property changes. See [`extensions/state.go`](../extensions/state.go). -`Check()` is read-only. `Apply()` mutates the system and is only called when `Check()` returns `Drifted` or `Missing`. A follow-up `Check()` must return `OK`, otherwise Converge reports a convergence failure. +`Check()` is read-only. `Apply()` mutates the system and is only called when `Check()` reports `InSync: false`. A follow-up `Check()` must return `InSync: true`, otherwise Converge reports a convergence failure. **Idempotency by construction:** Run it once, drift is fixed. Run it again, nothing changes. The engine enforces this via the Check/Apply split. @@ -309,7 +304,7 @@ Defined in `internal/exit/exit.go`: - **DAG execution order.** Resources execute in topological layer order. Dependencies complete before dependents. - **Auto-edges.** Implicit dependencies detected automatically (Service->Package, File->parent Dir). - **Duplicate detection.** Two extensions with same `ID()` = error before any Check(). -- **Critical flag.** If `Critical: true` (default), failure aborts remaining apply. +- **Critical flag.** If `Critical: true` (default: false), failure aborts remaining apply. - **Parallel execution.** `--parallel N` runs up to N resources concurrently within each layer (default: sequential). - **Per-resource timeout.** `--timeout` sets the deadline for each resource's Check/Apply cycle. - **Detailed exit codes.** `--detailed-exit-codes` enables granular exit codes for CI/CD integration. diff --git a/docs/examples.md b/docs/examples.md index f5626a1..116576a 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -177,6 +177,21 @@ func Blueprint(r *dsl.Run) { `r.Platform()` returns a `platform.Info` struct with `OS`, `Distro`, `Arch`, `PkgManager`, and `InitSystem`. +Use `p.Distro` for distro-specific logic within the same OS: + +```go +func Blueprint(r *dsl.Run) { + p := r.Platform() + + switch p.Distro { + case "ubuntu": + r.Package("apt-transport-https", dsl.PackageOpts{State: dsl.Present}) + case "fedora": + r.Package("dnf-plugins-core", dsl.PackageOpts{State: dsl.Present}) + } +} +``` + For platform-specific resources like `r.Registry()` (Windows), `r.Sysctl()` (Linux), or `r.Plist()` (macOS), use Go build tags on the blueprint file itself: ```go @@ -281,32 +296,32 @@ func Blueprint(r *dsl.Run) { ## Testing Blueprints -Blueprints are Go functions. Test them with `go test`: +Blueprints are Go functions compiled into the binary. Test them with `go test` by registering the blueprint and building the DAG: ```go -package myblueprint_test +package blueprints import ( "testing" - "github.com/TsekNet/converge/dsl/testing/mock" - "github.com/myorg/myinfra/blueprints/myblueprint" -) -func TestBlueprint(t *testing.T) { - r := mock.NewRun() - myblueprint.Blueprint(r) - - if !r.HasFile("/etc/motd") { - t.Error("expected /etc/motd to be declared") - } + "github.com/TsekNet/converge/dsl" +) - if !r.HasPackage("git") { - t.Error("expected git package to be declared") +func TestBaseline(t *testing.T) { + app := dsl.New() + app.Register("baseline", "test", Baseline) + + // BuildGraph calls the blueprint, builds the DAG, and adds auto-edges. + // It returns an error if the blueprint declares duplicate resources, + // references missing dependencies, or fails validation. + _, err := app.BuildGraph("baseline") + if err != nil { + t.Fatalf("BuildGraph failed: %v", err) } } ``` -No containers, no VMs, no network calls. +`BuildGraph` exercises the full blueprint: resource declaration, duplicate detection, dependency validation, and auto-edge wiring. No containers, no VMs, no network calls, no root required. --- @@ -316,17 +331,18 @@ All option structs share these common fields via `dsl.Meta`: | Field | Type | Default | Description | |-------|------|---------|-------------| -| `Critical` | `bool` | `true` | If `true`, failure aborts the run. Set `false` for best-effort. | +| `Critical` | `bool` | `false` | If `true`, failure aborts the run. Set `true` for resources whose failure should abort the run. | | `DependsOn` | `[]string` | `nil` | Explicit resource IDs this resource depends on. Complements auto-edges. | | `Noop` | `bool` | `false` | Per-resource dry-run: Check only, skip Apply. | | `Retry` | `int` | `0` | Per-resource max retries. 0 = use daemon default (--max-retries). | | `Limit` | `float64` | `0` | Per-resource rate limit (events/sec). 0 = use daemon default. | -| `AutoEdge` | `*bool` | `nil` | Set to `ptrFalse` to disable auto-edges for this resource. | -| `AutoGroup` | `*bool` | `nil` | Set to `ptrFalse` to disable auto-grouping for this resource. | +| `AutoEdge` | `*bool` | `nil` | Set to `falseVal := false; &falseVal` to disable auto-edges for this resource. | +| `AutoGroup` | `*bool` | `nil` | Set to `falseVal := false; &falseVal` to disable auto-grouping for this resource. | +| `Condition` | `extensions.Condition` | `nil` | Gate on runtime state. See [Conditions](#conditions). | **Auto-edges:** Dependencies are detected automatically: `service:X` depends on `package:X`, files depend on parent directories, services depend on config files. Use `DependsOn` for dependencies auto-edges cannot detect. -**Auto-grouping:** Package resources with the same manager and state are automatically batched into a single install/remove transaction (e.g., `apt install git curl neovim` instead of three separate calls). Set `AutoGroup: ptrFalse` on a package to opt out. +**Auto-grouping:** Package resources with the same manager and state are automatically batched into a single install/remove transaction (e.g., `apt install git curl neovim` instead of three separate calls). Set `AutoGroup` to a `*bool` pointing to `false` to opt out (e.g., `falseVal := false; Meta{AutoGroup: &falseVal}`). Use `DependsOn` for dependencies auto-edges cannot detect: @@ -478,6 +494,8 @@ r.Service(name string, opts dsl.ServiceOpts) | macOS | `launchd` | stub (not yet implemented) | | Windows | Windows SCM | `golang.org/x/sys/windows/svc/mgr` (native Win32) | +> **macOS note:** launchd is not yet implemented natively. Use `r.Exec()` with `launchctl` as a workaround. + **Idempotency:** Checks current state before acting. Starting a running service is a no-op. **Examples:** @@ -525,6 +543,8 @@ r.Exec(name string, opts dsl.ExecOpts) | `OnlyIfMatch` | `string` | `""` | When set, guard compares trimmed stdout against this string instead of exit code. | | `Shell` | `string` | `""` | `"auto"` (bash on Linux/macOS, powershell on Windows), `"powershell"`, `"pwsh"`, `"cmd"`, `"bash"`, `"sh"`, or custom path. | | `ShellParams` | `[]string` | `nil` | When set, replaces the default shell flags. PowerShell default: `-NoProfile -NonInteractive -ExecutionPolicy Bypass`. | +| `Dir` | `string` | `""` | Working directory. Empty = inherit. | +| `Env` | `[]string` | `nil` | Additional environment variables (KEY=VALUE format). | | `Retries` | `int` | `0` | Number of retry attempts on failure. | | `RetryDelay` | `time.Duration` | `0` | Delay between retries. | @@ -818,7 +838,7 @@ The `key` uses dotted notation, e.g., `net.ipv4.ip_forward`. | Field | Type | Default | Description | |-------|------|---------|-------------| | `Value` | `string` | `""` | Desired kernel parameter value. Required. | -| `Persist` | `bool` | `true` | If `true`, writes to `/etc/sysctl.d/99-converge.conf` so the setting survives reboots. | +| `Persist` | `bool` | `false` | If `true`, writes to `/etc/sysctl.d/99-converge.conf` so the setting survives reboots. Set `true` for reboot persistence. | **API:** Direct file I/O to `/proc/sys/`: no `sysctl` command. diff --git a/docs/extensions.md b/docs/extensions.md index 8ed5771..e175b66 100644 --- a/docs/extensions.md +++ b/docs/extensions.md @@ -133,6 +133,8 @@ func detectManager(name string) PackageManager { } ``` +**Note:** If the package manager is not already detected by `internal/platform/`, add detection logic to the appropriate platform detector function (e.g., `detectLinuxPkgManager()` in `internal/platform/platform.go`). + ### 3. Add tests Create `extensions/pkg/dnf_test.go` with table-driven tests: diff --git a/dsl/app.go b/dsl/app.go index 1e9fc46..5905bae 100644 --- a/dsl/app.go +++ b/dsl/app.go @@ -60,6 +60,12 @@ func (a *App) Extensions() []Item { {"Exec", "Run commands with guards and retries"}, {"User", "Manage local user accounts"}, {"Firewall", "Manage host firewall rules (nftables, pf, Windows Firewall)"}, + {"Template", "Render Go text/template to a file with variable substitution"}, + {"Hostname", "Ensure system hostname matches desired value"}, + {"Cron", "Manage cron jobs (Linux/macOS) and scheduled tasks (Windows)"}, + {"Repository", "Manage package repository sources (APT, DNF/YUM)"}, + {"KernelModule", "Load or blacklist kernel modules (Linux only)"}, + {"Reboot", "Schedule and track platform-native OS reboots"}, {"Registry", "Manage Windows registry keys (Windows only)"}, {"SecurityPolicy", "Manage Windows password and lockout policies (Windows only)"}, {"AuditPolicy", "Manage Windows advanced audit policy (Windows only)"},