From 508d35152b4b657540d7143be6c0064fbb386287 Mon Sep 17 00:00:00 2001 From: ShookEagle Date: Fri, 30 Oct 2026 20:41:25 -0500 Subject: [PATCH 1/3] feat: automatically install opted-in plugin updates at startup --- README.md | 2 +- docs/examples/plugins-source.json | 1 + docs/reference/plugins.md | 69 ++- .../2026-10-30-automatic-plugin-installs.md | 52 +++ ...-10-30-automatic-plugin-installs-design.md | 56 +++ internal/plugins/automatic.go | 57 +++ internal/plugins/automatic_test.go | 412 ++++++++++++++++++ internal/plugins/commands.go | 7 + internal/plugins/manager.go | 53 ++- internal/plugins/model.go | 22 +- internal/plugins/state.go | 13 +- 11 files changed, 711 insertions(+), 33 deletions(-) create mode 100644 docs/superpowers/plans/2026-10-30-automatic-plugin-installs.md create mode 100644 docs/superpowers/specs/2026-10-30-automatic-plugin-installs-design.md create mode 100644 internal/plugins/automatic.go create mode 100644 internal/plugins/automatic_test.go diff --git a/README.md b/README.md index c5d90f4..3cf4fb4 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ Prefer standalone? Skip step 1. `SOURCE_MODE=auto` installs into the server's ow SourceMod automatically requires Metamod. Framework upgrades preserve private configs, custom changes and disabled stock plugins. Exact version pins never silently become latest. -Server owners can manage third-party plugins from public GitHub/private GitLab releases or compile SourcePawn directly from individual repositories using `.source/plugins.json` and `egg plugins` panel console commands. Repository recipes track exact commits, use a pinned SourceMod compiler, and declare include dependencies. Preview and approve an exact package, then install it at the next normal restart. No node access or plugin CI pipeline is needed. [Per-server plugin configuration, source builds, updates and rollback](docs/reference/plugins.md). +Server owners can manage third-party plugins from public GitHub/private GitLab releases or compile SourcePawn directly from individual repositories using `.source/plugins.json` and `egg plugins` panel console commands. Set `"auto_approve": true` to install ready packages automatically at normal startup, or retain exact-package manual approval. Repository recipes use a pinned SourceMod compiler and declared include dependencies; branches/releases can track updates or be pinned to exact versions. No node access or plugin CI pipeline is needed. [Per-server plugin configuration, source builds, updates and rollback](docs/reference/plugins.md). The fresh-install password policy offers **one join password per server**, using EFF words and monthly rotation after opt-in. The wizard also supports per-game/node sharing and cron schedules with a timezone. Existing nodes retain their saved per-game/token/hour policy. Password generation is opt-in at both node and server; RCON credentials remain separate. diff --git a/docs/examples/plugins-source.json b/docs/examples/plugins-source.json index 54168be..d07d26e 100644 --- a/docs/examples/plugins-source.json +++ b/docs/examples/plugins-source.json @@ -1,6 +1,7 @@ { "version": 1, "check_interval_hours": 6, + "auto_approve": true, "plugins": [ { "id": "dxlevel-restrict", diff --git a/docs/reference/plugins.md b/docs/reference/plugins.md index 7dc3360..3342a69 100644 --- a/docs/reference/plugins.md +++ b/docs/reference/plugins.md @@ -2,7 +2,7 @@ Server owners can manage third-party release packages and build SourcePawn plugins directly from repositories through the panel file manager and console. This works in standalone and node-managed servers; packages, credentials, toolchains, approvals and rollback files stay in the server's private volume. No node access is needed. -The manager checks at startup and every six hours by default. It downloads and previews available versions, then waits for approval of an exact package. Approved installs, updates, rollbacks and removals happen before the game launches on the next normal restart. It never hot reloads plugins or forces a restart. Failed release checks keep the installed files usable. +The manager checks at startup and every six hours by default. Manual manifests wait for approval of an exact package. Set `"auto_approve": true` to automatically queue successful downloads/builds for installation. Installs, updates, rollbacks and removals happen before the game launches during normal startup. Checks while the game runs only stage and queue packages; they never hot reload plugins or force a restart. Failed checks and builds keep installed files usable. ## Configuration @@ -98,6 +98,56 @@ The third release asset is a loose `simple-chat.smx`, with no archive. Its `from Mappings can place files below `addons`, `cfg`, `scripts`, `materials`, `models`, `sound`, `resource` and `maps`. A package can contain extensions, translations, gamedata and default configuration along with plugins. Missing sources, duplicate destinations, ambiguous assets, traversal, archive links, special files and oversized packages are rejected. Downloads are limited to 256 MiB, expanded archives to 512 MiB, individual files to 64 MiB and archive entries to 10,000. Ordinary ZIP archives are supported; ZIP64, multi-disk and self-extracting executable ZIP layouts are rejected. Release recipes do not compile source. No repository/install scripts run and runtime dependencies are not installed automatically. +## Automatic installation and pins + +Add `"auto_approve": true` beside `version` in the existing manifest to cover +first installs and updates without per-version console approvals: + +```json +{ + "version": 1, + "check_interval_hours": 6, + "auto_approve": true, + "plugins": [] +} +``` + +Keep your existing entries in `plugins`. Omitting `auto_approve` or setting it +to `false` retains manual approval. A plugin's own `"auto_approve": false` or +`true` overrides the manifest policy. `egg plugins list` shows the effective +`approval=auto` or `approval=manual` for each tracked entry. + +The automatic flow is: check, download/build, verify the staged package, queue +it, and install before the game starts. Ready cached packages also qualify +after switching to automatic mode, including when the provider is offline. +Packages successfully prepared during startup can install on that launch. +Startup checks retain a shared 30-second budget; longer source builds retry +in the background and their completed packages wait for the next normal restart. +Only the newest successfully staged automatic snapshot is queued; a failed +newer check/build retains the previous valid package and installed files. + +Version selection works independently of approval policy. For release assets, +use `pin` for an exact release tag. For source builds, use `source.ref` for a +branch, tag or full commit SHA. Pin every include dependency's `source.ref` to +a full commit too when reproducible source inputs are required. Changing a pin +selects a new version for the same automatic installation flow. Missing pins +never fall back to latest. Without exact pins, configured branches and release +channels continue tracking updates. + +Automatic installs still block on unowned file collisions, framework ownership, +or locally edited managed code. They never imply `replace` or adoption. Fix the +conflict through the existing preview/keep/adopt/explicit-approval workflow. +Config, data, logs and other preserved paths retain their existing behavior. + +Explicit pending installs, rollbacks and uninstalls take precedence for that +startup. Later automatic checks follow the configured source again: disable +automatic approval or pin the desired revision when holding a rollback, and +remove a recipe when uninstalling a tracked package permanently. Turning auto +off cancels automatic pending actions while retaining staging and explicit +approvals. `cancel` removes a queued action, but a later check can queue it again +while automatic mode remains enabled. Policy edits alone do not change package +IDs or invalidate explicit approvals. + ## Build directly from a repository Give each repository its own plugin entry. Adding `build` selects source mode: @@ -118,7 +168,7 @@ places the resulting plugins in the active directory: "url": "https://gitlab.edgegamers.io", "repository": "source/plugins/counter-strike/dxlevel-restrict", "credential": "edgegamers-gitlab", - "ref": "main" + "ref": "master" }, "build": { "sourcemod": "1.13.0.7478", @@ -161,10 +211,11 @@ Source checks have a five-minute budget per repository and each compiler process has a one-minute limit. Startup retains its overall 30-second check budget; timed-out source builds retry in the background scheduler after the game starts. An unchanged, intact available build is reused. Build errors retain installed -files and earlier staged packages. Approvals still bind exact bytes and recipes; -a later commit does not change an already approved pending install. Source -packages use the same preview, approval, normal-restart installation, local-edit -protection, rollback and removal commands as release packages. +files and earlier staged packages. Explicit approvals still bind exact bytes and +recipes; a later commit does not change an explicitly approved pending install. +Source packages use the same automatic/manual approval policy, normal-startup +installation, local-edit protection, rollback and removal commands as release +packages. The manager executes only the compiler from the selected official toolchain, with fixed arguments, a minimal environment, bounded diagnostics and named @@ -189,7 +240,7 @@ The `source.credential` value refers to a key in this object. Use a project or p Keep this file private in the panel; do not put tokens in console commands, repository URLs or the manifest. The manager does not put tokens in the game process environment or shared node cache. Installed game plugins run as the server user and can read server files, including this credentials file; install code you trust. GitHub acquisition supports public release assets. -## Check, review and approve +## Check, review and approve manually Enter commands in the panel console, one complete line at a time: @@ -202,13 +253,13 @@ egg plugins preview match-tools egg plugins approve match-tools ``` -Replace `` with the full 64-character SHA-256 package ID printed by `preview`. Review every mapped path and any collision or modification notices. Approval binds that exact staged content and recipe; it does not approve whatever upstream publishes later. `egg plugins update match-tools ` is an alias for `approve`. +These approval commands are optional in automatic mode. Replace `` with the full 64-character SHA-256 package ID printed by `preview`. Review every mapped path and any collision or modification notices. An explicit approval binds that exact staged content and recipe; it does not approve whatever upstream publishes later. `egg plugins update match-tools ` is an alias for `approve`. To cancel a queued install, rollback or uninstall before restarting, run `egg plugins cancel match-tools`. Cancellation retains the staged package and existing game files. Restart through the panel when ready. The startup notice reports completion, and update notices name available and installed versions. All `SourceEgg | Plugins |` messages remain visible even when the console filter or log level hides ordinary lines. The masked messages also go to local logs and configured node console delivery. -Changing a mapping or other recipe setting invalidates its earlier approval. Run `check`, inspect the new `preview`, and approve the new exact ID. When the managed path set changes, review the new preview before approving its exact package ID. Editing `.source/plugins.json` is supported while the game runs; checks and commands reload it. If malformed configuration prevents initialization, the game can still start: fix the file and issue a plugin command to retry. Restart to resume automatic checks. An unrecoverable interrupted file transaction prevents startup until it is repaired. +Changing a mapping or other content recipe setting invalidates its earlier approval. Run `check`; automatic mode validates and queues the new package, while manual mode waits for preview/approval of the new exact ID. Approval policy changes alone retain package identities. Editing `.source/plugins.json` is supported while the game runs; checks and commands reload it. If malformed configuration prevents initialization, the game can still start: fix the file and issue a plugin command to retry. Restart to resume scheduled checks. An unrecoverable interrupted file transaction prevents startup until it is repaired. You can add a recipe through the console instead of editing the manifest. The JSON object must fit on one line: diff --git a/docs/superpowers/plans/2026-10-30-automatic-plugin-installs.md b/docs/superpowers/plans/2026-10-30-automatic-plugin-installs.md new file mode 100644 index 0000000..ff8ca8f --- /dev/null +++ b/docs/superpowers/plans/2026-10-30-automatic-plugin-installs.md @@ -0,0 +1,52 @@ +# Automatic Plugin Installs Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Install opted-in ready plugin versions on normal startup without routine package approvals. + +**Architecture:** Add an inherited boolean approval policy and reuse installer preview/pending transactions. Queue cached/checked snapshots before one startup apply pass so ready builds install on that launch, while explicit pending actions retain priority. + +**Tech Stack:** Go 1.27, existing plugin manager/installer, JSON manifests. + +**Spec:** `docs/superpowers/specs/2026-10-30-automatic-plugin-installs-design.md`. + +## Global Constraints + +- Manifest `auto_approve` defaults to false; per-plugin optional boolean overrides it. +- Policy never changes recipe hashes or staged package identities. +- Preserve the 30-second startup check budget; install only with the game stopped. +- Automatic queueing always uses `replace=false` and existing ownership/edit checks. +- Explicit pending install/rollback/uninstall actions take precedence for that startup. +- Preserve failed-build fallback, configuration/data/logs, pins and recovery. + +## Review Focus + +- Already staged packages must install after enabling auto even with the provider offline. +- A manual rollback/uninstall must not be undone during the same startup. +- Turning automatic approval off must cancel persisted automatic work across recreation. +- Cached source builds and failed newer builds must retain correct automatic snapshots. +- A stale queued revision must not override a newly resolved already-installed revision. + +### Task 1: Automatic approval policy and lifecycle + +**Files:** +- Modify `internal/plugins/model.go`, `state.go`, `manager.go`, `commands.go`. +- Create `internal/plugins/automatic.go`, `automatic_test.go`. +- Modify `README.md`, `docs/reference/plugins.md`, `docs/examples/plugins-source.json`. +- Update ignored `dist/css-server-config/plugins*.json` and `SETUP.txt`. + +**Interfaces:** +- Manifest `AutoApprove bool`; Plugin `AutoApprove *bool`; pendingAction `Automatic bool`, all JSON `auto_approve`/`automatic` with omission where appropriate. +- `(*Manager).autoApprove(Plugin) bool` resolves overrides. +- `(*Manager).queueAutomatic(Plugin, Snapshot)` previews and queues without replacing explicit actions. +- `(*Manager).applyPending() error` applies the existing action loop once after startup discovery. +- `recipeHash(Plugin)` excludes approval policy. + +- [x] Add behavior regressions for all validation/review-focus cases; run and observe failures. +- [x] Add policy fields, hash exclusion, effective list output and automatic queue/cancellation logic. +- [x] Refactor startup discovery/apply ordering; keep explicit actions protected and remove installed matching availability. +- [x] Run focused regressions and the existing full plugin/egg lifecycle suite; resolve failures. +- [x] Document automatic mode, pins, conflicts, explicit action behavior and restart timing; opt this server into automatic tracking. +- [x] Run `go test -race ./...`, `go vet ./...`, `CGO_ENABLED=0 go build ./cmd/...`, formatting and manifest validation. +- [x] Commit the feature and docs; record the completion contract in the execution ledger. +- [ ] Obtain a fresh whole-branch review, fix actionable findings with RED→GREEN tests, push and open a PR. diff --git a/docs/superpowers/specs/2026-10-30-automatic-plugin-installs-design.md b/docs/superpowers/specs/2026-10-30-automatic-plugin-installs-design.md new file mode 100644 index 0000000..b542cbb --- /dev/null +++ b/docs/superpowers/specs/2026-10-30-automatic-plugin-installs-design.md @@ -0,0 +1,56 @@ +# Automatic plugin installs + +The server owner chose automatic tracking of configured branches and releases +and explicitly asked to proceed without further design questions. Eliminate +routine exact-package approvals for opted-in first installs and updates. + +## Approach + +Add manifest-level `auto_approve: true`. Omitted/false retains manual approval +for existing manifests. An optional per-plugin boolean overrides the manifest. +Release `pin` and source/dependency `ref` keep their existing selection semantics; +exact version pins and full commit refs work with either approval policy. +Approval policy does not affect recipe hashes or staged package identities. + +The alternatives were manual approval of every package, automatic tracking, +and automatic installation with all source/include revisions frozen. The owner +chose tracking; pinned operation remains supported through existing selectors. + +## Lifecycle + +Checks validate/build in staging and queue eligible automatic snapshots using +the existing installer preview with `replace=false`. Checks while the game is +running never write game files. New successful snapshots supersede previous +automatic pending installs; failed checks/builds preserve installed files and +previous valid staging. A currently installed matching revision clears stale +automatic pending installs. + +At startup, collect ready cached snapshots and check for updates within the +existing 30-second budget, then apply pending actions before launching the game. +Ready packages can install on that startup, including cached packages when the +provider is unavailable. Source builds exceeding the startup budget retry in +the background and wait for the next normal restart. + +Explicit manual install/rollback/uninstall actions take precedence for that +startup. Automatic policy does not supersede them during discovery. Future +automatic checks follow the configured source again; pin or disable automatic +approval when intentionally holding a rollback or uninstalling a tracked entry. +Disabling automatic approval cancels automatic pending actions, preserving +explicit approvals and staged packages. Cancel alone removes a queued action; +a later automatic check may queue it again. + +## Boundaries + +No forced restarts, hot installs, automatic replacement of local edits, automatic +adoption of unowned files, new pin commands, or changes to framework ownership. +File collisions and changed managed files block that automatic install with a +clear message. Config/data/log preservation and transaction recovery remain. +List output identifies the effective approval policy. Update reference docs, +examples and this server's generated manifests to opt into automatic tracking. + +## Validation + +Exercise first startup, offline existing staging, source builds and failures, +background queueing, per-plugin overrides, policy opt-out, explicit actions, +local edit conflicts, pinned release selection and unchanged package hashes. +Run the full race-test suite, vet, builds and a fresh whole-branch review. diff --git a/internal/plugins/automatic.go b/internal/plugins/automatic.go new file mode 100644 index 0000000..c9c4815 --- /dev/null +++ b/internal/plugins/automatic.go @@ -0,0 +1,57 @@ +package plugins + +func (m *Manager) autoApprove(p Plugin) bool { + if p.AutoApprove != nil { + return *p.AutoApprove + } + return m.manifest.AutoApprove +} + +// Policy edits cancel only automatic work. Explicit actions retain their exact +// snapshot and are still validated against the content recipe at installation. +func (m *Manager) pruneAutomatic() error { + changed := false + for id, action := range m.state.Pending { + if !action.Automatic { + continue + } + p, tracked := m.plugin(id) + if !tracked || !m.autoApprove(p) || action.Recipe != recipeHash(p) { + delete(m.state.Pending, id) + changed = true + m.emit(id + ": automatic install cancelled because its policy or recipe changed") + } + } + if changed { + return m.save() + } + return nil +} + +func (m *Manager) clearAutomatic(id string) { + if action, ok := m.state.Pending[id]; ok && action.Automatic { + delete(m.state.Pending, id) + } +} + +// Queue only verified staging and retain all existing ownership and edit +// checks. Manual approvals, rollback and uninstall take precedence. +func (m *Manager) queueAutomatic(p Plugin, snapshot Snapshot) { + if !m.autoApprove(p) || snapshot.Recipe != recipeHash(p) { + return + } + pending, exists := m.state.Pending[p.ID] + if exists && !pending.Automatic { + return + } + if _, err := m.installer.Preview(p.ID, &snapshot, false); err != nil { + m.clearAutomatic(p.ID) + m.emit(p.ID + ": automatic install blocked; keeping installed files: " + err.Error()) + return + } + if exists && pending.Snapshot.ID == snapshot.ID { + return + } + m.state.Pending[p.ID] = pendingAction{Kind: "install", Automatic: true, Snapshot: snapshot, Recipe: snapshot.Recipe} + m.emit(p.ID + ": automatic install queued " + snapshot.Version + " (" + snapshot.ID + "); will install at next normal restart") +} diff --git a/internal/plugins/automatic_test.go b/internal/plugins/automatic_test.go new file mode 100644 index 0000000..e6aef4a --- /dev/null +++ b/internal/plugins/automatic_test.go @@ -0,0 +1,412 @@ +package plugins + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func setAutomaticPolicy(t *testing.T, volume string, enabled bool, overrides map[string]bool) { + t.Helper() + filename := filepath.Join(volume, manifestPath) + data, err := os.ReadFile(filename) + if err != nil { + t.Fatal(err) + } + var manifest map[string]any + if err := json.Unmarshal(data, &manifest); err != nil { + t.Fatal(err) + } + manifest["auto_approve"] = enabled + for _, value := range manifest["plugins"].([]any) { + p := value.(map[string]any) + if override, ok := overrides[p["id"].(string)]; ok { + p["auto_approve"] = override + } + } + data, err = json.Marshal(manifest) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filename, data, 0600); err != nil { + t.Fatal(err) + } +} + +func automaticInstalled(t *testing.T, m *Manager, id string) Snapshot { + t.Helper() + installed, err := m.installer.Installed() + if err != nil { + t.Fatal(err) + } + return installed[id].Current +} + +func TestAutomaticInstallsFirstVersionAndStartupUpdates(t *testing.T) { + m, source, volume, notices := managerFixture(t) + setAutomaticPolicy(t, volume, true, nil) + for _, version := range []string{"v1", "v2"} { + source.version, source.body = version, version + if err := m.Startup(context.Background()); err != nil { + t.Fatal(err) + } + if got := automaticInstalled(t, m, "demo").Version; got != version { + t.Fatalf("startup installed %q, want %q; %s", got, version, notices) + } + data, err := os.ReadFile(filepath.Join(volume, "tf/addons/sourcemod/plugins/demo.smx")) + if err != nil || string(data) != version { + t.Fatalf("installed bytes = %q, %v", data, err) + } + } +} + +func TestAutomaticRuntimeChecksQueueAndPersistUntilRestart(t *testing.T) { + m, source, volume, notices := managerFixture(t) + setAutomaticPolicy(t, volume, true, nil) + m.Command(context.Background(), "egg plugins check") + queued, ok := m.state.Pending["demo"] + if !ok || queued.Kind != "install" { + t.Fatalf("automatic install not queued: %s", notices) + } + if _, err := os.Stat(filepath.Join(volume, "tf/addons/sourcemod/plugins/demo.smx")); !os.IsNotExist(err) { + t.Fatal("runtime check wrote a live game file") + } + source.offline = true + next, err := New(volume, "tf", source, nil) + if err != nil { + t.Fatal(err) + } + if err := next.Startup(context.Background()); err != nil { + t.Fatal(err) + } + if got := automaticInstalled(t, next, "demo").ID; got != queued.Snapshot.ID { + t.Fatalf("persisted install = %q, want %q", got, queued.Snapshot.ID) + } +} + +func TestAutomaticOptInInstallsExistingStagingOfflineWithoutChangingPackage(t *testing.T) { + for _, global := range []bool{true, false} { + t.Run(map[bool]string{true: "manifest policy", false: "plugin override"}[global], func(t *testing.T) { + m, source, volume, notices := managerFixture(t) + m.Command(context.Background(), "egg plugins check") + staged := m.state.Available["demo"] + overrides := map[string]bool{} + if !global { + overrides["demo"] = true + } + setAutomaticPolicy(t, volume, global, overrides) + source.offline = true + if err := m.Startup(context.Background()); err != nil { + t.Fatal(err) + } + if got := automaticInstalled(t, m, "demo").ID; got != staged.ID { + t.Fatalf("existing staging changed or did not install: %q, want %q; %s", got, staged.ID, notices) + } + }) + } +} + +func TestAutomaticPerPluginOverride(t *testing.T) { + for _, test := range []struct { + name string + global, override bool + want string + }{ + {"manual plugin in automatic manifest", true, false, ""}, + {"automatic plugin in manual manifest", false, true, "v1"}, + } { + t.Run(test.name, func(t *testing.T) { + m, _, volume, notices := managerFixture(t) + setAutomaticPolicy(t, volume, test.global, map[string]bool{"demo": test.override}) + if err := m.Startup(context.Background()); err != nil { + t.Fatal(err) + } + if got := automaticInstalled(t, m, "demo").Version; got != test.want { + t.Fatalf("installed = %q, want %q; %s", got, test.want, notices) + } + m.Command(context.Background(), "egg plugins list") + mode := "manual" + if test.override { + mode = "auto" + } + if !strings.Contains(notices.String(), "approval="+mode) { + t.Fatalf("list omitted effective approval policy: %s", notices) + } + }) + } +} + +func TestAutomaticQueuesAllCachedPackagesBeforeProviderConsumesStartupBudget(t *testing.T) { + m, _, volume, notices := managerFixture(t) + second := m.manifest.Plugins[0] + second.ID = "second" + second.Mappings = []Mapping{{From: "demo.smx", To: "addons/sourcemod/plugins/second.smx"}} + manifest := m.manifest + manifest.Plugins = append(manifest.Plugins, second) + data, _ := json.Marshal(manifest) + if err := os.WriteFile(filepath.Join(volume, manifestPath), data, 0600); err != nil { + t.Fatal(err) + } + m.Command(context.Background(), "egg plugins check") + if len(m.state.Available) != 2 { + t.Fatalf("two cached packages required: %s", notices) + } + setAutomaticPolicy(t, volume, true, nil) + m.source, m.defaultSource = cancelledSource{}, false + ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) + defer cancel() + if err := m.Startup(ctx); err != nil { + t.Fatal(err) + } + for _, id := range []string{"demo", "second"} { + if automaticInstalled(t, m, id).ID == "" { + t.Fatalf("cached %s did not install after timeout: %s", id, notices) + } + } +} + +func TestAutomaticRejectsCachedPackageAfterContentRecipeEdit(t *testing.T) { + m, source, volume, notices := managerFixture(t) + m.Command(context.Background(), "egg plugins check") + manifest := m.manifest + manifest.Plugins[0].Preserve = []string{"addons/sourcemod/plugins/demo.smx"} + data, _ := json.Marshal(manifest) + if err := os.WriteFile(filepath.Join(volume, manifestPath), data, 0600); err != nil { + t.Fatal(err) + } + setAutomaticPolicy(t, volume, true, nil) + source.offline = true + if err := m.Startup(context.Background()); err != nil { + t.Fatal(err) + } + if automaticInstalled(t, m, "demo").ID != "" { + t.Fatalf("installed cached content for an earlier recipe: %s", notices) + } +} + +func TestAutomaticOptOutCancelsOnlyAutomaticPendingInstalls(t *testing.T) { + for _, explicit := range []bool{false, true} { + t.Run(map[bool]string{false: "automatic", true: "explicit approval"}[explicit], func(t *testing.T) { + m, source, volume, notices := managerFixture(t) + setAutomaticPolicy(t, volume, true, nil) + m.Command(context.Background(), "egg plugins check") + if _, ok := m.state.Pending["demo"]; !ok { + t.Fatalf("automatic action missing: %s", notices) + } + staged := m.state.Available["demo"] + if explicit { + m.Command(context.Background(), "egg plugins approve demo "+staged.ID) + } + setAutomaticPolicy(t, volume, false, nil) + source.offline = true + next, err := New(volume, "tf", source, nil) + if err != nil { + t.Fatal(err) + } + if err := next.Startup(context.Background()); err != nil { + t.Fatal(err) + } + got := automaticInstalled(t, next, "demo").ID + if (got != "") != explicit { + t.Fatalf("opt-out installed %q; explicit=%v", got, explicit) + } + if !explicit && next.state.Available["demo"].ID != staged.ID { + t.Fatal("opt-out discarded staging") + } + }) + } +} + +func TestAutomaticInstallsRespectExplicitPendingActions(t *testing.T) { + t.Run("exact manual install", func(t *testing.T) { + m, source, volume, notices := managerFixture(t) + m.Command(context.Background(), "egg plugins check") + m.Command(context.Background(), "egg plugins approve demo "+m.state.Available["demo"].ID) + setAutomaticPolicy(t, volume, true, nil) + source.version, source.body = "v2", "two" + if err := m.Startup(context.Background()); err != nil { + t.Fatal(err) + } + if got := automaticInstalled(t, m, "demo").Version; got != "v1" { + t.Fatalf("explicit approval replaced by %q: %s", got, notices) + } + }) + for _, action := range []string{"rollback", "uninstall"} { + t.Run(action, func(t *testing.T) { + m, source, volume, notices := managerFixture(t) + setAutomaticPolicy(t, volume, true, nil) + if err := m.Startup(context.Background()); err != nil { + t.Fatal(err) + } + first := automaticInstalled(t, m, "demo") + if first.ID == "" { + t.Fatalf("initial install missing: %s", notices) + } + want := "" + if action == "rollback" { + source.version, source.body = "v2", "two" + if err := m.Startup(context.Background()); err != nil { + t.Fatal(err) + } + m.Command(context.Background(), "egg plugins rollback demo "+first.ID) + want = "v1" + } else { + m.Command(context.Background(), "egg plugins uninstall demo confirm") + } + if err := m.Startup(context.Background()); err != nil { + t.Fatal(err) + } + if got := automaticInstalled(t, m, "demo").Version; got != want { + t.Fatalf("%s was undone: got %q, want %q; %s", action, got, want, notices) + } + }) + } +} + +func TestAutomaticInstallBlocksUnownedFilesAndLocalEdits(t *testing.T) { + for _, installed := range []bool{false, true} { + t.Run(map[bool]string{false: "unowned file", true: "local edit"}[installed], func(t *testing.T) { + m, source, volume, notices := managerFixture(t) + setAutomaticPolicy(t, volume, true, nil) + if installed { + if err := m.Startup(context.Background()); err != nil { + t.Fatal(err) + } + if automaticInstalled(t, m, "demo").ID == "" { + t.Fatalf("initial install missing: %s", notices) + } + } + target := filepath.Join(volume, "tf/addons/sourcemod/plugins/demo.smx") + if err := os.MkdirAll(filepath.Dir(target), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(target, []byte("local file"), 0600); err != nil { + t.Fatal(err) + } + source.version, source.body = "v2", "two" + if err := m.Startup(context.Background()); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(target) + if err != nil || string(data) != "local file" { + t.Fatalf("local file replaced: %q, %v", data, err) + } + if _, ok := m.state.Pending["demo"]; ok || !strings.Contains(notices.String(), "automatic install blocked") { + t.Fatalf("conflict not reported and blocked: %s", notices) + } + }) + } +} + +func TestAutomaticCheckReplacesPendingWithLatestOrClearsWhenCurrent(t *testing.T) { + m, source, volume, notices := managerFixture(t) + setAutomaticPolicy(t, volume, true, nil) + if err := m.Startup(context.Background()); err != nil { + t.Fatal(err) + } + for _, version := range []string{"v2", "v3"} { + source.version, source.body = version, version + m.Command(context.Background(), "egg plugins check") + if got := m.state.Pending["demo"].Snapshot.Version; got != version { + t.Fatalf("queued %q, want %q; %s", got, version, notices) + } + } + source.version, source.body = "v1", "version1" + if err := m.Startup(context.Background()); err != nil { + t.Fatal(err) + } + if got := automaticInstalled(t, m, "demo").Version; got != "v1" { + t.Fatalf("stale automatic install applied: %q", got) + } + if _, ok := m.state.Pending["demo"]; ok { + t.Fatal("stale automatic install retained") + } +} + +func TestAutomaticSourceBuildRetainsReadyVersionAfterFailure(t *testing.T) { + m, _, volume, notices := managerFixture(t) + p := buildRecipe(t) + p.ID = "demo" + p.Build.IncludeDirs = nil + p.Mappings = []Mapping{{From: "compiled/demo.smx", To: "addons/sourcemod/plugins/demo.smx"}, {From: "cfg/demo.cfg", To: "cfg/sourcemod/demo.cfg"}} + data, _ := json.Marshal(Manifest{Version: 1, Plugins: []Plugin{p}}) + if err := os.WriteFile(filepath.Join(volume, manifestPath), data, 0600); err != nil { + t.Fatal(err) + } + setAutomaticPolicy(t, volume, true, nil) + archive := func(body string) string { + return packageTar(t, []packageEntry{{name: "repo/scripting/demo.sp", body: body}, {name: "repo/cfg/demo.cfg", body: "defaults"}}) + } + source := &sourceManagerFixture{version: strings.Repeat("a", 40), archive: archive("STABLE")} + m.source, m.defaultSource, m.compiler = source, false, fixtureCompiler(t) + if err := m.Startup(context.Background()); err != nil { + t.Fatal(err) + } + if got := automaticInstalled(t, m, "demo").Version; got != source.version { + t.Fatalf("source did not install: %q; %s", got, notices) + } + config := filepath.Join(volume, "tf/cfg/sourcemod/demo.cfg") + if err := os.WriteFile(config, []byte("local settings"), 0600); err != nil { + t.Fatal(err) + } + source.version = strings.Repeat("b", 40) + m.Command(context.Background(), "egg plugins check") + ready := m.state.Available["demo"] + m.Command(context.Background(), "egg plugins check") + if source.downloads != 2 || m.state.Pending["demo"].Snapshot.ID != ready.ID { + t.Fatalf("cached source rebuilt or not queued: %d downloads; %s", source.downloads, notices) + } + source.version, source.archive = strings.Repeat("c", 40), archive("FAIL") + m.Command(context.Background(), "egg plugins check") + if m.state.Pending["demo"].Snapshot.ID != ready.ID { + t.Fatalf("failed build replaced ready automatic package: %s", notices) + } + source.offline = true + if err := m.Startup(context.Background()); err != nil { + t.Fatal(err) + } + if got := automaticInstalled(t, m, "demo").ID; got != ready.ID { + t.Fatalf("ready source did not install offline: %q; %s", got, notices) + } + if data, _ := os.ReadFile(config); string(data) != "local settings" { + t.Fatal("automatic update overwrote local settings") + } +} + +func TestAutomaticInstallsHonorPinnedRelease(t *testing.T) { + var origin string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/repos/test/demo/releases/tags/v1": + json.NewEncoder(w).Encode(map[string]any{"id": 1, "tag_name": "v1", "assets": []map[string]string{{"name": "demo.smx", "browser_download_url": origin + "/v1.smx"}}}) + case "/v1.smx": + w.Write([]byte("pinned version")) + default: + t.Errorf("pinned automatic install requested unexpected path: %s", r.URL.Path) + http.NotFound(w, r) + } + })) + defer srv.Close() + origin = srv.URL + m, _, volume, notices := managerFixture(t) + p := m.manifest.Plugins[0] + p.Pin, p.Source.URL = "v1", origin + data, _ := json.Marshal(Manifest{Version: 1, Plugins: []Plugin{p}}) + if err := os.WriteFile(filepath.Join(volume, manifestPath), data, 0600); err != nil { + t.Fatal(err) + } + setAutomaticPolicy(t, volume, true, nil) + m.source, m.defaultSource = &HTTPSource{Client: srv.Client()}, false + if err := m.Startup(context.Background()); err != nil { + t.Fatal(err) + } + if got := automaticInstalled(t, m, "demo").Version; got != "v1" { + t.Fatalf("pinned version did not install: %q; %s", got, notices) + } +} diff --git a/internal/plugins/commands.go b/internal/plugins/commands.go index 6b84a93..c0f88c9 100644 --- a/internal/plugins/commands.go +++ b/internal/plugins/commands.go @@ -80,6 +80,13 @@ func (m *Manager) command(ctx context.Context, f []string, line string) error { } else if p.Pin != "" { s += " pin=" + p.Pin } + if tracked { + if m.autoApprove(p) { + s += " approval=auto" + } else { + s += " approval=manual" + } + } if tracked && p.Build != nil { ref := p.Source.Ref if ref == "" { diff --git a/internal/plugins/manager.go b/internal/plugins/manager.go index aeb93b6..cf594d8 100644 --- a/internal/plugins/manager.go +++ b/internal/plugins/manager.go @@ -74,7 +74,7 @@ func New(volume, gameDir string, source ReleaseSource, notice func(string)) (*Ma return nil, errors.New("invalid pending preservation path") } } - if !identifier.MatchString(id) || !validSnapshotReference(p.Snapshot) || (p.Kind != "install" && p.Kind != "rollback" && p.Kind != "uninstall") { + if !identifier.MatchString(id) || !validSnapshotReference(p.Snapshot) || (p.Kind != "install" && p.Kind != "rollback" && p.Kind != "uninstall") || (p.Automatic && (p.Kind != "install" || p.Replace)) { return nil, errors.New("invalid pending plugin action") } } @@ -111,6 +111,19 @@ func (m *Manager) Startup(ctx context.Context) error { m.emit("Configuration error; keeping installed plugins: " + e.Error()) return nil } + // Discover before applying so successful automatic builds can install on + // this launch. Explicit pending actions remain present during discovery. + checkCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + m.check(checkCtx, "") + cancel() + if err := m.applyPending(); err != nil { + return err + } + m.collect() + return nil +} + +func (m *Manager) applyPending() error { ids := make([]string, 0, len(m.state.Pending)) for id := range m.state.Pending { ids = append(ids, id) @@ -157,6 +170,9 @@ func (m *Manager) Startup(ctx context.Context) error { continue } delete(m.state.Pending, id) + if a.Kind != "uninstall" && m.state.Available[id].ID == a.Snapshot.ID { + delete(m.state.Available, id) + } m.emit(id + ": " + a.Kind + " completed") if e = m.save(); e != nil { m.emit("Cannot save plugin action state: " + e.Error()) @@ -167,9 +183,6 @@ func (m *Manager) Startup(ctx context.Context) error { m.emit("Cannot save plugin state: " + e.Error()) return nil } - checkCtx, cancel := context.WithTimeout(ctx, 30*time.Second) - defer cancel() - m.check(checkCtx, "") return nil } @@ -203,6 +216,16 @@ func (m *Manager) check(ctx context.Context, id string) { m.emit("Cannot read installed plugin state: " + e.Error()) return } + // Queue every already-ready package before network checks can consume the + // startup budget, including when the configured provider is unavailable. + for _, p := range m.manifest.Plugins { + if id != "" && p.ID != id { + continue + } + if snapshot, ok := m.state.Available[p.ID]; ok && snapshot.ID != installed[p.ID].Current.ID { + m.queueAutomatic(p, snapshot) + } + } for _, p := range m.manifest.Plugins { if ctx.Err() != nil { break @@ -237,7 +260,11 @@ func (m *Manager) checkPlugin(ctx context.Context, p Plugin, old Snapshot) { if e != nil { m.emit(p.ID + ": update check failed; keeping installed files: " + e.Error()) if cached, ok := m.state.Available[p.ID]; ok && cached.Recipe == recipeHash(p) { - m.emit(p.ID + ": previously staged version " + cached.Version + " remains available; run egg plugins preview " + p.ID) + message := p.ID + ": previously staged version " + cached.Version + " remains available" + if !m.autoApprove(p) { + message += "; run egg plugins preview " + p.ID + } + m.emit(message) } return } @@ -247,12 +274,17 @@ func (m *Manager) checkPlugin(ctx context.Context, p Plugin, old Snapshot) { } if release.Version == old.Version && old.Recipe == recipeHash(p) { delete(m.state.Available, p.ID) + m.clearAutomatic(p.ID) m.emit(p.ID + ": installed " + old.Version + " is current") return } if p.Build != nil { if cached, ok := m.state.Available[p.ID]; ok && cached.Version == release.Version && cached.Recipe == recipeHash(p) && m.cachedSourceExists(cached) { - m.emit(p.ID + ": staged " + cached.Version + " remains available; run egg plugins preview " + p.ID) + message := p.ID + ": staged " + cached.Version + " remains available" + if !m.autoApprove(p) { + message += "; run egg plugins preview " + p.ID + } + m.emit(message) return } } @@ -266,9 +298,14 @@ func (m *Manager) checkPlugin(ctx context.Context, p Plugin, old Snapshot) { if current == "" { current = "not managed" } - m.emit(p.ID + ": new version " + snap.Version + " available (installed: " + current + "); run egg plugins preview " + p.ID) + if m.autoApprove(p) { + m.emit(p.ID + ": version " + snap.Version + " ready (installed: " + current + ")") + m.queueAutomatic(p, snap) + } else { + m.emit(p.ID + ": new version " + snap.Version + " available (installed: " + current + "); run egg plugins preview " + p.ID) + } if len(old.Files) > 0 && !sameLayout(old, snap) { - m.emit(p.ID + ": package layout changed; review all mapped paths before approving this package") + m.emit(p.ID + ": package layout changed; run egg plugins preview " + p.ID + " to inspect mapped paths") } } diff --git a/internal/plugins/model.go b/internal/plugins/model.go index 9b0c4e6..86eaeb5 100644 --- a/internal/plugins/model.go +++ b/internal/plugins/model.go @@ -17,18 +17,20 @@ import ( type Manifest struct { Version int `json:"version"` CheckIntervalHours int `json:"check_interval_hours"` + AutoApprove bool `json:"auto_approve,omitempty"` Plugins []Plugin `json:"plugins"` } type Plugin struct { - ID string `json:"id"` - Source Source `json:"source"` - Asset string `json:"asset,omitempty"` - Format string `json:"format,omitempty"` - Mappings []Mapping `json:"mappings"` - Preserve []string `json:"preserve,omitempty"` - Pin string `json:"pin,omitempty"` - Prerelease bool `json:"prerelease,omitempty"` - Build *Build `json:"build,omitempty"` + ID string `json:"id"` + Source Source `json:"source"` + Asset string `json:"asset,omitempty"` + Format string `json:"format,omitempty"` + Mappings []Mapping `json:"mappings"` + Preserve []string `json:"preserve,omitempty"` + Pin string `json:"pin,omitempty"` + Prerelease bool `json:"prerelease,omitempty"` + Build *Build `json:"build,omitempty"` + AutoApprove *bool `json:"auto_approve,omitempty"` } type Source struct { Provider string `json:"provider"` @@ -243,6 +245,8 @@ func (m *Manifest) Validate() error { return nil } func recipeHash(p Plugin) string { + // Approval policy controls deployment, not the staged package's contents. + p.AutoApprove = nil b, _ := json.Marshal(p) sum := sha256.Sum256(b) return hex.EncodeToString(sum[:]) diff --git a/internal/plugins/state.go b/internal/plugins/state.go index d48c421..e55587d 100644 --- a/internal/plugins/state.go +++ b/internal/plugins/state.go @@ -19,11 +19,12 @@ const credentialsPath = ".source/plugin-credentials.json" const statePath = ".source/plugins/state.json" type pendingAction struct { - Kind string `json:"kind"` - Snapshot Snapshot `json:"snapshot"` - Recipe string `json:"recipe,omitempty"` - Replace bool `json:"replace,omitempty"` - Preserve []string `json:"preserve,omitempty"` + Kind string `json:"kind"` + Automatic bool `json:"automatic,omitempty"` + Snapshot Snapshot `json:"snapshot"` + Recipe string `json:"recipe,omitempty"` + Replace bool `json:"replace,omitempty"` + Preserve []string `json:"preserve,omitempty"` } type managerState struct { Version int `json:"version"` @@ -137,7 +138,7 @@ func (m *Manager) reload() error { } m.source = &HTTPSource{Credentials: creds} } - return nil + return m.pruneAutomatic() } func (m *Manager) save() error { r, e := m.root() From 5f15a8d97b4aaff3866333f96c90efda672bf116 Mon Sep 17 00:00:00 2001 From: ShookEagle Date: Fri, 30 Oct 2026 20:44:49 -0500 Subject: [PATCH 2/3] docs: record automatic plugin installation verification --- docs/superpowers/plans/2026-10-30-automatic-plugin-installs.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/superpowers/plans/2026-10-30-automatic-plugin-installs.md b/docs/superpowers/plans/2026-10-30-automatic-plugin-installs.md index ff8ca8f..6c98773 100644 --- a/docs/superpowers/plans/2026-10-30-automatic-plugin-installs.md +++ b/docs/superpowers/plans/2026-10-30-automatic-plugin-installs.md @@ -49,4 +49,4 @@ - [x] Document automatic mode, pins, conflicts, explicit action behavior and restart timing; opt this server into automatic tracking. - [x] Run `go test -race ./...`, `go vet ./...`, `CGO_ENABLED=0 go build ./cmd/...`, formatting and manifest validation. - [x] Commit the feature and docs; record the completion contract in the execution ledger. -- [ ] Obtain a fresh whole-branch review, fix actionable findings with RED→GREEN tests, push and open a PR. +- [x] Obtain a fresh whole-branch review, fix actionable findings with RED→GREEN tests, push and open a PR. From d620894223a7dd33bbd439b9d14bed10fb86d0e5 Mon Sep 17 00:00:00 2001 From: ShookEagle Date: Fri, 30 Oct 2026 20:48:06 -0500 Subject: [PATCH 3/3] fix: allow automatic installs after pending approval pins change --- docs/reference/plugins.md | 6 ++++-- ...-10-30-automatic-plugin-installs-design.md | 6 ++++-- internal/plugins/automatic.go | 11 ++++++++-- internal/plugins/automatic_test.go | 20 +++++++++++++++++++ 4 files changed, 37 insertions(+), 6 deletions(-) diff --git a/docs/reference/plugins.md b/docs/reference/plugins.md index 3342a69..c8047ed 100644 --- a/docs/reference/plugins.md +++ b/docs/reference/plugins.md @@ -139,8 +139,10 @@ or locally edited managed code. They never imply `replace` or adoption. Fix the conflict through the existing preview/keep/adopt/explicit-approval workflow. Config, data, logs and other preserved paths retain their existing behavior. -Explicit pending installs, rollbacks and uninstalls take precedence for that -startup. Later automatic checks follow the configured source again: disable +Valid explicit pending installs, rollbacks and uninstalls take precedence for +that startup. A content recipe edit, including a changed pin, invalidates an +older approval and allows the newly selected automatic package to install. +Later automatic checks follow the configured source again: disable automatic approval or pin the desired revision when holding a rollback, and remove a recipe when uninstalling a tracked package permanently. Turning auto off cancels automatic pending actions while retaining staging and explicit diff --git a/docs/superpowers/specs/2026-10-30-automatic-plugin-installs-design.md b/docs/superpowers/specs/2026-10-30-automatic-plugin-installs-design.md index b542cbb..4c73a37 100644 --- a/docs/superpowers/specs/2026-10-30-automatic-plugin-installs-design.md +++ b/docs/superpowers/specs/2026-10-30-automatic-plugin-installs-design.md @@ -31,8 +31,10 @@ Ready packages can install on that startup, including cached packages when the provider is unavailable. Source builds exceeding the startup budget retry in the background and wait for the next normal restart. -Explicit manual install/rollback/uninstall actions take precedence for that -startup. Automatic policy does not supersede them during discovery. Future +Valid explicit manual install/rollback/uninstall actions take precedence for +that startup. Automatic policy does not supersede them during discovery. A +content edit (including a changed pin) invalidates the older approval, allowing +the new automatic package to install on that startup. Future automatic checks follow the configured source again; pin or disable automatic approval when intentionally holding a rollback or uninstalling a tracked entry. Disabling automatic approval cancels automatic pending actions, preserving diff --git a/internal/plugins/automatic.go b/internal/plugins/automatic.go index c9c4815..027d25d 100644 --- a/internal/plugins/automatic.go +++ b/internal/plugins/automatic.go @@ -35,14 +35,21 @@ func (m *Manager) clearAutomatic(id string) { } // Queue only verified staging and retain all existing ownership and edit -// checks. Manual approvals, rollback and uninstall take precedence. +// checks. Valid manual approvals, rollback and uninstall take precedence. func (m *Manager) queueAutomatic(p Plugin, snapshot Snapshot) { if !m.autoApprove(p) || snapshot.Recipe != recipeHash(p) { return } pending, exists := m.state.Pending[p.ID] if exists && !pending.Automatic { - return + if pending.Kind == "uninstall" || pending.Recipe == snapshot.Recipe { + return + } + // A content edit (including a changed pin) already invalidates this + // explicit approval. It must not delay the newly eligible auto build. + delete(m.state.Pending, p.ID) + exists = false + m.emit(p.ID + ": approval cancelled because its recipe changed") } if _, err := m.installer.Preview(p.ID, &snapshot, false); err != nil { m.clearAutomatic(p.ID) diff --git a/internal/plugins/automatic_test.go b/internal/plugins/automatic_test.go index e6aef4a..c41e58d 100644 --- a/internal/plugins/automatic_test.go +++ b/internal/plugins/automatic_test.go @@ -269,6 +269,26 @@ func TestAutomaticInstallsRespectExplicitPendingActions(t *testing.T) { } } +func TestAutomaticChangedPinIsNotBlockedByStaleManualApproval(t *testing.T) { + m, source, volume, notices := managerFixture(t) + m.Command(context.Background(), "egg plugins check") + m.Command(context.Background(), "egg plugins approve demo "+m.state.Available["demo"].ID) + manifest := m.manifest + manifest.Plugins[0].Pin = "v2" + data, _ := json.Marshal(manifest) + if err := os.WriteFile(filepath.Join(volume, manifestPath), data, 0600); err != nil { + t.Fatal(err) + } + setAutomaticPolicy(t, volume, true, nil) + source.version, source.body = "v2", "two" + if err := m.Startup(context.Background()); err != nil { + t.Fatal(err) + } + if got := automaticInstalled(t, m, "demo").Version; got != "v2" { + t.Fatalf("stale explicit approval blocked changed pin: got %q; %s", got, notices) + } +} + func TestAutomaticInstallBlocksUnownedFilesAndLocalEdits(t *testing.T) { for _, installed := range []bool{false, true} { t.Run(map[bool]string{false: "unowned file", true: "local edit"}[installed], func(t *testing.T) {