The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
fix(asymptote): restart the Beacon Cloud forwarder when the log may have been replaced
aakashpawar19995356f6666d01
diff --git a/CLAUDE.md b/CLAUDE.mdindex 0a3ad686..ca2ffa99 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -29,7 +29,7 @@ Do not recreate or depend on removed `asymptote` mirror trees. Keep new work foc- Preserve the local-only default. The public Beacon build must not require a hosted account, remote policy fetch, hosted dashboard, or external network dependency during normal hook execution, and hooks themselves never touch the network.- `beacon login` is the account-identity channel for interactive users and is required by the interactive `beacon endpoint install` wizard. It uses browser PKCE against beacon.sh and stores the scoped CLI token only in `~/.beacon/auth/session.json` (0600 under a 0700 directory). Signing in alone never starts forwarding. User-mode `beacon endpoint connect` may send that token once to `POST /api/cli/enroll/account` to authorize minting a separate device ingest key, and `beacon mcp token create` may send it to `POST /api/cli/mcp/tokens` (scope `mcp:token:create`, listed on the sign-in page) to mint a personal MCP token that is printed once to stdout and never written to a file, and `beacon share` may send it (scope `traces:write`, also on the sign-in page) to `PUT /v1/traces/{external_id}`, `POST /v1/traces/{external_id}/events/batch` and `GET /v1/traces/{external_id}` on the Beacon API host (`https://api.beacon.sh` for a beacon.sh sign-in, other hosts unchanged, `BEACON_API_URL` overrides) to upload a shared trace the person chose to publish, as a `beacon.trace.v1` summary and its events (`cli/beacon/internal/account/share.go`; a `bcn_api_` API key from `--key` or `BEACON_API_KEY` may stand in for it, precedence `--key`, then a current sign-in carrying the scope, then the environment). These are explicit, user-initiated requests with redirects refused. Hooks, plugins and background jobs never make them, with one exception: the git pre-push hook, only when the person opted in with `beacon git setup --share-sessions` (public needs confirmation), may make the three share requests during a push the person started, within the hook's budget and never failing the push. Never copy the account token into endpoint config, Vector, hook environments, logs, or command output. System/root/package/MDM/CI/piped-stdin/dry-run installs stay noninteractive and account-free.- System log access (`beacon endpoint install|repair --system --log-access shared|restricted`; docs in `docs/cli/endpoint-install.mdx#restricted-log-access`). Shared, the default, is the system log as it always was: hooks append to `/var/log/beacon-agent/runtime.jsonl` directly, so it is `0666`. Restricted is opt-in and makes the root collector the only writer: its `beacon_ingest` extension (`collector-builder/exporter/beaconjsonexporter/beaconingestextension`, appending through the exporter's own `internal/runtimelog`) serves `/var/run/beacon-agent/ingest.sock`, and the hook adapter and the CLI writer, as any account but root writing the system log, hand finished lines to it through `pkg/asymptoteobserve/localingest` (`Deliverer`). The protocol is one batch per connection (`BEACON-INGEST/1`, a header naming the log, one event per line, one JSON reply saying how far it got); the server refuses a batch for any log but its own, identifies the sender only by kernel peer credentials (`SO_PEERCRED`, `LOCAL_PEERCRED`), overwrites the event's `user` with that uid and its resolved name and always derives `event.id` itself (`StampLine` re-encodes, so a sender cannot split or forge lines or reuse another event's id), and bounds connections overall and per uid, batch size, each account's bytes per second, and its own time per connection (shorter than the client's, so it reports how far it got instead of being resent). The client sends only to a socket that root owns in a directory nobody else can write (group-writable ancestors only for gid 0/1, which macOS's `/private/var/run` needs). `Deliverer.Write` sends through the socket when it answers and otherwise appends directly as before; only a direct append refused for permission (a restricted log whose collector is down) spools the line, to the account's private spool for that log (`~/.beacon/endpoint/spool/<log digest>`, 0600 under 0700), and the next line that gets through either way drains it. Root writers and per-user logs always write directly. The mode is `config.json` `log_access`, carried through repair and package upgrades (`BEACON_LOG_ACCESS` in the install scripts); install creates the `beacon-log` group (`internal/endpoint/loggroup`, getent/groupadd, dscl/dseditgroup) and `writer.RestrictSystemLog` makes the directory `root:beacon-log 02750`, the log and archives `0640` and the lock root-only `0600`, after writing the root-owned `.beacon-log-access` marker beside the log; a shared log is not narrowed in place but copied to fresh root-created files and renamed over, under its lock (bounded wait), because a descriptor opened while it was 0666 survives any chmod. A failed install restores the previous mode in its rollback, and a shared install removes a dead socket. The marker is what tells every root writer (`asymptoteobserve.RuntimeLogModes`) to keep the restricted modes. The OTLP receivers on loopback are not covered: any local process can still send OTLP, unattributed, so never claim more than the hook channel guarantees. Doctor's `runtime_log_access` covers the marker, the socket and pending spool. Unix sockets are local IPC, not a network channel, so the hooks-never-touch-the-network rule holds. On Windows the same mode runs over the named pipe `\\.\pipe\beacon-agent-ingest` (`localingest` `transport_windows.go`, go-winio): the collector creates it as the first instance, and when the name is taken (any account may create one) it reports a recoverable error and retries every few seconds rather than failing, so the rest of the collector stays up; it rejects remote clients and its DACL denies NETWORK and withholds `FILE_CREATE_PIPE_INSTANCE` from ordinary accounts, so it is not a network channel either; a client connects at identification level and sends only to a pipe owned by SYSTEM or Administrators; the server counts a connection against its account from the client process's token before reading and stamps the SID it reads by `ImpersonateNamedPipeClient` after the preamble (they must agree), with `Peer.UID` a string (decimal uid on Unix, SID on Windows) and the name from `LookupAccountSid`, bounded. Privileged writers there are SYSTEM and tokens with Administrators enabled (`CheckTokenMembership`; elevation for another group is not enough). The directory gets `sysacl.RestrictedLogDirDACL` (protected: SYSTEM and Administrators full, `beacon-log` local group read, nothing else; the lock SYSTEM and Administrators only) and everything below it is reset, because every account may bypass traverse checking; `writer.RestrictSystemLog` replaces every file directly in the directory (the log family under the lock; files outside it with another hard link are skipped) with a copy created with its final owner and DACL (`sysacl.CreateRestrictedFile`) and a POSIX-semantics rename, fails naming any file held open without sharing delete and then puts a log that was shared back to shared, and writes the marker last (on Windows it decides nothing for root writers, so a failed or killed run is not mistaken for a finished one). The marker counts there when SYSTEM or Administrators own it and no other account can write it. `loggroup` creates the local group with `net.exe` and looks it up qualified with the computer name. Doctor reads the restricted ACL (`writer.CheckRestrictedSystemLogACL`). `packaging/windows/smoke-restricted-log.ps1` runs in `windows-package-smoke` against the installed MSI with a real ordinary account. Hook and writer tests point `logging.EndpointIngest`/`writer.Ingest` at sockets of their own.-- Beacon Cloud forwarding (`cli/beacon/internal/endpoint/asymptote`, `beacon endpoint connect`, `beacon endpoint asymptote`) is Vector-shaped: Beacon writes local JSONL, Vector ships runtime lines only from the connection point forward and reads inventory from the beginning to establish the endpoint's current baseline, plus the one bounded exception of the session backfill (below), and the `bcn_device_*` key stays only in `<BaseDir>/asymptote/vector-secrets.json` via Vector's secret backend. The onboarding wizard preselects Beacon Cloud, and confirming it connects this endpoint in the same command once the local install has succeeded; an endpoint that is already enrolled is never re-enrolled, because enrollment rotates the device key. Standard mode ships locally sanitized retained content; metadata-only uses local Vector transforms to remove prompts, responses, reasoning, tool arguments/results, tool descriptions/definitions, retrieval queries/documents, evaluation explanations, agent descriptions, stop sequences, approval/policy reasons, command output, raw fields, diffs, inventory content, and MCP definitions before buffering/upload. Every text-shaped event field must be classified in `metadata_fields_test.go` (`metadataOnlyRemoved`, each with its own `del()` in `pack/metadata-transforms.toml`, or `metadataOnlyKept`); a new field fails that test until it is, and `BEACON_TEST_VECTOR_BIN` runs the transform on an event with every field set. `vector.toml` is not rendered only at connect: `asymptote.ReconcileForwarder` re-renders it in place for a connected endpoint from the current pack with the enrollment's ingest URL and recorded privacy mode, validates it with the forwarder's own Vector exactly as connect does, atomically replaces it, and restarts the forwarder only when the content changed and the forwarder is running (a stopped one reads the new config when it next starts). It never enrolls, reads or rewrites the secrets file, makes a network request, or touches `vector-data/` (checkpoints stay, so pack changes must keep source ids and fingerprinting stable), and a rejected config is a warning that keeps the old one; it is a no-op when not connected, after an incomplete connect, without an installed unit, or where `ForwarderManager` is unsupported (supervised mode). `lifecycle.Install` runs it last when services are started (so install, repair and the Linux package upgrade), repair's teardown keeps the forwarder (`UninstallOptions.KeepManagedIngest`) instead of disconnecting it, and the macOS postinstall, which installs with `--no-start`, runs the hidden `beacon endpoint asymptote reconcile --system`. Keep the ingest URL `https://`, the wire contract aligned with `beacon-ingest` (`/v1/ingest/{runtime,inventory}` and `/v1/ingest/health`), and do not add another endpoint network channel. The cloud-sandbox shuttle is the bounded exception: only with `BEACON_ORIGIN=cloud`, it can upload new runtime lines to GCS, S3, or the same Beacon ingest contract because no Vector/service manager/browser/persistent disk exists there.+- Beacon Cloud forwarding (`cli/beacon/internal/endpoint/asymptote`, `beacon endpoint connect`, `beacon endpoint asymptote`) is Vector-shaped: Beacon writes local JSONL, Vector ships runtime lines only from the connection point forward and reads inventory from the beginning to establish the endpoint's current baseline, plus the one bounded exception of the session backfill (below), and the `bcn_device_*` key stays only in `<BaseDir>/asymptote/vector-secrets.json` via Vector's secret backend. The onboarding wizard preselects Beacon Cloud, and confirming it connects this endpoint in the same command once the local install has succeeded; an endpoint that is already enrolled is never re-enrolled, because enrollment rotates the device key. Standard mode ships locally sanitized retained content; metadata-only uses local Vector transforms to remove prompts, responses, reasoning, tool arguments/results, tool descriptions/definitions, retrieval queries/documents, evaluation explanations, agent descriptions, stop sequences, approval/policy reasons, command output, raw fields, diffs, inventory content, and MCP definitions before buffering/upload. Every text-shaped event field must be classified in `metadata_fields_test.go` (`metadataOnlyRemoved`, each with its own `del()` in `pack/metadata-transforms.toml`, or `metadataOnlyKept`); a new field fails that test until it is, and `BEACON_TEST_VECTOR_BIN` runs the transform on an event with every field set. `vector.toml` is not rendered only at connect: `asymptote.ReconcileForwarder` re-renders it in place for a connected endpoint from the current pack with the enrollment's ingest URL and recorded privacy mode, validates it with the forwarder's own Vector exactly as connect does, atomically replaces it, and, when run from install, repair, the package upgrade or the hidden reconcile the macOS postinstall runs (`ReconcileOptions.Restart`), restarts a running forwarder even when nothing changed (after `vector validate` of the current config with the forwarder's own Vector, and never after a warning, so a refused config or a missing Vector leaves the running forwarder alone), as the Sentinel reconcile does: switching to restricted log access replaces the runtime log with a copy, and Vector, which recognizes a file by its first line, keeps tailing the replaced one until it restarts; an upgrade may also have installed a new Vector. A stopped one is never started and reads the new config when it next starts. The `beacon_runtime` source reads `runtime.jsonl.1` too, as the Sentinel pack does, so lines written to a replaced log before a restart are found again at the next rotation instead of lost. It never enrolls, reads or rewrites the secrets file, makes a network request, or touches `vector-data/` (checkpoints stay, so pack changes must keep source ids and fingerprinting stable), and a rejected config is a warning that keeps the old one; it is a no-op when not connected, after an incomplete connect, without an installed unit, or where `ForwarderManager` is unsupported (supervised mode). `lifecycle.Install` runs it last when services are started (so install, repair and the Linux package upgrade), repair's teardown keeps the forwarder (`UninstallOptions.KeepManagedIngest`) instead of disconnecting it, and the macOS postinstall, which installs with `--no-start`, runs the hidden `beacon endpoint asymptote reconcile --system`. Keep the ingest URL `https://`, the wire contract aligned with `beacon-ingest` (`/v1/ingest/{runtime,inventory}` and `/v1/ingest/health`), and do not add another endpoint network channel. The cloud-sandbox shuttle is the bounded exception: only with `BEACON_ORIGIN=cloud`, it can upload new runtime lines to GCS, S3, or the same Beacon ingest contract because no Vector/service manager/browser/persistent disk exists there.- Session backfill (`cli/beacon/cmd/endpoint_backfill.go`; docs in `docs/cli/endpoint-install.mdx#session-backfill` and `docs/cli/endpoint-connect.mdx#session-backfill`): after every successful install (user or system mode), every session-store collector runs once with `CollectOptions.Since` (30 days; `sessionwindow.Recent` keeps those sessions, newest first, and never touches the cursors of the rest) and a shared `writer.Budget` (24 MiB, at most 12 MiB per runtime through `Budget.Sub`; a refused append returns `writer.ErrBudgetSpent`, the collector stops with cursors past only what was written, and a manual sync reads the rest). A new session-store collector takes both fields, reads its store only through `internal/sessionfs` (a test parses every collector package to enforce it), and joins `endpointBackfillRunners` and that test's list. Every connect, first or re-connect, user or system, runs the same sweep before enrollment (skipped when install just ran it) and, before the forwarder starts, `asymptote.StageBackfill` copies the window's `harness.collection_method=poll` lines into `cloud-backfill.jsonl` beside the runtime log, which the `beacon_backfill` Vector source (fingerprinted `device_and_inode`, so each atomically restaged copy is a new file) reads from the beginning into the runtime sink through the same privacy transform. Live hook/OTLP/plugin history before the connection point stays local. Re-connects restage, so a resend of already-shipped lines is expected and rests on the deterministic `event.id`; a privacy-mode change clears the checkpoints and the restage renames the new-mode copy over the old one (kept until then so the copy is always a new inode; deleted instead when nothing restages), and `disconnect` removes it. System mode runs the collectors under `withUserHome` for the active console user (`activeConsoleUser`), with cursors under the system base directory, and reports a skip when nobody is logged in; root is reading a home the console user controls, so the sweep runs under `sessionfs.Confine` (an `os.Root` on that home, files owned by the home's owner only, non-blocking opens that refuse FIFOs/devices, SQLite read from a private snapshot under `<SystemBaseDir>/state/backfill-snapshots`, retried until the database size/change counter and WAL header are unchanged across the copy, and refused past `sessionfs.MaxSnapshotBytes` (512 MiB with its WAL) with the runtime's sync command named in the report), and refused paths read as absent and are listed in the report. User-mode sync and backfill stay unconfined. The wizard's confirm screen names the upload (`WizardOptions.BackfillDays`). Dry-run, `--no-backfill` and `BEACON_BACKFILL=0` skip all of it; the cmd tests run with `BEACON_BACKFILL=0` set in `TestMain`.- `beacon endpoint install` has a full-screen onboarding wizard on interactive user TTYs. It signs in, preselects Beacon Cloud, requires an explicit choice to opt out to Local, and asks Managed users to choose Standard or Metadata-only privacy. Signing in alone still moves no telemetry. Confirming Beacon Cloud does: the confirm screen states that it installs Beacon and starts forwarding, and names what the selected privacy mode sends, so that screen is the consent point. The managed destination is recorded only after enrollment succeeds, so a failed enrollment leaves a working local install, prints `beacon endpoint connect` as the retry, and re-offers the question on the next install. The onboarding record is written only after `lifecycle.Install` returns, because a profile written first left a failed install looking onboarded and silently skipped the wizard on the retry. Explicit `install --connect` is unchanged. The wizard is skipped for system/root/CI/piped-stdin/dry-run or `BEACON_ONBOARDING=0`; those unattended paths must never gain an account or browser dependency. Legacy `BEACON_ONBOARDING_EMAIL`/`USAGE` submissions remain only for fleet compatibility. After the destination, the wizard shows an agent tools screen; every row is preselected (opt-out, space toggles). Beacon Cloud MCP is offered only with Beacon Cloud and runs the `beacon mcp connect` flow (`connectCloudMCP` with `yes`, OAuth, detected harnesses) only after the endpoint is connected (or already was), via `finishCloudSetup`; a failed enrollment skips it and names the retry. The Beacon Agent Skills are offered for either destination and installed user-wide into `~/.agents/skills` and, when Claude Code is set up, `~/.claude/skills` (`cli/beacon/internal/agentskills`, `beacon skills install|uninstall`; a `.beacon-managed` marker decides what Beacon may replace or remove; install and repair refresh only copies Beacon already wrote). Both run after `lifecycle.Install` returns and warn rather than fail. The answers are recorded as `onboarding.cloud_mcp`/`agent_skills`. Implementation lives in `cli/beacon/internal/onboarding`, `cli/beacon/cmd/endpoint_onboarding.go`, `cli/beacon/cmd/endpoint_install.go` and `cli/beacon/cmd/agent_tools.go`; keep `docs/cli/endpoint-onboarding.mdx` and `docs/cli/skills.mdx` in sync.- The update notice on bare interactive `beacon` (`cli/beacon/cmd/root.go`, cache in `cli/beacon/internal/updatecheck/cache.go`; docs in `docs/cli/version.mdx`) follows the Codex/Claude Code pattern: it reads `~/.beacon/endpoint/update-check.json` and never waits on the network, and only when that cache is a day old does it start a detached `beacon version refresh` (hidden) that asks GitHub for the latest release and rewrites the cache, failures included. It is the CLI's one background network call; it never runs from hooks, other commands, non-TTY output, CI or dev builds, and `BEACON_UPDATE_CHECK=0` turns it off. Installs other than Homebrew and the system package get the release download, because `beacon endpoint update` applies only to the system package.diff --git a/cli/beacon/cmd/endpoint_asymptote_reconcile.go b/cli/beacon/cmd/endpoint_asymptote_reconcile.goindex 7cb69280..b703e1d0 100644--- a/cli/beacon/cmd/endpoint_asymptote_reconcile.go+++ b/cli/beacon/cmd/endpoint_asymptote_reconcile.go@@ -18,14 +18,20 @@ var reconcileManagedForwarder = asymptote.ReconcileForwarder// addAsymptoteReconcileCommand attaches `beacon endpoint asymptote reconcile`, which the macOS// package postinstall runs (it installs with --no-start, so Install's own reconcile does not// run there) and which operators can run by hand. Install and repair reconcile on their own.+//+// It always restarts a running forwarder, as the Sentinel reconcile does after an upgrade: the+// package has just installed a new Vector, and its install may have replaced the runtime log with+// a copy, which Vector only notices when it restarts.func addAsymptoteReconcileCommand(group *cobra.Command) {cmd := &cobra.Command{Use: "reconcile",Short: "Internal: re-render a connected endpoint's Beacon Cloud forwarder config in place",Long: `Re-render vector.toml for a connected endpoint from the pack this version carries,keeping the recorded ingest URL and privacy mode. Vector validates the new config-before it replaces the old one, and the forwarder restarts only when it changed.-Nothing is enrolled, the device key is not touched, and no network request is made.`,+before it replaces the old one, and a running forwarder restarts, so it runs the+Vector the package installed and reads the current runtime log, which the upgrade may+have replaced. Nothing is enrolled, the device key is not touched, and no network+request is made.`,Hidden: true,SilenceUsage: true,RunE: runAsymptoteReconcile,@@ -44,7 +50,7 @@ func runAsymptoteReconcile(cmd *cobra.Command, args []string) error {if logPath == "" {logPath = loadOrDefaultConfig().LogPath}- result, err := reconcileManagedForwarder(asymptote.ReconcileOptions{UserMode: userMode, LogPath: logPath})+ result, err := reconcileManagedForwarder(asymptote.ReconcileOptions{UserMode: userMode, LogPath: logPath, Restart: true})if endpointOpts.jsonOutput {if encodeErr := json.NewEncoder(cmd.OutOrStdout()).Encode(result); encodeErr != nil && err == nil {err = encodeErr@@ -54,6 +60,10 @@ func runAsymptoteReconcile(cmd *cobra.Command, args []string) error {if err != nil {return err}+ if result.Warning != "" {+ fmt.Fprintln(cmd.ErrOrStderr(), "Warning: "+result.Message())+ return nil+ }if message := result.Message(); message != "" {fmt.Fprintln(cmd.OutOrStdout(), message)}@@ -63,7 +73,7 @@ func runAsymptoteReconcile(cmd *cobra.Command, args []string) error {// reportManagedForwarder prints the install or repair reconcile outcome when there is something// to say: an endpoint that is not connected hears nothing about Beacon Cloud.func reportManagedForwarder(out, errOut io.Writer, result *asymptote.ReconcileResult) {- if result == nil || result.Skipped != "" || result.Unchanged {+ if result == nil || result.Skipped != "" || (result.Unchanged && !result.Restarted && result.Warning == "") {return}if result.Warning != "" {diff --git a/cli/beacon/cmd/endpoint_asymptote_reconcile_test.go b/cli/beacon/cmd/endpoint_asymptote_reconcile_test.goindex 5fd4b429..91b60ffa 100644--- a/cli/beacon/cmd/endpoint_asymptote_reconcile_test.go+++ b/cli/beacon/cmd/endpoint_asymptote_reconcile_test.go@@ -5,6 +5,8 @@ import ("strings""testing"+ "github.com/spf13/cobra"+"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/asymptote")@@ -26,4 +28,44 @@ func TestReportManagedForwarderStaysQuietUnlessSomethingChanged(t *testing.T) {if !strings.Contains(out.String(), "/v.toml") {t.Fatalf("update printed %q", out.String())}+ // A current config is still worth a line when the forwarder was restarted, or failed to be.+ out.Reset()+ reportManagedForwarder(out, errOut, &asymptote.ReconcileResult{Unchanged: true, Restarted: true})+ if !strings.Contains(out.String(), "restarted") {+ t.Fatalf("restart printed %q", out.String())+ }+ out.Reset()+ errOut.Reset()+ reportManagedForwarder(out, errOut, &asymptote.ReconcileResult{Unchanged: true, Warning: "the forwarder could not be restarted"})+ if out.Len() != 0 || !strings.Contains(errOut.String(), "could not be restarted") {+ t.Fatalf("failed restart printed %q / %q", out.String(), errOut.String())+ }+}++// The macOS package installs with --no-start and then runs this command, so it is the upgrade's+// only chance to restart a forwarder still reading a log the upgrade replaced.+func TestAsymptoteReconcileCommandAsksForARestart(t *testing.T) {+ originalOpts, originalReconcile := endpointOpts, reconcileManagedForwarder+ t.Cleanup(func() { endpointOpts, reconcileManagedForwarder = originalOpts, originalReconcile })+ endpointOpts.userMode = true+ endpointOpts.systemMode = false+ endpointOpts.logPath = "/tmp/runtime.jsonl"+ endpointOpts.jsonOutput = false+ var got asymptote.ReconcileOptions+ reconcileManagedForwarder = func(opts asymptote.ReconcileOptions) (asymptote.ReconcileResult, error) {+ got = opts+ return asymptote.ReconcileResult{Unchanged: true, Restarted: true}, nil+ }+ cmd := &cobra.Command{}+ out := &bytes.Buffer{}+ cmd.SetOut(out)+ if err := runAsymptoteReconcile(cmd, nil); err != nil {+ t.Fatal(err)+ }+ if !got.Restart || got.LogPath != "/tmp/runtime.jsonl" || !got.UserMode {+ t.Fatalf("options = %+v, want a user-mode restart of the named log", got)+ }+ if !strings.Contains(out.String(), "restarted") {+ t.Fatalf("output %q does not report the restart", out.String())+ }}diff --git a/cli/beacon/internal/endpoint/asymptote/asymptote_test.go b/cli/beacon/internal/endpoint/asymptote/asymptote_test.goindex 814a4a50..299ec62a 100644--- a/cli/beacon/internal/endpoint/asymptote/asymptote_test.go+++ b/cli/beacon/internal/endpoint/asymptote/asymptote_test.go@@ -23,7 +23,7 @@ func TestVectorConfigForwardsBothStreamsOverHTTPWithABearerSecret(t *testing.T)t.Fatalf("VectorConfig returned error: %v", err)}for _, want := range []string{- `include = ["/tmp/beacon/runtime.jsonl"]`,+ `include = ["/tmp/beacon/runtime.jsonl", "/tmp/beacon/runtime.jsonl.1"]`,`include = ["/tmp/beacon/inventory_state.jsonl"]`,`read_from = "end"`,`read_from = "beginning"`,@@ -224,7 +224,7 @@ func TestRenderVectorConfigReplacesEveryEnvironmentReference(t *testing.T) {`uri = "https://ingest.example.test/v1/ingest/runtime"`,`uri = "https://ingest.example.test/v1/ingest/inventory"`,`uri = "https://ingest.example.test/v1/ingest/health"`,- `include = ["/Users/me/.beacon/endpoint/logs/runtime.jsonl"]`,+ `include = ["/Users/me/.beacon/endpoint/logs/runtime.jsonl", "/Users/me/.beacon/endpoint/logs/runtime.jsonl.1"]`,`token = "SECRET[beacon.device_key]"`,} {if !strings.Contains(got, want) {diff --git a/cli/beacon/internal/endpoint/asymptote/pack/vector.toml.tmpl b/cli/beacon/internal/endpoint/asymptote/pack/vector.toml.tmplindex f4f9e794..0410a1ed 100644--- a/cli/beacon/internal/endpoint/asymptote/pack/vector.toml.tmpl+++ b/cli/beacon/internal/endpoint/asymptote/pack/vector.toml.tmpl@@ -22,7 +22,13 @@ path = "${BEACON_ASYMPTOTE_SECRETS_FILE}"[sources.beacon_runtime]type = "file"-include = ["{{LOG_PATH}}"]+# The first rotated file too, as the Sentinel pack reads it. Vector recognizes a file by its first+# line, so when the log is replaced by a copy (switching to restricted log access does) it keeps+# reading the replaced file until it restarts or the log rotates. At the rotation it finds its file+# again as the .1, reopens it and resumes at its checkpoint, so the lines written in between ship+# instead of being lost. A rotated file it was already reading is the same file to Vector, so+# nothing is read twice.+include = ["{{LOG_PATH}}", "{{LOG_PATH}}.1"]# Nothing recorded before the device was approved is shipped.read_from = "end"diff --git a/cli/beacon/internal/endpoint/asymptote/reconcile.go b/cli/beacon/internal/endpoint/asymptote/reconcile.goindex c1b80f3c..02b6dcdf 100644--- a/cli/beacon/internal/endpoint/asymptote/reconcile.go+++ b/cli/beacon/internal/endpoint/asymptote/reconcile.go@@ -19,6 +19,12 @@ type ReconcileOptions struct {LogPath string// Forwarder overrides the service manager; nil uses service.ForwarderManager.Forwarder Forwarder+ // Restart restarts a running forwarder even when its config and unit are current. Install,+ // repair and the package upgrade set it, because they may have replaced the runtime log with a+ // copy (switching to restricted log access does), and Vector, which recognizes a file by its+ // first line, keeps reading the replaced file until it restarts. After a restart it resumes in+ // the copy where it left off. A stopped forwarder is still never started.+ Restart bool}// ReconcileResult reports what ReconcileForwarder did.@@ -34,7 +40,8 @@ type ReconcileResult struct {Updated bool `json:"updated,omitempty"`// UnitUpdated is true when a stale service unit was rewritten.UnitUpdated bool `json:"unit_updated,omitempty"`- // Restarted is true when the forwarder was restarted to load an updated config or unit.+ // Restarted is true when the forwarder was restarted, to load an updated config or unit or+ // because the caller asked for a restart.Restarted bool `json:"restarted,omitempty"`// Warning explains a refused check/update or a failed restart. Updated and UnitUpdated// report any changes already written; a warning does not imply those were rolled back.@@ -59,6 +66,8 @@ func (r ReconcileResult) Message() string {return "Beacon Cloud forwarder config updated and the forwarder restarted (" + r.VectorConfig + ")."case r.Updated:return "Beacon Cloud forwarder config updated (" + r.VectorConfig + "); it takes effect when the forwarder next starts."+ case r.Unchanged && r.Restarted:+ return "Beacon Cloud forwarder config is current; the forwarder restarted so it reads the current runtime log."case r.Unchanged:return "Beacon Cloud forwarder config is current."case r.Skipped != "":@@ -77,8 +86,9 @@ func (r ReconcileResult) Message() string {// endpoint's runtime log. It never enrolls, never reads the device key or rewrites the secrets// file, makes no network request, and leaves the Vector data directory and its checkpoints// alone. The new config is validated by Vector exactly as connect validates it before it-// replaces the old one, and the forwarder is restarted only when the config or launchd log paths changed. A config-// Vector rejects is reported as a warning and the running forwarder keeps the old one.+// replaces the old one, and a running forwarder is restarted when the config or launchd log paths+// changed, or always when opts.Restart is set. A config Vector rejects is reported as a warning and+// the running forwarder keeps the old one.//// The returned error is reserved for a failure that leaves something to fix by hand (the// validated config could not be written); every reason to leave a working forwarder alone is a@@ -106,6 +116,44 @@ func ReconcileForwarder(opts ReconcileOptions) (ReconcileResult, error) {result.Skipped = "forwarder service is not installed (" + unitPath + ")"return result, nil}+ result, err := reconcileFiles(opts, manager)+ if err != nil {+ return result, err+ }+ // A warning means something was kept or is missing (the new config was refused, the Vector or+ // the unit is unusable), and a restart could stop a forwarder that is still running fine, so it+ // never restarts. Otherwise a changed config or unit is loaded, and an unchanged one is restarted+ // only when the caller asked.+ changed := result.Updated || result.UnitUpdated+ if result.Warning != "" || (!changed && !opts.Restart) {+ return result, nil+ }+ // Restart only a forwarder that is running, so reconcile never starts one an operator stopped.+ // Loaded is not enough: on systemd an enabled unit that was stopped still reports Loaded. A+ // forwarder that is not running reads the new config when it is next started.+ if !manager.Status().Running {+ return result, nil+ }+ if err := manager.Load(); err != nil {+ failed := fmt.Sprintf("the forwarder could not be restarted and may be stopped; check `beacon endpoint status`: %v", err)+ if changed {+ failed = fmt.Sprintf("forwarder updated (%s) but it could not be restarted: %v", result.VectorConfig, err)+ }+ if result.Warning != "" {+ failed = result.Warning + "; " + failed+ }+ result.Warning = failed+ return result, nil+ }+ result.Restarted = true+ return result, nil+}++// reconcileFiles is ReconcileForwarder's config and unit half: it brings vector.toml and the+// service unit up to date for an installed forwarder and reports what it did, and never restarts+// anything.+func reconcileFiles(opts ReconcileOptions, manager Forwarder) (ReconcileResult, error) {+ var result ReconcileResultconfigPath := VectorConfigPath(opts.UserMode)result.VectorConfig = configPath@@ -181,6 +229,13 @@ func ReconcileForwarder(opts ReconcileOptions) (ReconcileResult, error) {}if configCurrent && unitCurrent {result.Unchanged = true+ // A restart loads this config into the Vector the service runs now, which an upgrade may+ // have replaced, so it must still accept it. If not, the running forwarder is left alone.+ if opts.Restart {+ if err := ValidateVectorConfig(vector.Path, configPath); err != nil {+ result.Warning = fmt.Sprintf("left the forwarder running without a restart because its Vector rejects the current config: %v", err)+ }+ }return result, nil}if !configCurrent {@@ -208,16 +263,5 @@ func ReconcileForwarder(opts ReconcileOptions) (ReconcileResult, error) {}result.UnitUpdated = true}- // Restart only a forwarder that is running, so reconcile never starts one an operator stopped.- // Loaded is not enough: on systemd an enabled unit that was stopped still reports Loaded. A- // forwarder that is not running reads the new config when it is next started.- if !manager.Status().Running {- return result, nil- }- if err := manager.Load(); err != nil {- result.Warning = fmt.Sprintf("forwarder updated (%s) but it could not be restarted: %v", configPath, err)- return result, nil- }- result.Restarted = truereturn result, nil}diff --git a/cli/beacon/internal/endpoint/asymptote/reconcile_test.go b/cli/beacon/internal/endpoint/asymptote/reconcile_test.goindex 365bad6d..65c30ab9 100644--- a/cli/beacon/internal/endpoint/asymptote/reconcile_test.go+++ b/cli/beacon/internal/endpoint/asymptote/reconcile_test.go@@ -3,6 +3,7 @@ package asymptoteimport ("bytes""context"+ "errors""os""path/filepath""strings"@@ -174,6 +175,106 @@ func TestReconcileLeavesACurrentConfigAndTheForwarderAlone(t *testing.T) {f.assertCredentialsAndCheckpointsUntouched(t)}+// Switching to restricted log access replaces the runtime log with a copy that starts with the same+// line, and Vector keeps tailing the replaced file until it restarts. Install, repair and the+// package upgrade therefore ask for a restart even when the config is current; nothing is+// rewritten.+func TestReconcileRestartsARunningForwarderWithACurrentConfigWhenAsked(t *testing.T) {+ f := newReconcileFixture(t, "standard")+ before, _ := os.ReadFile(VectorConfigPath(true))+ beforeInfo, _ := os.Stat(VectorConfigPath(true))+ loads, unloads := f.fwd.loads, f.fwd.unloads++ result, err := ReconcileForwarder(ReconcileOptions{UserMode: true, Forwarder: f.fwd, Restart: true})+ if err != nil {+ t.Fatal(err)+ }+ if !result.Unchanged || result.Updated || result.UnitUpdated || !result.Restarted || result.Warning != "" {+ t.Fatalf("result = %+v, want an unchanged config and a restart", result)+ }+ if f.fwd.loads != loads+1 || f.fwd.unloads != unloads {+ t.Fatalf("forwarder loads %d->%d unloads %d->%d, want exactly one restart", loads, f.fwd.loads, unloads, f.fwd.unloads)+ }+ after, _ := os.ReadFile(VectorConfigPath(true))+ afterInfo, _ := os.Stat(VectorConfigPath(true))+ if !bytes.Equal(before, after) || !afterInfo.ModTime().Equal(beforeInfo.ModTime()) {+ t.Fatal("a requested restart rewrote a current config")+ }+ if !strings.Contains(result.Message(), "restarted") {+ t.Fatalf("message %q does not say the forwarder restarted", result.Message())+ }+ f.assertCredentialsAndCheckpointsUntouched(t)+}++// A requested restart never starts a forwarder an operator stopped.+func TestReconcileRestartLeavesAStoppedForwarderStopped(t *testing.T) {+ f := newReconcileFixture(t, "standard")+ f.fwd.stopped = true+ loads := f.fwd.loads++ result, err := ReconcileForwarder(ReconcileOptions{UserMode: true, Forwarder: f.fwd, Restart: true})+ if err != nil {+ t.Fatal(err)+ }+ if !result.Unchanged || result.Restarted {+ t.Fatalf("result = %+v, want unchanged without a restart", result)+ }+ if f.fwd.loads != loads {+ t.Fatal("a requested restart started a forwarder an operator stopped")+ }+}++// A restart that fails is reported: on launchd the bootout has already run, so the forwarder may+// be stopped.+func TestReconcileReportsAFailedRequestedRestart(t *testing.T) {+ f := newReconcileFixture(t, "standard")+ f.fwd.loadErr = errors.New("bootstrap failed")++ result, err := ReconcileForwarder(ReconcileOptions{UserMode: true, Forwarder: f.fwd, Restart: true})+ if err != nil {+ t.Fatal(err)+ }+ if result.Restarted || !strings.Contains(result.Warning, "bootstrap failed") || !strings.Contains(result.Warning, "beacon endpoint status") {+ t.Fatalf("result = %+v, want a warning naming the failed restart", result)+ }+}++// A requested restart never takes down a forwarder that is running fine. The kept config after a+// refused render, and a current config the forwarder's own Vector now rejects, would both leave+// nothing running after a restart, so neither restarts.+func TestReconcileRequestedRestartNeverStopsAWorkingForwarder(t *testing.T) {+ for _, stale := range []bool{true, false} {+ f := newReconcileFixture(t, "metadata-only")+ if stale {+ writeStaleConfig(t)+ }+ before, _ := os.ReadFile(VectorConfigPath(true))+ enrollment, err := LoadEnrollment(true)+ if err != nil {+ t.Fatal(err)+ }+ enrollment.VectorBin = fakeVector(t, "0.56.0", 78)+ if err := SaveEnrollment(true, *enrollment); err != nil {+ t.Fatal(err)+ }+ loads := f.fwd.loads++ result, err := ReconcileForwarder(ReconcileOptions{UserMode: true, Forwarder: f.fwd, Restart: true})+ if err != nil {+ t.Fatal(err)+ }+ if result.Updated || result.Restarted || !strings.Contains(result.Warning, "reject") {+ t.Fatalf("stale=%v: result = %+v, want a warning and no restart", stale, result)+ }+ if f.fwd.loads != loads {+ t.Fatalf("stale=%v: a requested restart loaded a config the forwarder's Vector rejects", stale)+ }+ if got, _ := os.ReadFile(VectorConfigPath(true)); !bytes.Equal(got, before) {+ t.Fatalf("stale=%v: the config changed", stale)+ }+ }+}+func TestReconcileKeepsTheOldConfigWhenVectorRejectsTheNewOne(t *testing.T) {f := newReconcileFixture(t, "metadata-only")stale := writeStaleConfig(t)diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.goindex cf932437..2397b839 100644--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go@@ -62,9 +62,12 @@ var (// scriptForwarderStatuses is the seam for reading those forwarders' state in GetStatus.scriptForwarderStatuses = service.ScriptForwarderStatuses// reconcileManagedForwarder is the seam for the Beacon Cloud forwarder reconcile, so tests can- // see whether Install reaches it without a connected endpoint or a service manager.+ // see whether Install reaches it without a connected endpoint or a service manager. It always+ // restarts a running forwarder, as the Sentinel one below does: an install or repair may have+ // replaced the log with a copy (switching to restricted log access does), which Vector only+ // notices when it restarts, and a package upgrade may have installed a new Vector.reconcileManagedForwarder = func(userMode bool, logPath string) (asymptote.ReconcileResult, error) {- return asymptote.ReconcileForwarder(asymptote.ReconcileOptions{UserMode: userMode, LogPath: logPath})+ return asymptote.ReconcileForwarder(asymptote.ReconcileOptions{UserMode: userMode, LogPath: logPath, Restart: true})}// reconcileSentinelForwarder and removeSentinelForwarder are the seams for the managed Sentinel// forwarder. Install always restarts it: an install or repair may have replaced the log with adiff --git a/cli/beacon/internal/endpoint/siempack/log_paths_test.go b/cli/beacon/internal/endpoint/siempack/log_paths_test.goindex 08ad8705..be0eb623 100644--- a/cli/beacon/internal/endpoint/siempack/log_paths_test.go+++ b/cli/beacon/internal/endpoint/siempack/log_paths_test.go@@ -51,7 +51,7 @@ func TestTOMLLogPathsRoundTrip(t *testing.T) {// rotated packs also read the file a rotation renamed the log to.rotated bool}{- {name: "asymptote", install: asymptote.InstallPack, render: asymptote.VectorConfig, inventory: true, backfill: true},+ {name: "asymptote", install: asymptote.InstallPack, render: asymptote.VectorConfig, inventory: true, backfill: true, rotated: true},{name: "cloudwatch", install: cloudwatch.InstallPack, render: cloudwatch.ConfigSnippet},{name: "falcon", install: falcon.InstallPack, render: falcon.ConfigSnippet},{name: "gcs", install: gcs.InstallPack, inventory: true},diff --git a/docs/cli/endpoint-connect.mdx b/docs/cli/endpoint-connect.mdxindex 550b85c5..9bb141e2 100644--- a/docs/cli/endpoint-connect.mdx+++ b/docs/cli/endpoint-connect.mdx@@ -109,7 +109,16 @@ which would rotate the device key. The re-render:- validates the new config with the forwarder's own Vector exactly as `connect` does, and onlythen replaces the old file atomically. A config Vector rejects is reported as a warning, and therunning forwarder keeps the old one;-- restarts the forwarder only when the content changed and the forwarder is running (a stopped one reads the new config when it next starts).+- restarts the forwarder when it is running, even when the config is current, after checking that+ its Vector still accepts that config. Switching to restricted log access replaces the runtime log+ with a copy, and Vector keeps reading the replaced file until it restarts, then resumes in the+ copy where it left off; an upgrade may also have installed a new Vector. A stopped forwarder is+ never started, and a forwarder whose config was refused, or whose Vector is missing, keeps running+ as it was.++The forwarder also reads the first rotated log (`runtime.jsonl.1`), as the Sentinel forwarder+does, so lines written to a replaced log before a restart are picked up at the next rotation+instead of lost. It still ships nothing written before the device was connected.It does nothing on an endpoint that is not connected, after a connect that did not finish, whenthe forwarder service is not installed, or where the service manager cannot run it (superviseddiff --git a/docs/cli/endpoint-repair.mdx b/docs/cli/endpoint-repair.mdxindex bd96e40d..e03b5e93 100644--- a/docs/cli/endpoint-repair.mdx+++ b/docs/cli/endpoint-repair.mdx@@ -15,7 +15,7 @@ Repair preserves runtime logs while reinstalling managed endpoint files. By defaDuring repair, Beacon removes the existing managed service before reinstalling it so an unhealthy collector can release local OTLP ports. If reinstall cannot complete, Beacon restores the previous endpoint configuration so local state is not left partially rolled back.-On an endpoint connected to Beacon Cloud, repair leaves the forwarder service, the device key, and Vector's checkpoints and buffer in place, and re-renders `vector.toml` from this version's forwarder pack with the recorded ingest URL and privacy mode. Vector validates the new config before it replaces the old one; the forwarder restarts only when the content changed, and a config Vector rejects is reported as a warning while the forwarder keeps running on the old one. Repair never re-enrolls the device or rotates its key, and `--no-start` leaves the forwarder untouched. See [Keeping the forwarder config current](/cli/endpoint-connect#keeping-the-forwarder-config-current).+On an endpoint connected to Beacon Cloud, repair leaves the forwarder service, the device key, and Vector's checkpoints and buffer in place, and re-renders `vector.toml` from this version's forwarder pack with the recorded ingest URL and privacy mode. Vector validates the new config before it replaces the old one; a running forwarder restarts so it reads the current runtime log, which switching to restricted log access replaces with a copy, and a config Vector rejects is reported as a warning while the forwarder keeps running on the old one. Repair never re-enrolls the device or rotates its key, and `--no-start` leaves the forwarder untouched. See [Keeping the forwarder config current](/cli/endpoint-connect#keeping-the-forwarder-config-current).## Flagsdiff --git a/packaging/macos/README.md b/packaging/macos/README.mdindex d22eb037..fffce2a7 100644--- a/packaging/macos/README.md+++ b/packaging/macos/README.md@@ -50,8 +50,8 @@ enrollment record and `0600` device key belowdisconnect --system` and `beacon endpoint uninstall --system` remove it. A packageupgrade keeps it and runs `beacon endpoint asymptote reconcile --system`, whichre-renders its `vector.toml` from the new version's pack with the recorded privacy-mode, validates it with Vector, and restarts the forwarder only when it changed; the-device key, the enrollment and Vector's checkpoints are left as they are.+mode, validates it with Vector, and restarts a running forwarder so it runs the new+Vector and reads the current runtime log, which the upgrade may have replaced; the device key, the enrollment and Vector's checkpoints are left as they are.The package postinstall also repairs endpoint user configuration for the activeconsole user when one is logged in. This user-context step points Claude Code anddiff --git a/packaging/macos/scripts/postinstall b/packaging/macos/scripts/postinstallindex ff56bdea..5a2cce5a 100755--- a/packaging/macos/scripts/postinstall+++ b/packaging/macos/scripts/postinstall@@ -135,9 +135,10 @@ if command -v launchctl >/dev/null 2>&1; then# loads it when on and removes it when off, so an upgrade keeps whatever the endpoint chose."${BEACON_BIN:-/opt/beacon/bin/beacon}" endpoint sessions install-daemon --system || \echo "Warning: scheduled session sync job not configured (endpoint is installed and running)" >&2- # A connected endpoint's Beacon Cloud forwarder config is re-rendered from this version's pack,- # validated, and swapped in with a forwarder restart only when it changed. The install above ran- # with --no-start, so it left this to the package. Never enrolls or touches the device key, and+ # A connected endpoint's Beacon Cloud forwarder config is re-rendered from this version's pack and+ # validated, and a running forwarder is restarted, so it runs the Vector this package installed and+ # reads the current runtime log, which the install may have replaced with a copy (switching to+ # restricted log access does). The install above ran with --no-start, so it left this to the package. Never enrolls or touches the device key, and# a no-op on an endpoint that is not connected. Non-fatal: a rejected config keeps the old one."${BEACON_BIN:-/opt/beacon/bin/beacon}" endpoint asymptote reconcile --system || \echo "Warning: Beacon Cloud forwarder config not reconciled (endpoint is installed and running)" >&2