Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

feat(cli): ask for an email once during interactive endpoint install

shukieshahfc44838cbee9
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 5d703945..adfa1afd 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -83,6 +83,7 @@ jobs:
./beacon --help > /tmp/beacon-help.txt
./beacon endpoint --help > /tmp/beacon-endpoint-help.txt
./beacon endpoint hooks --help > /tmp/beacon-hooks-help.txt
+ ./beacon endpoint onboarding --help > /tmp/beacon-onboarding-help.txt
./beacon endpoint integrations claude-cowork --help > /tmp/beacon-cowork-help.txt
./beacon endpoint wazuh --help > /tmp/beacon-wazuh-help.txt
./beacon endpoint rapid7 --help > /tmp/beacon-rapid7-help.txt
diff --git a/CLAUDE.md b/CLAUDE.md
index ce3c629d..9dceee37 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -18,6 +18,7 @@ Do not recreate or depend on removed `asymptote` mirror trees. Keep new work foc
- Beacon is visibility-first endpoint telemetry for local AI agent runtimes, not a hosted policy service or general endpoint protection product.
- Preserve the local-only product posture. The public Beacon build should not require a hosted account, remote policy fetch, hosted dashboard, or external network dependency during normal hook execution.
+- One narrow, deliberate exception to the no-network posture: `beacon endpoint install` asks for an email and work/personal intent once per machine and POSTs that plus install context (OS, arch, version, install method, detected runtime names, a random install ID) to an Asymptote-run signup endpoint. This is intentional product behavior for open-source attribution, not an oversight — do not remove it. It is strictly bounded: interactive TTY only, once per machine, never during hook execution, never on `--system`/root/CI/piped-stdin/`--dry-run` installs, and always skippable with `--no-onboarding` or `BEACON_ONBOARDING=0`. A failed submission never fails an install. No prompt text, telemetry event, file content, or command ever leaves the machine through it. Implementation lives in `cli/beacon/internal/onboarding` and `cli/beacon/cmd/endpoint_onboarding.go`; the README documents the payload field-by-field, so changing the fields means changing that table too.
- Do not add dependency vulnerability scanning, OSV/GHSA lookups, package remediation, or other vulnerability-enforcement flows to the public hook path.
- Do not add broad runtime enforcement unless explicitly requested. Current control behavior is limited to hook-native approvals/denials exposed by supported agent runtimes.
- Keep direct destination support scoped to local JSONL/Wazuh unless explicitly requested. Elastic support is a file-tailing pack over local JSONL; Beacon itself must not store Elastic credentials or require a hosted Elastic dependency.
diff --git a/README.md b/README.md
index 6dd11c5d..87ceda41 100644
--- a/README.md
+++ b/README.md
@@ -216,6 +216,57 @@ matching, fixtures, and supported event fields.
See the [Quickstart](https://docs.asymptotelabs.ai/cli/quickstart) docs for the
full setup paths.
+### First-run onboarding
+
+The first time you run `beacon endpoint install` in a terminal, Beacon asks two
+questions — your email and whether this is work or personal use — and sends the
+answers to Asymptote once. Knowing who runs Beacon is how we decide which runtimes
+and integrations to build next.
+
+Exactly what is sent, and nothing else:
+
+| Field | Example |
+| --- | --- |
+| Email you enter | `[email protected]` |
+| Work, personal, or evaluating | `work` |
+| OS, architecture, OS version | `darwin`, `arm64`, `15.5` |
+| Beacon version and install method | `v0.0.31`, `homebrew` |
+| Names of agent runtimes on this machine | `claude_code`, `cursor` |
+| A random install ID | `64871b2b…` |
+
+**Never sent:** prompts, file contents, commands, telemetry events, repository names,
+or anything else Beacon captures. The endpoint agent itself stays local-only — this is
+one HTTP request at install time, not an ongoing channel.
+
+It happens once per machine. The answer is recorded in `~/.beacon/profile.json`, which
+survives uninstall so a reinstall does not ask again.
+
+**It never runs non-interactively.** Package postinstall scripts, MDM deployments,
+`--system` installs, CI, `--dry-run`, and any piped or redirected stdin skip it
+silently. Unattended installs that still need it suppressed can set:
+
+```bash
+BEACON_ONBOARDING=0 beacon endpoint install
+```
+
+For a fleet rollout where you *do* want attribution but have no terminal, supply the
+answers up front:
+
+```bash
[email protected] BEACON_ONBOARDING_USAGE=work \
+ beacon endpoint install
+```
+
+Inspect or clear the record at any time:
+
+```bash
+beacon endpoint onboarding # show what was recorded
+beacon endpoint onboarding --reset # clear it
+```
+
+To have your record deleted, email the install ID shown by
+`beacon endpoint onboarding` to <[email protected]>.
+
### For Security & IT Teams
Start with the
diff --git a/cli/beacon/cmd/endpoint.go b/cli/beacon/cmd/endpoint.go
index 6b80e040..37320338 100644
--- a/cli/beacon/cmd/endpoint.go
+++ b/cli/beacon/cmd/endpoint.go
@@ -35,6 +35,8 @@ var endpointOpts struct {
noStart bool
serviceKind string
dryRun bool
+ onboardingReset bool
+ onboardingResend bool
fix bool
allTargets bool
coworkHeaders string
@@ -361,6 +363,7 @@ func init() {
endpointCmd.AddCommand(endpointUninstallCmd)
endpointCmd.AddCommand(endpointRepairCmd)
endpointCmd.AddCommand(endpointDashboardCmd)
+ endpointCmd.AddCommand(endpointOnboardingCmd)
for _, c := range buildDestinationCommands() {
endpointCmd.AddCommand(c)
}
@@ -407,6 +410,11 @@ func init() {
endpointInstallCmd.Flags().BoolVar(&endpointOpts.noStart, "no-start", false, "Write files without starting the collector service")
endpointInstallCmd.Flags().StringVar(&endpointOpts.serviceKind, "service", "", "Service manager to use: auto (default), launchd, systemd, or none for a supervised collector process")
endpointInstallCmd.Flags().BoolVar(&endpointOpts.dryRun, "dry-run", false, "Print planned actions without changing endpoint files or services")
+ endpointOnboardingCmd.Flags().BoolVar(&endpointOpts.onboardingReset, "reset", false, "Clear the onboarding record so the question is asked again")
+ endpointOnboardingCmd.Flags().BoolVar(&endpointOpts.onboardingResend, "resend", false, "Retry a signup that could not be delivered")
+ endpointOnboardingCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print the onboarding record as JSON")
+ endpointOnboardingCmd.Flags().BoolVar(&endpointOpts.userMode, "user", true, "Use per-user endpoint paths")
+ endpointOnboardingCmd.Flags().BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths and the system collector service")
endpointInstallCmd.Flags().StringVar(&endpointOpts.contentRetention, "content-retention", "", "Deprecated no-op; Beacon always captures full content subject to redaction and size limits")
_ = endpointInstallCmd.Flags().MarkHidden("content-retention")
_ = endpointInstallCmd.Flags().MarkDeprecated("content-retention", "Beacon now always captures full content; this flag is ignored")
diff --git a/cli/beacon/cmd/endpoint_install.go b/cli/beacon/cmd/endpoint_install.go
index abfa3727..834a8e30 100644
--- a/cli/beacon/cmd/endpoint_install.go
+++ b/cli/beacon/cmd/endpoint_install.go
@@ -101,6 +101,11 @@ func runEndpointInstall(cmd *cobra.Command, args []string) error {
if endpointOpts.dryRun {
return printPlannedActions(plannedInstallActions(false, serviceKind))
}
+ // Asked once, on an interactive install, before anything is written to disk. Every
+ // non-interactive path (package postinstall, MDM, CI) is gated out inside.
+ if err := maybeRunOnboarding(cmd); err != nil {
+ return err
+ }
result, err := lifecycle.Install(lifecycle.InstallOptions{
UserMode: endpointUserMode(),
LogPath: endpointOpts.logPath,
diff --git a/cli/beacon/cmd/endpoint_onboarding.go b/cli/beacon/cmd/endpoint_onboarding.go
new file mode 100644
index 00000000..16b0cf1c
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_onboarding.go
@@ -0,0 +1,322 @@
+package cmd
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/onboarding"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version"
+ "github.com/spf13/cobra"
+)
+
+// Environment overrides for onboarding.
+const (
+ // onboardingEnvEnabled set to a false-ish value skips the prompt entirely. There is
+ // no equivalent CLI flag: this exists for unattended CI and MDM installs, not as a
+ // convenient way for an interactive user to decline.
+ onboardingEnvEnabled = "BEACON_ONBOARDING"
+ // onboardingEnvEmail and onboardingEnvUsage let a headless rollout supply the
+ // answers up front. An admin deploying by MDM often does want the attribution;
+ // they just have no terminal to type it into.
+ onboardingEnvEmail = "BEACON_ONBOARDING_EMAIL"
+ onboardingEnvUsage = "BEACON_ONBOARDING_USAGE"
+)
+
+// Reasons the prompt did not run. Surfaced by `endpoint onboarding --show` so support
+// can tell "declined" apart from "never asked".
+const (
+ onboardingSkipCompleted = "already_completed"
+ onboardingSkipNotAterminal = "not_a_terminal"
+ onboardingSkipOptedOut = "opted_out"
+ onboardingSkipCI = "ci"
+ onboardingSkipSystemInstall = "system_install"
+)
+
+// Indirection points so the gate and the flow can be tested without a terminal, a
+// network, or a real home directory.
+var (
+ onboardingLoad = onboarding.Load
+ onboardingSave = onboarding.Save
+ onboardingAsk = onboarding.Prompt
+ onboardingSend = onboarding.Submit
+ onboardingStdin io.Reader = os.Stdin
+ onboardingIsTTY = defaultOnboardingIsTTY
+ onboardingIsRoot = func() bool { return os.Geteuid() == 0 }
+ onboardingProbeFn = onboarding.StartRuntimeProbe
+)
+
+// runtimeProbeBudget bounds how long submission waits on background runtime
+// discovery. The probe starts before the first question, so in practice it has
+// already finished by the time a human has typed an email.
+const runtimeProbeBudget = 2 * time.Second
+
+// submitBudget bounds the whole submission so a wedged endpoint cannot stall an
+// install behind it.
+const submitBudget = 6 * time.Second
+
+func defaultOnboardingIsTTY() bool {
+ return isCharDevice(os.Stdin) && isCharDevice(os.Stdout)
+}
+
+// maybeRunOnboarding runs the one-time signup prompt if this install should ask.
+//
+// It is called from `endpoint install` after the --dry-run early return, so a dry run
+// never prompts. An error returned here does stop the install: the prompt is a
+// required step on an interactive terminal, and every refusal path names the opt-out.
+func maybeRunOnboarding(cmd *cobra.Command) error {
+ profile := onboardingLoad()
+
+ // Someone who already answered is never asked again, but a submission that failed
+ // on a flaky network still deserves a quiet retry.
+ if profile.Prompted() {
+ resendPendingOnboarding(&profile)
+ return nil
+ }
+
+ // A headless rollout that supplied answers is recorded without a terminal.
+ if email, usage, ok := onboardingAnswersFromEnv(cmd.ErrOrStderr()); ok {
+ completeOnboarding(cmd, &profile, email, usage, nil)
+ return nil
+ }
+
+ if _, skipped := onboardingSkipReason(profile); skipped {
+ return nil
+ }
+
+ // Discovery shells out to every installed runtime, so start it now and collect it
+ // after the questions. The latency disappears behind the user reading and typing.
+ probe := onboardingProbeFn()
+
+ answers, err := onboardingAsk(onboardingStdin, cmd.OutOrStdout())
+ if err != nil {
+ return err
+ }
+ completeOnboarding(cmd, &profile, answers.Email, answers.Usage, probe)
+ return nil
+}
+
+// onboardingSkipReason reports whether the prompt should stay silent, and why.
+func onboardingSkipReason(profile onboarding.Profile) (string, bool) {
+ switch {
+ case profile.Prompted():
+ return onboardingSkipCompleted, true
+ case !onboardingEnabledByEnv():
+ return onboardingSkipOptedOut, true
+ // A system install is the MDM and package-postinstall path. It runs as root with
+ // no console user to ask, and blocking it would break fleet deployment.
+ case !endpointUserMode(), onboardingIsRoot():
+ return onboardingSkipSystemInstall, true
+ case isCIEnvironment():
+ return onboardingSkipCI, true
+ case !onboardingIsTTY():
+ return onboardingSkipNotAterminal, true
+ default:
+ return "", false
+ }
+}
+
+// onboardingEnabledByEnv reports whether BEACON_ONBOARDING permits the prompt.
+func onboardingEnabledByEnv() bool {
+ switch strings.ToLower(strings.TrimSpace(os.Getenv(onboardingEnvEnabled))) {
+ case "0", "false", "no", "off":
+ return false
+ default:
+ return true
+ }
+}
+
+// isCIEnvironment covers the CI systems that set a conventional marker. The terminal
+// check already catches most of them; this is belt and braces for runners that
+// allocate a pty.
+func isCIEnvironment() bool {
+ for _, key := range []string{"CI", "CONTINUOUS_INTEGRATION", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE", "JENKINS_URL", "TEAMCITY_VERSION"} {
+ if strings.TrimSpace(os.Getenv(key)) != "" {
+ return true
+ }
+ }
+ return false
+}
+
+// onboardingAnswersFromEnv reads pre-supplied answers for a headless rollout.
+//
+// Bad values are reported and ignored rather than treated as an error: this path runs
+// inside fleet deployments, where failing an install over a typo in an MDM variable
+// would be far worse than losing one attribution row.
+func onboardingAnswersFromEnv(stderr io.Writer) (string, string, bool) {
+ rawEmail := strings.TrimSpace(os.Getenv(onboardingEnvEmail))
+ rawUsage := strings.TrimSpace(os.Getenv(onboardingEnvUsage))
+ if rawEmail == "" || rawUsage == "" {
+ return "", "", false
+ }
+ if !onboardingEnabledByEnv() {
+ return "", "", false
+ }
+ email, err := onboarding.NormalizeEmail(rawEmail)
+ if err != nil {
+ fmt.Fprintf(stderr, "beacon: ignoring %s: %v\n", onboardingEnvEmail, err)
+ return "", "", false
+ }
+ usage, ok := onboarding.NormalizeUsage(rawUsage)
+ if !ok {
+ fmt.Fprintf(stderr, "beacon: ignoring %s=%q: expected one of work, personal, evaluating\n", onboardingEnvUsage, rawUsage)
+ return "", "", false
+ }
+ return email, usage, true
+}
+
+// completeOnboarding submits the answers and records the outcome.
+//
+// It never returns an error. Once the user has answered, the install belongs to them;
+// a signup endpoint being unreachable is our problem, not theirs.
+func completeOnboarding(cmd *cobra.Command, profile *onboarding.Profile, email, usage string, probe *onboarding.RuntimeProbe) {
+ installID, err := onboarding.EnsureInstallID(profile)
+ if err != nil {
+ // Without an install ID there is no dedupe key, so there is nothing sensible
+ // to send. Record the answer locally so we still never ask twice.
+ installID = ""
+ }
+
+ mode := "user"
+ if !endpointUserMode() {
+ mode = "system"
+ }
+ submission := onboarding.NewSubmission(
+ installID,
+ email,
+ usage,
+ version.GetVersion(),
+ mode,
+ probe.Wait(runtimeProbeBudget),
+ )
+
+ ctx, cancel := context.WithTimeout(context.Background(), submitBudget)
+ defer cancel()
+ outcome, sendErr := onboardingSend(ctx, submission)
+
+ profile.Onboarding = onboarding.Onboarding{
+ CompletedAt: time.Now().UTC().Format(time.RFC3339),
+ Outcome: outcome,
+ Email: email,
+ Usage: usage,
+ BeaconVersion: version.GetVersion(),
+ }
+ // Keep the payload only when resending could still work. A rejected submission is
+ // terminal, and holding the address on disk past that point serves nobody.
+ if outcome == onboarding.OutcomePending {
+ profile.Pending = &submission
+ } else {
+ profile.Pending = nil
+ }
+
+ if err := onboardingSave(*profile); err != nil {
+ fmt.Fprintf(cmd.ErrOrStderr(), "beacon: could not record onboarding: %v\n", err)
+ }
+ if sendErr != nil && outcome == onboarding.OutcomeRejected {
+ fmt.Fprintf(cmd.ErrOrStderr(), "beacon: signup was not accepted (%v); continuing.\n", sendErr)
+ }
+}
+
+// resendPendingOnboarding retries a submission that previously failed. Best effort
+// and silent: the user already answered and must not be bothered about it again.
+func resendPendingOnboarding(profile *onboarding.Profile) {
+ if profile.Pending == nil {
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), submitBudget)
+ defer cancel()
+
+ outcome, _ := onboardingSend(ctx, *profile.Pending)
+ if outcome == onboarding.OutcomePending {
+ return
+ }
+ profile.Onboarding.Outcome = outcome
+ profile.Pending = nil
+ _ = onboardingSave(*profile)
+}
+
+var endpointOnboardingCmd = &cobra.Command{
+ Use: "onboarding",
+ Short: "Show or reset the one-time Beacon onboarding record",
+ SilenceUsage: true,
+ RunE: runEndpointOnboarding,
+}
+
+type endpointOnboardingStatus struct {
+ Prompted bool `json:"prompted"`
+ CompletedAt string `json:"completed_at,omitempty"`
+ Outcome string `json:"outcome,omitempty"`
+ Email string `json:"email,omitempty"`
+ Usage string `json:"usage,omitempty"`
+ InstallID string `json:"install_id,omitempty"`
+ BeaconVersion string `json:"beacon_version,omitempty"`
+ Pending bool `json:"pending_submission"`
+ SkipReason string `json:"skip_reason,omitempty"`
+ ProfilePath string `json:"profile_path"`
+ Endpoint string `json:"endpoint"`
+}
+
+func runEndpointOnboarding(cmd *cobra.Command, args []string) error {
+ out := cmd.OutOrStdout()
+
+ if endpointOpts.onboardingReset {
+ if err := os.Remove(onboarding.Path()); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ fmt.Fprintf(out, "Onboarding record cleared: %s\n", onboarding.Path())
+ return nil
+ }
+
+ profile := onboardingLoad()
+
+ if endpointOpts.onboardingResend {
+ if profile.Pending == nil {
+ fmt.Fprintln(out, "No pending signup to resend.")
+ return nil
+ }
+ resendPendingOnboarding(&profile)
+ fmt.Fprintf(out, "Resend attempted. Outcome: %s\n", profile.Onboarding.Outcome)
+ return nil
+ }
+
+ reason, _ := onboardingSkipReason(profile)
+ status := endpointOnboardingStatus{
+ Prompted: profile.Prompted(),
+ CompletedAt: profile.Onboarding.CompletedAt,
+ Outcome: profile.Onboarding.Outcome,
+ Email: profile.Onboarding.Email,
+ Usage: profile.Onboarding.Usage,
+ InstallID: profile.InstallID,
+ BeaconVersion: profile.Onboarding.BeaconVersion,
+ Pending: profile.Pending != nil,
+ SkipReason: reason,
+ ProfilePath: onboarding.Path(),
+ Endpoint: onboarding.Endpoint(),
+ }
+
+ if endpointOpts.jsonOutput {
+ return json.NewEncoder(out).Encode(status)
+ }
+
+ if !status.Prompted {
+ fmt.Fprintln(out, "Onboarding: not yet completed")
+ if status.SkipReason != "" {
+ fmt.Fprintf(out, "Would skip because: %s\n", status.SkipReason)
+ }
+ } else {
+ fmt.Fprintf(out, "Onboarding: completed %s (%s)\n", status.CompletedAt, status.Outcome)
+ fmt.Fprintf(out, "Email: %s\n", status.Email)
+ fmt.Fprintf(out, "Usage: %s\n", status.Usage)
+ }
+ fmt.Fprintf(out, "Install ID: %s\n", status.InstallID)
+ fmt.Fprintf(out, "Profile: %s\n", status.ProfilePath)
+ fmt.Fprintf(out, "Endpoint: %s\n", status.Endpoint)
+ if status.Pending {
+ fmt.Fprintln(out, "A signup is queued for resend. Retry with: beacon endpoint onboarding --resend")
+ }
+ return nil
+}
diff --git a/cli/beacon/cmd/endpoint_onboarding_test.go b/cli/beacon/cmd/endpoint_onboarding_test.go
new file mode 100644
index 00000000..fee8c3d7
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_onboarding_test.go
@@ -0,0 +1,463 @@
+package cmd
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "io"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/onboarding"
+ "github.com/spf13/cobra"
+)
+
+// onboardingHarness isolates the package-level state the onboarding gate reads, so a
+// test can describe exactly one situation without inheriting another's leftovers.
+type onboardingHarness struct {
+ t *testing.T
+ cmd *cobra.Command
+ stdout *bytes.Buffer
+ stderr *bytes.Buffer
+ asked bool
+ sent []onboarding.Submission
+ saved []onboarding.Profile
+ loaded onboarding.Profile
+ answers onboarding.Answers
+ askErr error
+ outcome string
+ sendErr error
+ probeRuns int
+}
+
+func newOnboardingHarness(t *testing.T) *onboardingHarness {
+ t.Helper()
+
+ h := &onboardingHarness{
+ t: t,
+ stdout: &bytes.Buffer{},
+ stderr: &bytes.Buffer{},
+ answers: onboarding.Answers{Email: "[email protected]", Usage: onboarding.UsageWork},
+ outcome: onboarding.OutcomeSubmitted,
+ }
+ h.cmd = &cobra.Command{}
+ h.cmd.SetOut(h.stdout)
+ h.cmd.SetErr(h.stderr)
+
+ // An interactive per-user install with nothing opted out: the one situation in
+ // which the prompt is supposed to appear. Each test moves one thing off this base.
+ prevOpts := endpointOpts
+ endpointOpts.userMode = true
+ endpointOpts.systemMode = false
+ endpointOpts.jsonOutput = false
+ endpointOpts.onboardingReset = false
+ endpointOpts.onboardingResend = false
+
+ for _, key := range []string{"CI", "CONTINUOUS_INTEGRATION", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE", "JENKINS_URL", "TEAMCITY_VERSION"} {
+ t.Setenv(key, "")
+ }
+ t.Setenv(onboardingEnvEnabled, "")
+ t.Setenv(onboardingEnvEmail, "")
+ t.Setenv(onboardingEnvUsage, "")
+ t.Setenv("HOME", t.TempDir())
+
+ prevLoad, prevSave, prevAsk, prevSend := onboardingLoad, onboardingSave, onboardingAsk, onboardingSend
+ prevTTY, prevRoot, prevProbe := onboardingIsTTY, onboardingIsRoot, onboardingProbeFn
+
+ onboardingLoad = func() onboarding.Profile { return h.loaded }
+ onboardingSave = func(p onboarding.Profile) error {
+ h.saved = append(h.saved, p)
+ return nil
+ }
+ onboardingAsk = func(io.Reader, io.Writer) (onboarding.Answers, error) {
+ h.asked = true
+ return h.answers, h.askErr
+ }
+ onboardingSend = func(_ context.Context, s onboarding.Submission) (string, error) {
+ h.sent = append(h.sent, s)
+ return h.outcome, h.sendErr
+ }
+ onboardingIsTTY = func() bool { return true }
+ onboardingIsRoot = func() bool { return false }
+ onboardingProbeFn = func() *onboarding.RuntimeProbe {
+ h.probeRuns++
+ return nil
+ }
+
+ t.Cleanup(func() {
+ endpointOpts = prevOpts
+ onboardingLoad, onboardingSave, onboardingAsk, onboardingSend = prevLoad, prevSave, prevAsk, prevSend
+ onboardingIsTTY, onboardingIsRoot, onboardingProbeFn = prevTTY, prevRoot, prevProbe
+ })
+ return h
+}
+
+func TestMaybeRunOnboardingPromptsOnInteractiveInstall(t *testing.T) {
+ h := newOnboardingHarness(t)
+
+ if err := maybeRunOnboarding(h.cmd); err != nil {
+ t.Fatalf("maybeRunOnboarding returned error: %v", err)
+ }
+ if !h.asked {
+ t.Fatalf("expected the prompt to run on an interactive per-user install")
+ }
+ if len(h.sent) != 1 {
+ t.Fatalf("submissions = %d, want 1", len(h.sent))
+ }
+ if h.sent[0].Email != "[email protected]" || h.sent[0].Usage != onboarding.UsageWork {
+ t.Fatalf("submission = %+v, want the prompt answers", h.sent[0])
+ }
+ if h.sent[0].InstallMode != "user" {
+ t.Fatalf("install_mode = %q, want user", h.sent[0].InstallMode)
+ }
+ if len(h.saved) != 1 || !h.saved[0].Prompted() {
+ t.Fatalf("saved = %+v, want one completed profile", h.saved)
+ }
+ if h.saved[0].InstallID == "" {
+ t.Fatalf("saved profile has no install ID")
+ }
+}
+
+// Every one of these is a real deployment path. A prompt in any of them hangs an
+// install that no human is watching.
+func TestMaybeRunOnboardingStaysSilentWhenGated(t *testing.T) {
+ cases := []struct {
+ name string
+ arrange func(t *testing.T, h *onboardingHarness)
+ wantReason string
+ }{
+ {
+ name: "already completed",
+ arrange: func(_ *testing.T, h *onboardingHarness) {
+ h.loaded = onboarding.Profile{Onboarding: onboarding.Onboarding{CompletedAt: "2026-08-07T00:00:00Z"}}
+ },
+ wantReason: onboardingSkipCompleted,
+ },
+ {
+ name: "BEACON_ONBOARDING=0",
+ arrange: func(t *testing.T, _ *onboardingHarness) { t.Setenv(onboardingEnvEnabled, "0") },
+ wantReason: onboardingSkipOptedOut,
+ },
+ {
+ name: "BEACON_ONBOARDING=false",
+ arrange: func(t *testing.T, _ *onboardingHarness) { t.Setenv(onboardingEnvEnabled, "false") },
+ wantReason: onboardingSkipOptedOut,
+ },
+ {
+ name: "system install",
+ arrange: func(_ *testing.T, _ *onboardingHarness) { endpointOpts.systemMode = true },
+ wantReason: onboardingSkipSystemInstall,
+ },
+ {
+ name: "running as root",
+ arrange: func(_ *testing.T, _ *onboardingHarness) { onboardingIsRoot = func() bool { return true } },
+ wantReason: onboardingSkipSystemInstall,
+ },
+ {
+ name: "CI",
+ arrange: func(t *testing.T, _ *onboardingHarness) { t.Setenv("CI", "true") },
+ wantReason: onboardingSkipCI,
+ },
+ {
+ name: "GitHub Actions",
+ arrange: func(t *testing.T, _ *onboardingHarness) { t.Setenv("GITHUB_ACTIONS", "true") },
+ wantReason: onboardingSkipCI,
+ },
+ {
+ name: "piped stdin",
+ arrange: func(_ *testing.T, _ *onboardingHarness) { onboardingIsTTY = func() bool { return false } },
+ wantReason: onboardingSkipNotAterminal,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ h := newOnboardingHarness(t)
+ tc.arrange(t, h)
+
+ reason, skipped := onboardingSkipReason(h.loaded)
+ if !skipped {
+ t.Fatalf("onboardingSkipReason() reported the prompt should run")
+ }
+ if reason != tc.wantReason {
+ t.Fatalf("skip reason = %q, want %q", reason, tc.wantReason)
+ }
+
+ if err := maybeRunOnboarding(h.cmd); err != nil {
+ t.Fatalf("maybeRunOnboarding returned error: %v", err)
+ }
+ if h.asked {
+ t.Fatalf("the prompt ran despite %s", tc.name)
+ }
+ if len(h.sent) != 0 {
+ t.Fatalf("submitted %d payloads while gated, want 0", len(h.sent))
+ }
+ if h.stdout.Len() != 0 {
+ t.Fatalf("gated onboarding wrote to stdout: %q", h.stdout.String())
+ }
+ })
+ }
+}
+
+// A user who cannot get past the prompt stops the install.
+func TestMaybeRunOnboardingPropagatesPromptFailure(t *testing.T) {
+ h := newOnboardingHarness(t)
+ h.askErr = onboarding.ErrTooManyAttempts
+
+ err := maybeRunOnboarding(h.cmd)
+ if err == nil {
+ t.Fatalf("maybeRunOnboarding returned nil, want the prompt failure to stop the install")
+ }
+ if strings.Contains(err.Error(), "BEACON_ONBOARDING") {
+ t.Fatalf("error %q leaks the unattended-install escape hatch", err)
+ }
+ if len(h.saved) != 0 {
+ t.Fatalf("saved a profile for an unanswered prompt: %+v", h.saved)
+ }
+}
+
+// The user answered; the network did not cooperate. That is our problem, not theirs.
+func TestMaybeRunOnboardingSurvivesSubmissionFailure(t *testing.T) {
+ h := newOnboardingHarness(t)
+ h.outcome = onboarding.OutcomePending
+ h.sendErr = errors.New("connection refused")
+
+ if err := maybeRunOnboarding(h.cmd); err != nil {
+ t.Fatalf("maybeRunOnboarding returned error: %v", err)
+ }
+ if len(h.saved) != 1 {
+ t.Fatalf("saved = %d profiles, want 1", len(h.saved))
+ }
+ saved := h.saved[0]
+ if !saved.Prompted() {
+ t.Fatalf("profile is not marked completed, so the user would be asked again")
+ }
+ if saved.Onboarding.Outcome != onboarding.OutcomePending {
+ t.Fatalf("outcome = %q, want %q", saved.Onboarding.Outcome, onboarding.OutcomePending)
+ }
+ if saved.Pending == nil {
+ t.Fatalf("pending payload was not kept, so the signup can never be resent")
+ }
+}
+
+// A refusal is terminal, and the address should not linger on disk afterwards.
+func TestMaybeRunOnboardingDropsPayloadWhenRejected(t *testing.T) {
+ h := newOnboardingHarness(t)
+ h.outcome = onboarding.OutcomeRejected
+ h.sendErr = errors.New("signup endpoint returned 429 Too Many Requests")
+
+ if err := maybeRunOnboarding(h.cmd); err != nil {
+ t.Fatalf("maybeRunOnboarding returned error: %v", err)
+ }
+ if h.saved[0].Pending != nil {
+ t.Fatalf("kept a payload for a terminal rejection")
+ }
+ if !strings.Contains(h.stderr.String(), "continuing") {
+ t.Fatalf("stderr = %q, want a note that the install continues", h.stderr.String())
+ }
+}
+
+func TestMaybeRunOnboardingResendsPendingSubmission(t *testing.T) {
+ h := newOnboardingHarness(t)
+ pending := onboarding.Submission{InstallID: "abc123", Email: "[email protected]"}
+ h.loaded = onboarding.Profile{
+ InstallID: "abc123",
+ Onboarding: onboarding.Onboarding{CompletedAt: "2026-08-07T00:00:00Z", Outcome: onboarding.OutcomePending},
+ Pending: &pending,
+ }
+
+ if err := maybeRunOnboarding(h.cmd); err != nil {
+ t.Fatalf("maybeRunOnboarding returned error: %v", err)
+ }
+ if h.asked {
+ t.Fatalf("re-prompted a user who already answered")
+ }
+ if len(h.sent) != 1 || h.sent[0].InstallID != "abc123" {
+ t.Fatalf("sent = %+v, want the pending payload resent once", h.sent)
+ }
+ if len(h.saved) != 1 || h.saved[0].Pending != nil {
+ t.Fatalf("saved = %+v, want the pending payload cleared after success", h.saved)
+ }
+}
+
+func TestMaybeRunOnboardingKeepsPendingWhenResendFails(t *testing.T) {
+ h := newOnboardingHarness(t)
+ h.outcome = onboarding.OutcomePending
+ pending := onboarding.Submission{InstallID: "abc123"}
+ h.loaded = onboarding.Profile{
+ Onboarding: onboarding.Onboarding{CompletedAt: "2026-08-07T00:00:00Z", Outcome: onboarding.OutcomePending},
+ Pending: &pending,
+ }
+
+ if err := maybeRunOnboarding(h.cmd); err != nil {
+ t.Fatalf("maybeRunOnboarding returned error: %v", err)
+ }
+ if len(h.saved) != 0 {
+ t.Fatalf("rewrote the profile on a failed resend: %+v", h.saved)
+ }
+}
+
+// An MDM rollout has no terminal but often does want the attribution.
+func TestMaybeRunOnboardingAcceptsEnvironmentAnswersHeadless(t *testing.T) {
+ h := newOnboardingHarness(t)
+ onboardingIsTTY = func() bool { return false }
+ t.Setenv(onboardingEnvEmail, " [email protected] ")
+ t.Setenv(onboardingEnvUsage, "work")
+
+ if err := maybeRunOnboarding(h.cmd); err != nil {
+ t.Fatalf("maybeRunOnboarding returned error: %v", err)
+ }
+ if h.asked {
+ t.Fatalf("prompted despite pre-supplied answers")
+ }
+ if len(h.sent) != 1 {
+ t.Fatalf("submissions = %d, want 1", len(h.sent))
+ }
+ if h.sent[0].Email != "[email protected]" {
+ t.Fatalf("email = %q, want it normalized", h.sent[0].Email)
+ }
+}
+
+// A typo in an MDM variable must not fail a fleet install.
+func TestMaybeRunOnboardingIgnoresInvalidEnvironmentAnswers(t *testing.T) {
+ h := newOnboardingHarness(t)
+ onboardingIsTTY = func() bool { return false }
+ t.Setenv(onboardingEnvEmail, "not-an-email")
+ t.Setenv(onboardingEnvUsage, "work")
+
+ if err := maybeRunOnboarding(h.cmd); err != nil {
+ t.Fatalf("maybeRunOnboarding returned error: %v", err)
+ }
+ if len(h.sent) != 0 || h.asked {
+ t.Fatalf("acted on an invalid environment answer")
+ }
+ if !strings.Contains(h.stderr.String(), onboardingEnvEmail) {
+ t.Fatalf("stderr = %q, want it to name the ignored variable", h.stderr.String())
+ }
+}
+
+func TestMaybeRunOnboardingEnvironmentAnswersRespectOptOut(t *testing.T) {
+ h := newOnboardingHarness(t)
+ t.Setenv(onboardingEnvEnabled, "0")
+ t.Setenv(onboardingEnvEmail, "[email protected]")
+ t.Setenv(onboardingEnvUsage, "work")
+
+ if err := maybeRunOnboarding(h.cmd); err != nil {
+ t.Fatalf("maybeRunOnboarding returned error: %v", err)
+ }
+ if len(h.sent) != 0 {
+ t.Fatalf("submitted despite BEACON_ONBOARDING=0")
+ }
+}
+
+// The opt-out is an environment variable only. Shipping a CLI flag would make
+// declining a single keystroke, which is not what this prompt is for.
+func TestInstallHasNoOnboardingOptOutFlag(t *testing.T) {
+ if flag := endpointInstallCmd.Flags().Lookup("no-onboarding"); flag != nil {
+ t.Fatalf("endpoint install still registers --no-onboarding")
+ }
+}
+
+func TestEndpointOnboardingShowsRecord(t *testing.T) {
+ h := newOnboardingHarness(t)
+ h.loaded = onboarding.Profile{
+ InstallID: "abc123",
+ Onboarding: onboarding.Onboarding{
+ CompletedAt: "2026-08-07T00:00:00Z",
+ Outcome: onboarding.OutcomeSubmitted,
+ Email: "[email protected]",
+ Usage: onboarding.UsageWork,
+ },
+ }
+
+ if err := runEndpointOnboarding(h.cmd, nil); err != nil {
+ t.Fatalf("runEndpointOnboarding returned error: %v", err)
+ }
+ out := h.stdout.String()
+ for _, want := range []string{"completed", "[email protected]", "abc123"} {
+ if !strings.Contains(out, want) {
+ t.Fatalf("output is missing %q:\n%s", want, out)
+ }
+ }
+}
+
+func TestEndpointOnboardingResetRemovesProfile(t *testing.T) {
+ h := newOnboardingHarness(t)
+ endpointOpts.onboardingReset = true
+
+ if err := onboarding.Save(onboarding.Profile{Onboarding: onboarding.Onboarding{CompletedAt: "x"}}); err != nil {
+ t.Fatalf("Save: %v", err)
+ }
+ if err := runEndpointOnboarding(h.cmd, nil); err != nil {
+ t.Fatalf("runEndpointOnboarding returned error: %v", err)
+ }
+ if _, err := os.Stat(onboarding.Path()); !os.IsNotExist(err) {
+ t.Fatalf("profile still exists after --reset (err = %v)", err)
+ }
+}
+
+func TestEndpointOnboardingResetOnMissingProfileIsNotAnError(t *testing.T) {
+ h := newOnboardingHarness(t)
+ endpointOpts.onboardingReset = true
+
+ if err := runEndpointOnboarding(h.cmd, nil); err != nil {
+ t.Fatalf("runEndpointOnboarding returned error for a missing profile: %v", err)
+ }
+}
+
+func TestEndpointOnboardingResendWithoutPendingIsQuiet(t *testing.T) {
+ h := newOnboardingHarness(t)
+ endpointOpts.onboardingResend = true
+
+ if err := runEndpointOnboarding(h.cmd, nil); err != nil {
+ t.Fatalf("runEndpointOnboarding returned error: %v", err)
+ }
+ if len(h.sent) != 0 {
+ t.Fatalf("sent %d payloads with nothing pending", len(h.sent))
+ }
+ if !strings.Contains(h.stdout.String(), "No pending signup") {
+ t.Fatalf("output = %q, want it to say there is nothing to resend", h.stdout.String())
+ }
+}
+
+func TestEndpointOnboardingJSONOutput(t *testing.T) {
+ h := newOnboardingHarness(t)
+ endpointOpts.jsonOutput = true
+ h.loaded = onboarding.Profile{
+ InstallID: "abc123",
+ Onboarding: onboarding.Onboarding{CompletedAt: "2026-08-07T00:00:00Z", Outcome: onboarding.OutcomeSubmitted},
+ }
+
+ if err := runEndpointOnboarding(h.cmd, nil); err != nil {
+ t.Fatalf("runEndpointOnboarding returned error: %v", err)
+ }
+ out := h.stdout.String()
+ if !strings.HasPrefix(strings.TrimSpace(out), "{") {
+ t.Fatalf("output is not JSON:\n%s", out)
+ }
+ if !strings.Contains(out, `"prompted":true`) {
+ t.Fatalf("JSON = %s, want prompted true", out)
+ }
+}
+
+func TestOnboardingEnabledByEnv(t *testing.T) {
+ cases := map[string]bool{
+ "": true,
+ "1": true,
+ "true": true,
+ "yes": true,
+ "0": false,
+ "false": false,
+ "FALSE": false,
+ "no": false,
+ "off": false,
+ " 0 ": false,
+ }
+ for value, want := range cases {
+ t.Setenv(onboardingEnvEnabled, value)
+ if got := onboardingEnabledByEnv(); got != want {
+ t.Fatalf("onboardingEnabledByEnv() = %t for %q, want %t", got, value, want)
+ }
+ }
+}
diff --git a/cli/beacon/cmd/root.go b/cli/beacon/cmd/root.go
index a8d083a3..f8b98776 100644
--- a/cli/beacon/cmd/root.go
+++ b/cli/beacon/cmd/root.go
@@ -71,6 +71,20 @@ func shouldUseColor(out io.Writer) bool {
if !ok {
return false
}
+ return isCharDevice(file)
+}
+
+// isCharDevice reports whether a file is attached to a terminal rather than a pipe,
+// a redirect, or a file.
+//
+// Onboarding depends on this to stay out of the way of every non-interactive install
+// path: package postinstall scripts, MDM helpers, CI, and the packaging smoke tests
+// all reach `endpoint install` without a terminal, and a prompt there would hang a
+// fleet deployment.
+func isCharDevice(file *os.File) bool {
+ if file == nil {
+ return false
+ }
stat, err := file.Stat()
if err != nil {
return false
diff --git a/cli/beacon/go.mod b/cli/beacon/go.mod
index 5ffa001f..00f11086 100644
--- a/cli/beacon/go.mod
+++ b/cli/beacon/go.mod
@@ -6,6 +6,7 @@ require (
github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve v0.0.0
github.com/pelletier/go-toml/v2 v2.3.1
github.com/spf13/cobra v1.8.1
+ golang.org/x/term v0.33.0
gopkg.in/yaml.v3 v3.0.1
)
@@ -21,6 +22,7 @@ require (
github.com/spf13/pflag v1.0.5 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 // indirect
+ golang.org/x/sys v0.34.0 // indirect
golang.org/x/text v0.22.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20240826202546-f6391c0de4c7 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240826202546-f6391c0de4c7 // indirect
diff --git a/cli/beacon/go.sum b/cli/beacon/go.sum
index a222ae92..512a7bfe 100644
--- a/cli/beacon/go.sum
+++ b/cli/beacon/go.sum
@@ -22,6 +22,10 @@ go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 h1:kx6Ds3MlpiUHKj7syVnbp57++8WpuKPcR5yjLBjvLEA=
golang.org/x/exp v0.0.0-20240823005443-9b4947da3948/go.mod h1:akd2r19cwCdwSwWeIdzYQGa/EZZyqcOdwWiwj5L5eKQ=
+golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
+golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
+golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=
+golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
google.golang.org/genproto/googleapis/api v0.0.0-20240826202546-f6391c0de4c7 h1:YcyjlL1PRr2Q17/I0dPk2JmYS5CDXfcdb2Z3YRioEbw=
diff --git a/cli/beacon/internal/onboarding/picker.go b/cli/beacon/internal/onboarding/picker.go
new file mode 100644
index 00000000..60491070
--- /dev/null
+++ b/cli/beacon/internal/onboarding/picker.go
@@ -0,0 +1,217 @@
+package onboarding
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "strings"
+
+ "golang.org/x/term"
+)
+
+// errRawUnavailable means the terminal could not be put into raw mode, so the caller
+// should fall back to the typed numbered menu. Plenty of real environments cannot do
+// raw input -- CI pseudo-terminals, some IDE consoles, unusual SSH setups -- and none
+// of them should lose the ability to answer.
+var errRawUnavailable = errors.New("raw terminal mode unavailable")
+
+// ANSI control sequences. Only the handful worth using: anything more elaborate
+// misbehaves across the range of terminals people actually run.
+const (
+ ansiUp = "\x1b[%dA"
+ ansiClearLine = "\r\x1b[K"
+ ansiHideCur = "\x1b[?25l"
+ ansiShowCur = "\x1b[?25h"
+)
+
+const (
+ colorReset = "\x1b[0m"
+ colorDim = "\x1b[2m"
+ colorAccnt = "\x1b[38;5;141m" // the Beacon purple used by the root splash
+ colorGreen = "\x1b[32m"
+)
+
+// keyAction is what a keypress means to the picker.
+type keyAction int
+
+const (
+ keyUp keyAction = iota
+ keyDown
+ keySelect
+ keyPick
+ keyAbort
+)
+
+// keyEvent is one decoded keypress. index is meaningful only for keyPick.
+type keyEvent struct {
+ action keyAction
+ index int
+}
+
+// selectOption renders an arrow-key menu and returns the index the user chose.
+//
+// The terminal is restored on every exit path, including Ctrl-C: raw mode disables
+// the interrupt signal, so leaving without restoring would hand the user back a shell
+// with no echo.
+func selectOption(in *os.File, out io.Writer, options []string, color bool) (int, error) {
+ fd := int(in.Fd())
+ state, err := term.MakeRaw(fd)
+ if err != nil {
+ return 0, errRawUnavailable
+ }
+ defer func() {
+ _ = term.Restore(fd, state)
+ fmt.Fprint(out, ansiShowCur)
+ }()
+
+ fmt.Fprint(out, ansiHideCur)
+
+ selected := 0
+ render(out, options, selected, color, true)
+
+ buf := make([]byte, 32)
+ for {
+ n, err := in.Read(buf)
+ if err != nil || n == 0 {
+ clear(out, len(options)+1)
+ return 0, ErrPromptAborted
+ }
+ moved := false
+ for _, event := range decodeKeys(buf[:n], len(options)) {
+ switch event.action {
+ case keyUp:
+ selected = (selected - 1 + len(options)) % len(options)
+ moved = true
+ case keyDown:
+ selected = (selected + 1) % len(options)
+ moved = true
+ case keySelect:
+ clear(out, len(options)+1)
+ return selected, nil
+ case keyPick:
+ clear(out, len(options)+1)
+ return event.index, nil
+ case keyAbort:
+ clear(out, len(options)+1)
+ return 0, ErrPromptAborted
+ }
+ }
+ if moved {
+ render(out, options, selected, color, false)
+ }
+ }
+}
+
+// decodeKeys turns a single raw read into the keypresses it contains.
+//
+// One Read can carry several keys, because a terminal hands over whatever has arrived
+// rather than one keystroke at a time: fast typing, a paste, and scripted input all
+// produce multi-byte reads. An earlier version matched only an exact one-byte read or
+// a three-byte escape, so an ordinary `1\n` was silently discarded and the picker sat
+// waiting for a key the user had already pressed.
+func decodeKeys(buf []byte, total int) []keyEvent {
+ var events []keyEvent
+ for i := 0; i < len(buf); {
+ if buf[i] == 0x1b {
+ // Arrow keys. Anything else starting with escape is a sequence this picker
+ // does not use; drop the remainder rather than misread its bytes as
+ // separate keypresses.
+ if i+2 < len(buf) && buf[i+1] == '[' {
+ switch buf[i+2] {
+ case 'A':
+ events = append(events, keyEvent{keyUp, 0})
+ case 'B':
+ events = append(events, keyEvent{keyDown, 0})
+ }
+ i += 3
+ continue
+ }
+ break
+ }
+ if event, ok := decodeByte(buf[i], total); ok {
+ events = append(events, event)
+ // Selecting or aborting ends the menu, so nothing after it can matter.
+ if event.action != keyUp && event.action != keyDown {
+ return events
+ }
+ }
+ i++
+ }
+ return events
+}
+
+// decodeByte maps a single non-escape byte onto an action.
+func decodeByte(c byte, total int) (keyEvent, bool) {
+ switch {
+ case c == 'k' || c == 'K':
+ return keyEvent{keyUp, 0}, true
+ case c == 'j' || c == 'J':
+ return keyEvent{keyDown, 0}, true
+ case c == '\r' || c == '\n':
+ return keyEvent{keySelect, 0}, true
+ // A number key picks that entry outright: anyone who already knows the menu
+ // should not have to arrow down to their answer.
+ case c >= '1' && c <= '9' && int(c-'0') <= total:
+ return keyEvent{keyPick, int(c - '1')}, true
+ case c == 0x03 || c == 0x04: // Ctrl-C, Ctrl-D
+ return keyEvent{keyAbort, 0}, true
+ default:
+ return keyEvent{}, false
+ }
+}
+
+// render draws the option list plus its key hint, overwriting the previous draw.
+func render(out io.Writer, options []string, selected int, color bool, first bool) {
+ if !first {
+ fmt.Fprintf(out, ansiUp, len(options)+1)
+ }
+ accent, dimmed, clear := "", "", ""
+ if color {
+ accent, dimmed, clear = colorAccnt, colorDim, colorReset
+ }
+ for i, option := range options {
+ fmt.Fprint(out, ansiClearLine)
+ if i == selected {
+ fmt.Fprintf(out, " %s❯ %s%s\r\n", accent, option, clear)
+ } else {
+ fmt.Fprintf(out, " %s\r\n", option)
+ }
+ }
+ fmt.Fprint(out, ansiClearLine)
+ fmt.Fprintf(out, " %s↑/↓ move · ↵ select · ^C cancel%s\r\n", dimmed, clear)
+}
+
+// clear erases the last n rendered lines and parks the cursor at their start.
+func clear(out io.Writer, n int) {
+ fmt.Fprintf(out, ansiUp, n)
+ for i := 0; i < n; i++ {
+ fmt.Fprint(out, ansiClearLine)
+ if i < n-1 {
+ fmt.Fprint(out, "\r\n")
+ }
+ }
+ fmt.Fprintf(out, ansiUp, n-1)
+ fmt.Fprint(out, "\r")
+}
+
+// terminalFile reports whether r is a real terminal that raw mode can drive.
+func terminalFile(r io.Reader) (*os.File, bool) {
+ file, ok := r.(*os.File)
+ if !ok {
+ return nil, false
+ }
+ return file, term.IsTerminal(int(file.Fd()))
+}
+
+// supportsColor mirrors the CLI's existing convention for the root splash.
+func supportsColor(out io.Writer) bool {
+ if os.Getenv("NO_COLOR") != "" || strings.EqualFold(os.Getenv("TERM"), "dumb") {
+ return false
+ }
+ file, ok := out.(*os.File)
+ if !ok {
+ return false
+ }
+ return term.IsTerminal(int(file.Fd()))
+}
diff --git a/cli/beacon/internal/onboarding/picker_test.go b/cli/beacon/internal/onboarding/picker_test.go
new file mode 100644
index 00000000..d77527b9
--- /dev/null
+++ b/cli/beacon/internal/onboarding/picker_test.go
@@ -0,0 +1,187 @@
+package onboarding
+
+import (
+ "bytes"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestDecodeKeysSingleKeypress(t *testing.T) {
+ const total = 3
+ cases := []struct {
+ name string
+ bytes []byte
+ want []keyEvent
+ }{
+ {"up arrow", []byte{0x1b, '[', 'A'}, []keyEvent{{keyUp, 0}}},
+ {"down arrow", []byte{0x1b, '[', 'B'}, []keyEvent{{keyDown, 0}}},
+ {"vim k", []byte{'k'}, []keyEvent{{keyUp, 0}}},
+ {"vim j", []byte{'j'}, []keyEvent{{keyDown, 0}}},
+ {"enter", []byte{'\r'}, []keyEvent{{keySelect, 0}}},
+ {"newline", []byte{'\n'}, []keyEvent{{keySelect, 0}}},
+ {"digit picks directly", []byte{'2'}, []keyEvent{{keyPick, 1}}},
+ {"last digit", []byte{'3'}, []keyEvent{{keyPick, 2}}},
+ {"digit past the end is ignored", []byte{'4'}, nil},
+ {"zero is not an option", []byte{'0'}, nil},
+ {"ctrl-c aborts", []byte{0x03}, []keyEvent{{keyAbort, 0}}},
+ {"ctrl-d aborts", []byte{0x04}, []keyEvent{{keyAbort, 0}}},
+ {"empty read yields nothing", []byte{}, nil},
+ {"unknown letter ignored", []byte{'z'}, nil},
+ {"right arrow ignored", []byte{0x1b, '[', 'C'}, nil},
+ {"bare escape ignored", []byte{0x1b}, nil},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ assertEvents(t, decodeKeys(tc.bytes, total), tc.want)
+ })
+ }
+}
+
+// A terminal hands over whatever has arrived, not one keystroke at a time. Fast
+// typing, a paste, and scripted input all produce multi-byte reads -- and an earlier
+// version dropped them silently, leaving the picker waiting on a key already pressed.
+func TestDecodeKeysMultipleKeysInOneRead(t *testing.T) {
+ const total = 3
+ cases := []struct {
+ name string
+ bytes []byte
+ want []keyEvent
+ }{
+ {"digit then newline", []byte("1\n"), []keyEvent{{keyPick, 0}}},
+ {"digit then carriage return", []byte("2\r"), []keyEvent{{keyPick, 1}}},
+ {"two downs then enter", append(append([]byte{0x1b, '[', 'B'}, 0x1b, '[', 'B'), '\r'),
+ []keyEvent{{keyDown, 0}, {keyDown, 0}, {keySelect, 0}}},
+ {"vim keys then enter", []byte("jjk\r"),
+ []keyEvent{{keyDown, 0}, {keyDown, 0}, {keyUp, 0}, {keySelect, 0}}},
+ {"noise before a digit", []byte("xy2"), []keyEvent{{keyPick, 1}}},
+ {"nothing survives past a select", []byte("\r3jjj"), []keyEvent{{keySelect, 0}}},
+ {"nothing survives past an abort", []byte{0x03, '2', '\r'}, []keyEvent{{keyAbort, 0}}},
+ {"a whole pasted line still selects", []byte("1\[email protected]\n"), []keyEvent{{keyPick, 0}}},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ assertEvents(t, decodeKeys(tc.bytes, total), tc.want)
+ })
+ }
+}
+
+func assertEvents(t *testing.T, got, want []keyEvent) {
+ t.Helper()
+ if len(got) != len(want) {
+ t.Fatalf("decodeKeys returned %v, want %v", got, want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("decodeKeys returned %v, want %v", got, want)
+ }
+ }
+}
+
+func TestRenderMarksTheSelectedOption(t *testing.T) {
+ var out bytes.Buffer
+ render(&out, []string{"Alpha", "Beta", "Gamma"}, 1, false, true)
+ got := out.String()
+
+ if !strings.Contains(got, "❯ Beta") {
+ t.Fatalf("selected option is not marked:\n%s", got)
+ }
+ if strings.Contains(got, "❯ Alpha") || strings.Contains(got, "❯ Gamma") {
+ t.Fatalf("more than one option is marked:\n%s", got)
+ }
+ if !strings.Contains(got, "↑/↓ move") || !strings.Contains(got, "^C cancel") {
+ t.Fatalf("key hint is missing:\n%s", got)
+ }
+}
+
+// The first draw must not move the cursor up, or it will eat whatever the caller
+// printed above the menu.
+func TestRenderFirstDrawDoesNotMoveTheCursor(t *testing.T) {
+ var first, redraw bytes.Buffer
+ render(&first, []string{"A", "B"}, 0, false, true)
+ render(&redraw, []string{"A", "B"}, 0, false, false)
+
+ if strings.Contains(first.String(), "\x1b[3A") {
+ t.Fatalf("first draw moved the cursor up:\n%q", first.String())
+ }
+ if !strings.HasPrefix(redraw.String(), "\x1b[3A") {
+ t.Fatalf("redraw did not rewind over its own %d lines:\n%q", 3, redraw.String())
+ }
+}
+
+func TestRenderHonorsColorOff(t *testing.T) {
+ var out bytes.Buffer
+ render(&out, []string{"Alpha", "Beta"}, 0, false, true)
+ if strings.Contains(out.String(), colorAccnt) || strings.Contains(out.String(), colorDim) {
+ t.Fatalf("colour escapes leaked with colour disabled:\n%q", out.String())
+ }
+
+ out.Reset()
+ render(&out, []string{"Alpha", "Beta"}, 0, true, true)
+ if !strings.Contains(out.String(), colorAccnt) {
+ t.Fatalf("colour was requested but not emitted:\n%q", out.String())
+ }
+}
+
+// Raw mode is impossible on a plain file, and that must degrade to the typed menu
+// rather than failing the install.
+func TestSelectOptionFallsBackWithoutATerminal(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "not-a-tty")
+ file, err := os.Create(path)
+ if err != nil {
+ t.Fatalf("Create: %v", err)
+ }
+ defer file.Close()
+
+ if _, err := selectOption(file, io.Discard, []string{"A", "B"}, false); !errors.Is(err, errRawUnavailable) {
+ t.Fatalf("selectOption error = %v, want errRawUnavailable", err)
+ }
+}
+
+func TestTerminalFileRejectsNonFiles(t *testing.T) {
+ if _, ok := terminalFile(strings.NewReader("x")); ok {
+ t.Fatalf("a strings.Reader was reported as a terminal")
+ }
+ path := filepath.Join(t.TempDir(), "plain")
+ if err := os.WriteFile(path, []byte("x"), 0o600); err != nil {
+ t.Fatalf("WriteFile: %v", err)
+ }
+ file, _ := os.Open(path)
+ defer file.Close()
+ if _, ok := terminalFile(file); ok {
+ t.Fatalf("a regular file was reported as a terminal")
+ }
+}
+
+func TestSupportsColorRespectsNoColor(t *testing.T) {
+ t.Setenv("NO_COLOR", "1")
+ if supportsColor(os.Stdout) {
+ t.Fatalf("NO_COLOR was set but colour was still enabled")
+ }
+ t.Setenv("NO_COLOR", "")
+ t.Setenv("TERM", "dumb")
+ if supportsColor(os.Stdout) {
+ t.Fatalf("TERM=dumb but colour was still enabled")
+ }
+}
+
+// clear must rewind exactly as far as it wiped, so the confirmation line lands where
+// the menu was instead of below it.
+func TestClearRewindsWhatItWiped(t *testing.T) {
+ var out bytes.Buffer
+ clear(&out, 4)
+ got := out.String()
+
+ if !strings.HasPrefix(got, "\x1b[4A") {
+ t.Fatalf("clear did not rewind 4 lines first:\n%q", got)
+ }
+ if strings.Count(got, "\x1b[K") != 4 {
+ t.Fatalf("clear wiped %d lines, want 4:\n%q", strings.Count(got, "\x1b[K"), got)
+ }
+ if !strings.HasSuffix(got, "\x1b[3A\r") {
+ t.Fatalf("clear did not park the cursor at the start of the block:\n%q", got)
+ }
+}
diff --git a/cli/beacon/internal/onboarding/profile.go b/cli/beacon/internal/onboarding/profile.go
new file mode 100644
index 00000000..29968aca
--- /dev/null
+++ b/cli/beacon/internal/onboarding/profile.go
@@ -0,0 +1,151 @@
+// Package onboarding implements Beacon's one-time, install-time account signal:
+// a prompt for the operator's email and how they are using Beacon, submitted once
+// to an Asymptote-run endpoint.
+//
+// Everything here is best-effort. Onboarding never fails an install, never runs
+// outside an interactive terminal, and never runs twice on the same machine.
+package onboarding
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "os"
+ "path/filepath"
+)
+
+// ProfilePath is the profile location relative to the user's home directory.
+//
+// This is a deliberate sibling of ~/.beacon/endpoint/ rather than a file inside it.
+// lifecycle.Uninstall removes the endpoint config and every manifest-listed file, so a
+// profile stored under ~/.beacon/endpoint/ would be destroyed by an uninstall and the
+// user would be prompted again on their next install. The endpoint config is also
+// mode-specific (--user vs --system) and rewritten wholesale by every install and
+// repair, which would lose the record just as reliably.
+const ProfilePath = ".beacon/profile.json"
+
+// SchemaVersion is the profile format version. Bump it only for a breaking change;
+// readers tolerate unknown fields, so additive changes do not need a bump.
+const SchemaVersion = 1
+
+// Outcome records how the one-time submission ended.
+const (
+ // OutcomeSubmitted means the endpoint accepted the signup.
+ OutcomeSubmitted = "submitted"
+ // OutcomePending means the submission failed in a way worth retrying (network
+ // error, timeout, 5xx). The payload is kept so a later command can resend it.
+ OutcomePending = "pending"
+ // OutcomeRejected means the endpoint refused the submission (4xx, rate limit).
+ // Terminal: there is nothing useful to retry.
+ OutcomeRejected = "rejected"
+ // OutcomeSkipped means the user opted out through a documented escape hatch.
+ OutcomeSkipped = "skipped"
+)
+
+// Profile is the persisted per-machine Beacon profile.
+type Profile struct {
+ SchemaVersion int `json:"schema_version"`
+ InstallID string `json:"install_id"`
+ Onboarding Onboarding `json:"onboarding"`
+ Pending *Submission `json:"pending_submission,omitempty"`
+}
+
+// Onboarding records the outcome of the one-time prompt.
+type Onboarding struct {
+ CompletedAt string `json:"completed_at,omitempty"`
+ Outcome string `json:"outcome,omitempty"`
+ Email string `json:"email,omitempty"`
+ Usage string `json:"usage,omitempty"`
+ BeaconVersion string `json:"beacon_version,omitempty"`
+}
+
+// Prompted reports whether this machine has already been through onboarding.
+// It is the single gate that makes the prompt fire once and only once.
+func (p Profile) Prompted() bool {
+ return p.Onboarding.CompletedAt != ""
+}
+
+// Path returns the absolute profile path, honoring HOME so tests can redirect it.
+func Path() string {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return filepath.Join(".", ProfilePath)
+ }
+ return filepath.Join(home, ProfilePath)
+}
+
+// Load reads the profile.
+//
+// A missing file and a corrupt file are both reported as an empty profile with no
+// error. Onboarding is a sales signal, not a correctness requirement: refusing to
+// install because a JSON file got truncated would trade a real user's install for a
+// lead we were never going to get anyway. An unreadable profile simply reads as
+// "not yet prompted".
+func Load() Profile {
+ data, err := os.ReadFile(Path())
+ if err != nil {
+ return Profile{}
+ }
+ var p Profile
+ if err := json.Unmarshal(data, &p); err != nil {
+ return Profile{}
+ }
+ return p
+}
+
+// Save writes the profile, minting an install ID and stamping the schema version if
+// they are not set yet. The file is 0600 because it holds the operator's email.
+func Save(p Profile) error {
+ if p.SchemaVersion == 0 {
+ p.SchemaVersion = SchemaVersion
+ }
+ if p.InstallID == "" {
+ id, err := NewInstallID()
+ if err != nil {
+ return err
+ }
+ p.InstallID = id
+ }
+ path := Path()
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return err
+ }
+ data, err := json.MarshalIndent(p, "", " ")
+ if err != nil {
+ return err
+ }
+ data = append(data, '\n')
+ if err := os.WriteFile(path, data, 0o600); err != nil {
+ return err
+ }
+ // WriteFile only applies the mode when it creates the file, so an existing
+ // profile written before this code shipped would keep its old permissions.
+ return os.Chmod(path, 0o600)
+}
+
+// NewInstallID returns a random 128-bit hex identifier.
+//
+// This is the dedupe key for the signup endpoint (so reinstalling updates one row
+// instead of creating another) and the handle a user quotes to request deletion. It
+// is unrelated to any hardware or account identifier and carries no user data.
+func NewInstallID() (string, error) {
+ buf := make([]byte, 16)
+ if _, err := rand.Read(buf); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(buf), nil
+}
+
+// EnsureInstallID returns the profile's install ID, minting and persisting one if the
+// profile does not have it yet.
+func EnsureInstallID(p *Profile) (string, error) {
+ if p.InstallID != "" {
+ return p.InstallID, nil
+ }
+ id, err := NewInstallID()
+ if err != nil {
+ return "", err
+ }
+ p.InstallID = id
+ return id, nil
+}
diff --git a/cli/beacon/internal/onboarding/profile_test.go b/cli/beacon/internal/onboarding/profile_test.go
new file mode 100644
index 00000000..5f69d5a9
--- /dev/null
+++ b/cli/beacon/internal/onboarding/profile_test.go
@@ -0,0 +1,202 @@
+package onboarding
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestPathHonorsHome(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+
+ want := filepath.Join(home, ProfilePath)
+ if got := Path(); got != want {
+ t.Fatalf("Path() = %q, want %q", got, want)
+ }
+}
+
+func TestLoadMissingProfileReportsNotPrompted(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+
+ p := Load()
+ if p.Prompted() {
+ t.Fatalf("Prompted() = true for a missing profile, want false")
+ }
+ if p.InstallID != "" {
+ t.Fatalf("InstallID = %q for a missing profile, want empty", p.InstallID)
+ }
+}
+
+// A truncated or hand-edited profile must not fail an install. Onboarding is a sales
+// signal; refusing to install over it would trade a real user for a lead.
+func TestLoadCorruptProfileReportsNotPrompted(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ path := filepath.Join(home, ProfilePath)
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatalf("MkdirAll: %v", err)
+ }
+ if err := os.WriteFile(path, []byte(`{"schema_version": 1, "onboardi`), 0o600); err != nil {
+ t.Fatalf("WriteFile: %v", err)
+ }
+
+ if Load().Prompted() {
+ t.Fatalf("Prompted() = true for a corrupt profile, want false")
+ }
+}
+
+func TestSaveRoundTrip(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+
+ in := Profile{
+ Onboarding: Onboarding{
+ CompletedAt: "2026-08-07T18:03:11Z",
+ Outcome: OutcomeSubmitted,
+ Email: "[email protected]",
+ Usage: UsageWork,
+ BeaconVersion: "v0.0.31",
+ },
+ }
+ if err := Save(in); err != nil {
+ t.Fatalf("Save: %v", err)
+ }
+
+ got := Load()
+ if !got.Prompted() {
+ t.Fatalf("Prompted() = false after Save, want true")
+ }
+ if got.Onboarding.Email != in.Onboarding.Email {
+ t.Fatalf("Email = %q, want %q", got.Onboarding.Email, in.Onboarding.Email)
+ }
+ if got.Onboarding.Outcome != OutcomeSubmitted {
+ t.Fatalf("Outcome = %q, want %q", got.Onboarding.Outcome, OutcomeSubmitted)
+ }
+ if got.SchemaVersion != SchemaVersion {
+ t.Fatalf("SchemaVersion = %d, want %d", got.SchemaVersion, SchemaVersion)
+ }
+ if len(got.InstallID) != 32 {
+ t.Fatalf("InstallID = %q, want 32 hex characters", got.InstallID)
+ }
+}
+
+// The profile holds the operator's email address, so it must not be world-readable.
+func TestSaveUsesOwnerOnlyPermissions(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+
+ if err := Save(Profile{}); err != nil {
+ t.Fatalf("Save: %v", err)
+ }
+
+ info, err := os.Stat(filepath.Join(home, ProfilePath))
+ if err != nil {
+ t.Fatalf("Stat: %v", err)
+ }
+ if perm := info.Mode().Perm(); perm != 0o600 {
+ t.Fatalf("profile permissions = %o, want 600", perm)
+ }
+}
+
+// A profile written by an older build with looser permissions gets tightened rather
+// than silently kept, because os.WriteFile only applies its mode on creation.
+func TestSaveTightensExistingPermissions(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ path := filepath.Join(home, ProfilePath)
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatalf("MkdirAll: %v", err)
+ }
+ if err := os.WriteFile(path, []byte("{}"), 0o644); err != nil {
+ t.Fatalf("WriteFile: %v", err)
+ }
+
+ if err := Save(Profile{}); err != nil {
+ t.Fatalf("Save: %v", err)
+ }
+
+ info, err := os.Stat(path)
+ if err != nil {
+ t.Fatalf("Stat: %v", err)
+ }
+ if perm := info.Mode().Perm(); perm != 0o600 {
+ t.Fatalf("profile permissions = %o, want 600", perm)
+ }
+}
+
+func TestSavePreservesExistingInstallID(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+
+ if err := Save(Profile{InstallID: "deadbeefdeadbeefdeadbeefdeadbeef"}); err != nil {
+ t.Fatalf("Save: %v", err)
+ }
+ first := Load().InstallID
+
+ if err := Save(Profile{InstallID: first, Onboarding: Onboarding{CompletedAt: "later"}}); err != nil {
+ t.Fatalf("Save: %v", err)
+ }
+ if got := Load().InstallID; got != first {
+ t.Fatalf("InstallID = %q after resave, want stable %q", got, first)
+ }
+}
+
+func TestSaveWritesValidJSON(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+
+ if err := Save(Profile{Onboarding: Onboarding{Outcome: OutcomeSkipped}}); err != nil {
+ t.Fatalf("Save: %v", err)
+ }
+
+ data, err := os.ReadFile(filepath.Join(home, ProfilePath))
+ if err != nil {
+ t.Fatalf("ReadFile: %v", err)
+ }
+ var raw map[string]any
+ if err := json.Unmarshal(data, &raw); err != nil {
+ t.Fatalf("profile is not valid JSON: %v", err)
+ }
+ if _, ok := raw["pending_submission"]; ok {
+ t.Fatalf("pending_submission should be omitted when nil, got %v", raw["pending_submission"])
+ }
+}
+
+func TestNewInstallIDIsUnique(t *testing.T) {
+ seen := map[string]bool{}
+ for i := 0; i < 64; i++ {
+ id, err := NewInstallID()
+ if err != nil {
+ t.Fatalf("NewInstallID: %v", err)
+ }
+ if len(id) != 32 {
+ t.Fatalf("NewInstallID() = %q, want 32 hex characters", id)
+ }
+ if seen[id] {
+ t.Fatalf("NewInstallID() returned a duplicate: %q", id)
+ }
+ seen[id] = true
+ }
+}
+
+func TestEnsureInstallIDKeepsExisting(t *testing.T) {
+ p := Profile{InstallID: "cafebabecafebabecafebabecafebabe"}
+ got, err := EnsureInstallID(&p)
+ if err != nil {
+ t.Fatalf("EnsureInstallID: %v", err)
+ }
+ if got != "cafebabecafebabecafebabecafebabe" {
+ t.Fatalf("EnsureInstallID() = %q, want the existing ID", got)
+ }
+}
+
+func TestEnsureInstallIDMintsWhenMissing(t *testing.T) {
+ p := Profile{}
+ got, err := EnsureInstallID(&p)
+ if err != nil {
+ t.Fatalf("EnsureInstallID: %v", err)
+ }
+ if got == "" || p.InstallID != got {
+ t.Fatalf("EnsureInstallID() = %q, profile = %q; want a minted ID stored on the profile", got, p.InstallID)
+ }
+}
diff --git a/cli/beacon/internal/onboarding/prompt.go b/cli/beacon/internal/onboarding/prompt.go
new file mode 100644
index 00000000..99c80bce
--- /dev/null
+++ b/cli/beacon/internal/onboarding/prompt.go
@@ -0,0 +1,173 @@
+package onboarding
+
+import (
+ "bufio"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+)
+
+// maxAttempts bounds the email question so someone who cannot produce an address ends
+// with a clear message instead of looping.
+const maxAttempts = 5
+
+// ErrPromptAborted means the user ended input (Ctrl-C or Ctrl-D) without answering.
+// Cancelling aborts this install and nothing more: the user can re-run and answer.
+// The message deliberately does not mention BEACON_ONBOARDING -- that variable is for
+// unattended CI and MDM installs, documented in the CLI reference, not an escape hatch
+// to hand someone the moment they try to decline.
+var ErrPromptAborted = errors.New("onboarding cancelled")
+
+// ErrTooManyAttempts means the question was answered incorrectly too many times.
+var ErrTooManyAttempts = errors.New("too many invalid answers")
+
+// Answers holds what the user chose.
+type Answers struct {
+ Email string
+ Usage string
+}
+
+// Prompt runs the one-time onboarding questions.
+//
+// On a real terminal the usage question is an arrow-key picker. Anywhere else -- a
+// buffer in tests, a terminal that will not enter raw mode -- it degrades to a typed
+// numbered menu, so no environment loses the ability to answer.
+func Prompt(in io.Reader, out io.Writer) (Answers, error) {
+ color := supportsColor(out)
+ reader := bufio.NewReader(in)
+
+ fmt.Fprintln(out)
+ fmt.Fprintf(out, " %sBeacon is free and open source.%s Sharing your email helps us\n", bold(color), reset(color))
+ fmt.Fprintln(out, " prioritize which agent runtimes to support next.")
+ fmt.Fprintln(out)
+
+ usage, err := askUsage(reader, in, out, color)
+ if err != nil {
+ return Answers{}, err
+ }
+
+ email, err := askEmail(reader, out, color)
+ if err != nil {
+ return Answers{}, err
+ }
+
+ // A work answer on a consumer mailbox is worth a note but not a rejection:
+ // contractors and people at companies without their own domain are all real.
+ if usage == UsageWork && ClassifyDomain(EmailDomain(email)) == DomainFree {
+ fmt.Fprintf(out, " %s%s is a personal mailbox — using it anyway.%s\n", dim(color), EmailDomain(email), reset(color))
+ }
+
+ fmt.Fprintln(out)
+ return Answers{Email: email, Usage: usage}, nil
+}
+
+func askUsage(reader *bufio.Reader, in io.Reader, out io.Writer, color bool) (string, error) {
+ fmt.Fprintf(out, " %sHow are you using Beacon?%s\n\n", bold(color), reset(color))
+
+ if tty, ok := terminalFile(in); ok {
+ index, err := selectOption(tty, out, UsageLabels, color)
+ if err == nil {
+ printChoice(out, UsageLabels[index], color)
+ return ValidUsages[index], nil
+ }
+ if !errors.Is(err, errRawUnavailable) {
+ return "", ErrPromptAborted
+ }
+ // Raw mode was refused; fall through to the typed menu below.
+ }
+
+ for i, label := range UsageLabels {
+ fmt.Fprintf(out, " %d) %s\n", i+1, label)
+ }
+ fmt.Fprintln(out)
+ for attempt := 0; attempt < maxAttempts; attempt++ {
+ line, err := readLine(reader, out, fmt.Sprintf(" Choice [1-%d] ", len(UsageLabels)))
+ if err != nil {
+ return "", err
+ }
+ if usage, ok := NormalizeUsage(line); ok {
+ // Echo the same confirmation the picker shows, so both paths read alike.
+ for i, candidate := range ValidUsages {
+ if candidate == usage {
+ printChoice(out, UsageLabels[i], color)
+ break
+ }
+ }
+ return usage, nil
+ }
+ fmt.Fprintf(out, " %s✗ enter a number from 1 to %d%s\n", warn(color), len(UsageLabels), reset(color))
+ }
+ return "", ErrTooManyAttempts
+}
+
+func askEmail(reader *bufio.Reader, out io.Writer, color bool) (string, error) {
+ for attempt := 0; attempt < maxAttempts; attempt++ {
+ line, err := readLine(reader, out, fmt.Sprintf(" %sEmail%s › ", bold(color), reset(color)))
+ if err != nil {
+ return "", err
+ }
+ email, invalid := NormalizeEmail(line)
+ if invalid == nil {
+ return email, nil
+ }
+ fmt.Fprintf(out, " %s✗ %s%s\n", warn(color), invalid, reset(color))
+ }
+ return "", ErrTooManyAttempts
+}
+
+func printChoice(out io.Writer, label string, color bool) {
+ fmt.Fprintf(out, " %s✓%s %s\n\n", ok(color), reset(color), label)
+}
+
+// readLine writes a prompt and reads one line. EOF with no content means Ctrl-D or
+// exhausted input, which is an abort rather than a bad answer.
+func readLine(reader *bufio.Reader, out io.Writer, prompt string) (string, error) {
+ fmt.Fprint(out, prompt)
+ line, err := reader.ReadString('\n')
+ if err != nil {
+ if errors.Is(err, io.EOF) && strings.TrimSpace(line) != "" {
+ return strings.TrimSpace(line), nil
+ }
+ fmt.Fprintln(out)
+ return "", ErrPromptAborted
+ }
+ return strings.TrimSpace(line), nil
+}
+
+// Colour helpers return empty strings when colour is off, so every format string can
+// use them unconditionally.
+func bold(c bool) string {
+ if c {
+ return "\x1b[1m"
+ }
+ return ""
+}
+
+func dim(c bool) string {
+ if c {
+ return colorDim
+ }
+ return ""
+}
+
+func warn(c bool) string {
+ if c {
+ return "\x1b[33m"
+ }
+ return ""
+}
+
+func ok(c bool) string {
+ if c {
+ return colorGreen
+ }
+ return ""
+}
+
+func reset(c bool) string {
+ if c {
+ return colorReset
+ }
+ return ""
+}
diff --git a/cli/beacon/internal/onboarding/prompt_test.go b/cli/beacon/internal/onboarding/prompt_test.go
new file mode 100644
index 00000000..b341a4a3
--- /dev/null
+++ b/cli/beacon/internal/onboarding/prompt_test.go
@@ -0,0 +1,168 @@
+package onboarding
+
+import (
+ "bytes"
+ "errors"
+ "strings"
+ "testing"
+)
+
+func runPrompt(t *testing.T, input string) (Answers, string, error) {
+ t.Helper()
+ var out bytes.Buffer
+ answers, err := Prompt(strings.NewReader(input), &out)
+ return answers, out.String(), err
+}
+
+func TestPromptHappyPath(t *testing.T) {
+ answers, out, err := runPrompt(t, "1\[email protected]\n")
+ if err != nil {
+ t.Fatalf("Prompt returned error: %v", err)
+ }
+ if answers.Usage != UsageWork {
+ t.Fatalf("Usage = %q, want %q", answers.Usage, UsageWork)
+ }
+ if answers.Email != "[email protected]" {
+ t.Fatalf("Email = %q, want %q", answers.Email, "[email protected]")
+ }
+ if !strings.Contains(out, "Email") {
+ t.Fatalf("prompt output did not ask for an email:\n%s", out)
+ }
+}
+
+// One line of context, not a wall of text. Users skim, and a prompt that lectures
+// gets skipped harder than one that asks.
+func TestPromptExplainsWhyItIsAsking(t *testing.T) {
+ _, out, err := runPrompt(t, "2\[email protected]\n")
+ if err != nil {
+ t.Fatalf("Prompt returned error: %v", err)
+ }
+ for _, want := range []string{"free and open source", "How are you using Beacon?"} {
+ if !strings.Contains(out, want) {
+ t.Fatalf("prompt output is missing %q:\n%s", want, out)
+ }
+ }
+ if lines := strings.Count(strings.TrimSpace(out), "\n"); lines > 14 {
+ t.Fatalf("prompt renders %d lines; keep it short:\n%s", lines+1, out)
+ }
+}
+
+func TestPromptNormalizesAnswers(t *testing.T) {
+ answers, _, err := runPrompt(t, " work \n <[email protected]> \n")
+ if err != nil {
+ t.Fatalf("Prompt returned error: %v", err)
+ }
+ if answers.Usage != UsageWork {
+ t.Fatalf("Usage = %q, want %q", answers.Usage, UsageWork)
+ }
+ if answers.Email != "[email protected]" {
+ t.Fatalf("Email = %q, want it normalized", answers.Email)
+ }
+}
+
+func TestPromptRetriesInvalidEmailThenAccepts(t *testing.T) {
+ answers, out, err := runPrompt(t, "1\nnot-an-email\nstill@bad\[email protected]\n")
+ if err != nil {
+ t.Fatalf("Prompt returned error: %v", err)
+ }
+ if answers.Email != "[email protected]" {
+ t.Fatalf("Email = %q, want the third answer accepted", answers.Email)
+ }
+ if !strings.Contains(out, ErrEmailNoAt.Error()) {
+ t.Fatalf("output did not explain the first failure:\n%s", out)
+ }
+ if !strings.Contains(out, ErrEmailNoDot.Error()) {
+ t.Fatalf("output did not explain the second failure:\n%s", out)
+ }
+}
+
+func TestPromptRetriesInvalidUsageThenAccepts(t *testing.T) {
+ answers, out, err := runPrompt(t, "9\nmaybe\n3\[email protected]\n")
+ if err != nil {
+ t.Fatalf("Prompt returned error: %v", err)
+ }
+ if answers.Usage != UsageEvaluating {
+ t.Fatalf("Usage = %q, want %q", answers.Usage, UsageEvaluating)
+ }
+ if !strings.Contains(out, "enter a number from 1 to 3") {
+ t.Fatalf("output did not reprompt for the menu:\n%s", out)
+ }
+}
+
+func TestPromptGivesUpAfterTooManyBadEmails(t *testing.T) {
+ input := "1\n" + strings.Repeat("nope\n", maxAttempts+2)
+ _, out, err := runPrompt(t, input)
+ if !errors.Is(err, ErrTooManyAttempts) {
+ t.Fatalf("error = %v, want ErrTooManyAttempts", err)
+ }
+ // Nothing in the message advertises a way to skip the question.
+ if strings.Contains(err.Error(), "BEACON_ONBOARDING") {
+ t.Fatalf("error %q leaks the unattended-install escape hatch", err)
+ }
+ if strings.Count(out, "Email") != maxAttempts {
+ t.Fatalf("asked for an email %d times, want %d", strings.Count(out, "Email"), maxAttempts)
+ }
+}
+
+func TestPromptGivesUpAfterTooManyBadUsageAnswers(t *testing.T) {
+ _, _, err := runPrompt(t, strings.Repeat("nope\n", maxAttempts+2))
+ if !errors.Is(err, ErrTooManyAttempts) {
+ t.Fatalf("error = %v, want ErrTooManyAttempts", err)
+ }
+}
+
+// Ctrl-D at either question aborts the install and says only that. Cancelling is not
+// a lock: the user can re-run and answer.
+func TestPromptAbortsOnEOF(t *testing.T) {
+ cases := map[string]string{
+ "eof at usage": "",
+ "eof at email": "1\n",
+ }
+ for name, input := range cases {
+ t.Run(name, func(t *testing.T) {
+ _, _, err := runPrompt(t, input)
+ if !errors.Is(err, ErrPromptAborted) {
+ t.Fatalf("error = %v, want ErrPromptAborted", err)
+ }
+ if got := err.Error(); got != "onboarding cancelled" {
+ t.Fatalf("error = %q, want a bare cancellation message", got)
+ }
+ })
+ }
+}
+
+// A final line without a trailing newline is still an answer, not an abort.
+func TestPromptAcceptsUnterminatedFinalLine(t *testing.T) {
+ answers, _, err := runPrompt(t, "1\[email protected]")
+ if err != nil {
+ t.Fatalf("Prompt returned error: %v", err)
+ }
+ if answers.Email != "[email protected]" {
+ t.Fatalf("Email = %q, want the unterminated line accepted", answers.Email)
+ }
+}
+
+// A consumer mailbox with a work answer is accepted with a note. Rejecting it would
+// lose real contractors and consultants over a formatting opinion.
+func TestPromptAcceptsFreeMailboxForWorkUse(t *testing.T) {
+ answers, out, err := runPrompt(t, "1\[email protected]\n")
+ if err != nil {
+ t.Fatalf("Prompt returned error: %v", err)
+ }
+ if answers.Email != "[email protected]" || answers.Usage != UsageWork {
+ t.Fatalf("answers = %+v, want the free mailbox accepted for work use", answers)
+ }
+ if !strings.Contains(out, "personal mailbox") {
+ t.Fatalf("output did not note the personal mailbox:\n%s", out)
+ }
+}
+
+func TestPromptDoesNotNoteFreeMailboxForPersonalUse(t *testing.T) {
+ _, out, err := runPrompt(t, "2\[email protected]\n")
+ if err != nil {
+ t.Fatalf("Prompt returned error: %v", err)
+ }
+ if strings.Contains(out, "personal mailbox") {
+ t.Fatalf("personal use should not trigger the mailbox note:\n%s", out)
+ }
+}
diff --git a/cli/beacon/internal/onboarding/runtimes.go b/cli/beacon/internal/onboarding/runtimes.go
new file mode 100644
index 00000000..6b4ac522
--- /dev/null
+++ b/cli/beacon/internal/onboarding/runtimes.go
@@ -0,0 +1,60 @@
+package onboarding
+
+import (
+ "sort"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness"
+)
+
+// discoverAll is indirected so tests can supply a fake without shelling out.
+var discoverAll = harness.DiscoverAll
+
+// RuntimeProbe is a background agent-runtime discovery pass.
+//
+// harness.DiscoverAll runs `--version` against every supported runtime with a two
+// second timeout each, so a machine with several installed can take tens of seconds
+// in the worst case. That is far too long to sit in front of a prompt. Starting the
+// probe before the first question and collecting it at submit time hides the whole
+// cost behind the time it takes a human to read the disclosure and type an email,
+// and reuses the existing discovery logic rather than maintaining a second copy.
+type RuntimeProbe struct {
+ done chan []string
+}
+
+// StartRuntimeProbe begins discovery immediately and returns a handle to collect it.
+func StartRuntimeProbe() *RuntimeProbe {
+ // Read the indirection on the caller's goroutine rather than inside the worker.
+ // Wait can return before discovery finishes, so the worker may outlive the caller;
+ // capturing here means a test swapping discoverAll back cannot race a live probe.
+ discover := discoverAll
+ p := &RuntimeProbe{done: make(chan []string, 1)}
+ go func() {
+ found := []string{}
+ for _, h := range discover() {
+ if h.Detected {
+ found = append(found, h.Name)
+ }
+ }
+ sort.Strings(found)
+ p.done <- found
+ }()
+ return p
+}
+
+// Wait collects the probe, giving up after timeout.
+//
+// A probe that has not finished in time yields an empty list rather than delaying the
+// install. Missing runtime detail on one row is a far better outcome than a user
+// staring at a stalled prompt.
+func (p *RuntimeProbe) Wait(timeout time.Duration) []string {
+ if p == nil {
+ return []string{}
+ }
+ select {
+ case found := <-p.done:
+ return found
+ case <-time.After(timeout):
+ return []string{}
+ }
+}
diff --git a/cli/beacon/internal/onboarding/runtimes_test.go b/cli/beacon/internal/onboarding/runtimes_test.go
new file mode 100644
index 00000000..fb7fdbfe
--- /dev/null
+++ b/cli/beacon/internal/onboarding/runtimes_test.go
@@ -0,0 +1,84 @@
+package onboarding
+
+import (
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness"
+)
+
+func TestRuntimeProbeReportsDetectedNamesSorted(t *testing.T) {
+ discoverAll = func() []harness.Harness {
+ return []harness.Harness{
+ {Name: "cursor", Detected: true},
+ {Name: "claude_code", Detected: true},
+ {Name: "gemini_cli", Detected: false},
+ }
+ }
+ t.Cleanup(func() { discoverAll = harness.DiscoverAll })
+
+ got := StartRuntimeProbe().Wait(2 * time.Second)
+ if len(got) != 2 || got[0] != "claude_code" || got[1] != "cursor" {
+ t.Fatalf("Wait() = %v, want sorted detected names", got)
+ }
+}
+
+func TestRuntimeProbeOmitsUndetectedRuntimes(t *testing.T) {
+ discoverAll = func() []harness.Harness {
+ return []harness.Harness{{Name: "codex", Detected: false}}
+ }
+ t.Cleanup(func() { discoverAll = harness.DiscoverAll })
+
+ if got := StartRuntimeProbe().Wait(2 * time.Second); len(got) != 0 {
+ t.Fatalf("Wait() = %v, want no entries", got)
+ }
+}
+
+// Discovery shells out to every installed runtime and can take tens of seconds. It
+// must never hold up the install: a slow probe yields nothing rather than blocking.
+func TestRuntimeProbeGivesUpOnSlowDiscovery(t *testing.T) {
+ release := make(chan struct{})
+ discoverAll = func() []harness.Harness {
+ <-release
+ return []harness.Harness{{Name: "claude_code", Detected: true}}
+ }
+ t.Cleanup(func() {
+ close(release)
+ discoverAll = harness.DiscoverAll
+ })
+
+ start := time.Now()
+ got := StartRuntimeProbe().Wait(50 * time.Millisecond)
+ elapsed := time.Since(start)
+
+ if len(got) != 0 {
+ t.Fatalf("Wait() = %v, want empty on timeout", got)
+ }
+ if elapsed > time.Second {
+ t.Fatalf("Wait() blocked for %s, want it to give up promptly", elapsed)
+ }
+}
+
+func TestRuntimeProbeNilIsSafe(t *testing.T) {
+ var p *RuntimeProbe
+ if got := p.Wait(time.Second); len(got) != 0 {
+ t.Fatalf("Wait() on a nil probe = %v, want empty", got)
+ }
+}
+
+// The probe runs concurrently with the prompt, so collecting it twice (retry paths)
+// must not deadlock or panic.
+func TestRuntimeProbeSecondWaitTimesOutCleanly(t *testing.T) {
+ discoverAll = func() []harness.Harness {
+ return []harness.Harness{{Name: "claude_code", Detected: true}}
+ }
+ t.Cleanup(func() { discoverAll = harness.DiscoverAll })
+
+ probe := StartRuntimeProbe()
+ if got := probe.Wait(2 * time.Second); len(got) != 1 {
+ t.Fatalf("first Wait() = %v, want one entry", got)
+ }
+ if got := probe.Wait(10 * time.Millisecond); len(got) != 0 {
+ t.Fatalf("second Wait() = %v, want empty", got)
+ }
+}
diff --git a/cli/beacon/internal/onboarding/submit.go b/cli/beacon/internal/onboarding/submit.go
new file mode 100644
index 00000000..35968952
--- /dev/null
+++ b/cli/beacon/internal/onboarding/submit.go
@@ -0,0 +1,208 @@
+package onboarding
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "time"
+)
+
+// DefaultEndpoint is the signup endpoint compiled into released binaries. It is a var
+// so a release build can retarget it with -ldflags.
+//
+// This is Asymptote's own hostname rather than the raw <project-ref>.supabase.co URL,
+// which keeps the project reference out of every shipped binary. Note the limit of
+// that: auth.asymptotelabs.ai is itself the project's Supabase custom domain, so it
+// cannot be repointed at a different provider without moving auth too. If signups
+// ever need to outlive this Supabase project, put a proxy on a dedicated hostname and
+// change this constant then -- installs already in the wild will keep using whatever
+// they shipped with.
+var DefaultEndpoint = "https://auth.asymptotelabs.ai/functions/v1/beacon-signup"
+
+// EndpointEnv overrides the endpoint. Used by tests and by anyone running their own
+// collector for an internal rollout.
+const EndpointEnv = "BEACON_SIGNUP_ENDPOINT"
+
+const submitTimeout = 5 * time.Second
+
+var httpClient = &http.Client{Timeout: submitTimeout}
+
+// Submission is the payload sent to the signup endpoint.
+//
+// Every field is either something the user typed or something about the install
+// itself. No prompt text, file path, repository name, or telemetry content is
+// included, and the README documents this list verbatim.
+type Submission struct {
+ InstallID string `json:"install_id"`
+ Email string `json:"email"`
+ Usage string `json:"usage"`
+ EmailDomain string `json:"email_domain"`
+ EmailDomainKind string `json:"email_domain_kind"`
+ OS string `json:"os"`
+ Arch string `json:"arch"`
+ OSVersion string `json:"os_version,omitempty"`
+ BeaconVersion string `json:"beacon_version"`
+ InstallMethod string `json:"install_method"`
+ InstallMode string `json:"install_mode"`
+ DetectedRuntimes []string `json:"detected_runtimes"`
+ Source string `json:"source"`
+ ClientSentAt string `json:"client_sent_at"`
+}
+
+// Install method values.
+const (
+ MethodHomebrew = "homebrew"
+ MethodPackage = "package"
+ MethodSource = "source"
+)
+
+// SourceCLIOnboarding marks rows that came from this prompt, so the table can later
+// hold signups from other surfaces without ambiguity.
+const SourceCLIOnboarding = "cli_onboarding"
+
+// Endpoint returns the signup endpoint for this process.
+func Endpoint() string {
+ if v := strings.TrimSpace(os.Getenv(EndpointEnv)); v != "" {
+ return v
+ }
+ return DefaultEndpoint
+}
+
+// Submit posts the signup and reports which outcome to record.
+//
+// It returns an Outcome* constant alongside any error. Callers must treat the outcome
+// as authoritative and the error as explanatory only: onboarding never fails an
+// install, so a returned error is for logging, not for propagating.
+//
+// - 2xx -> OutcomeSubmitted
+// - 4xx, including 429 -> OutcomeRejected (terminal; nothing useful to retry)
+// - 5xx, network, timeout -> OutcomePending (worth resending later)
+func Submit(ctx context.Context, sub Submission) (string, error) {
+ body, err := json.Marshal(sub)
+ if err != nil {
+ // A payload we cannot even marshal will never marshal later either.
+ return OutcomeRejected, fmt.Errorf("encode signup: %w", err)
+ }
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, Endpoint(), bytes.NewReader(body))
+ if err != nil {
+ return OutcomeRejected, fmt.Errorf("build signup request: %w", err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("User-Agent", "beacon/"+sub.BeaconVersion+" ("+sub.OS+"/"+sub.Arch+")")
+
+ resp, err := httpClient.Do(req)
+ if err != nil {
+ return OutcomePending, fmt.Errorf("send signup: %w", err)
+ }
+ defer resp.Body.Close()
+
+ switch {
+ case resp.StatusCode >= 200 && resp.StatusCode < 300:
+ return OutcomeSubmitted, nil
+ case resp.StatusCode >= 500:
+ return OutcomePending, fmt.Errorf("signup endpoint returned %s", resp.Status)
+ default:
+ return OutcomeRejected, fmt.Errorf("signup endpoint returned %s", resp.Status)
+ }
+}
+
+// NewSubmission assembles a payload from the answers plus locally derived install
+// context.
+func NewSubmission(installID, email, usage, beaconVersion, installMode string, runtimes []string) Submission {
+ domain := EmailDomain(email)
+ if runtimes == nil {
+ runtimes = []string{}
+ }
+ return Submission{
+ InstallID: installID,
+ Email: email,
+ Usage: usage,
+ EmailDomain: domain,
+ EmailDomainKind: ClassifyDomain(domain),
+ OS: runtime.GOOS,
+ Arch: runtime.GOARCH,
+ OSVersion: OSVersion(),
+ BeaconVersion: beaconVersion,
+ InstallMethod: InstallMethod(),
+ InstallMode: installMode,
+ DetectedRuntimes: runtimes,
+ Source: SourceCLIOnboarding,
+ ClientSentAt: time.Now().UTC().Format(time.RFC3339),
+ }
+}
+
+// InstallMethod guesses how this binary got onto the machine from where it lives.
+// Homebrew and the signed packages install to well-known prefixes; anything else is
+// treated as a local build.
+func InstallMethod() string {
+ exe, err := os.Executable()
+ if err != nil {
+ return MethodSource
+ }
+ if resolved, err := filepath.EvalSymlinks(exe); err == nil {
+ exe = resolved
+ }
+ switch {
+ case strings.Contains(exe, "/Cellar/"), strings.Contains(exe, "/homebrew/"), strings.Contains(exe, "/linuxbrew/"):
+ return MethodHomebrew
+ case strings.HasPrefix(exe, "/opt/beacon/"), strings.HasPrefix(exe, "/usr/local/beacon/"):
+ return MethodPackage
+ default:
+ return MethodSource
+ }
+}
+
+// OSVersion returns a short OS version string, or "" if it cannot be determined
+// cheaply. This is never worth blocking an install on, so every failure path returns
+// the empty string and the field is omitted from the payload.
+func OSVersion() string {
+ switch runtime.GOOS {
+ case "darwin":
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ out, err := exec.CommandContext(ctx, "sw_vers", "-productVersion").Output()
+ if err != nil {
+ return ""
+ }
+ return strings.TrimSpace(string(out))
+ case "linux":
+ return linuxOSVersion("/etc/os-release")
+ default:
+ return ""
+ }
+}
+
+// linuxOSVersion reads a distribution name and version out of an os-release file.
+// The path is a parameter so the parsing is testable without touching /etc.
+func linuxOSVersion(path string) string {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return ""
+ }
+ fields := map[string]string{}
+ for _, line := range strings.Split(string(data), "\n") {
+ key, value, found := strings.Cut(strings.TrimSpace(line), "=")
+ if !found {
+ continue
+ }
+ fields[key] = strings.Trim(strings.TrimSpace(value), `"'`)
+ }
+ id := fields["ID"]
+ version := fields["VERSION_ID"]
+ switch {
+ case id != "" && version != "":
+ return id + " " + version
+ case fields["PRETTY_NAME"] != "":
+ return fields["PRETTY_NAME"]
+ default:
+ return id
+ }
+}
diff --git a/cli/beacon/internal/onboarding/submit_test.go b/cli/beacon/internal/onboarding/submit_test.go
new file mode 100644
index 00000000..e908fb44
--- /dev/null
+++ b/cli/beacon/internal/onboarding/submit_test.go
@@ -0,0 +1,266 @@
+package onboarding
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestEndpointPrefersEnvOverride(t *testing.T) {
+ t.Setenv(EndpointEnv, "http://127.0.0.1:9999/signup")
+ if got := Endpoint(); got != "http://127.0.0.1:9999/signup" {
+ t.Fatalf("Endpoint() = %q, want the override", got)
+ }
+
+ t.Setenv(EndpointEnv, " ")
+ if got := Endpoint(); got != DefaultEndpoint {
+ t.Fatalf("Endpoint() = %q for a blank override, want the default", got)
+ }
+}
+
+// Released binaries must not carry the raw <project-ref>.supabase.co host: that URL
+// is permanent once shipped and leaks the project reference into every download.
+func TestDefaultEndpointUsesOwnedDomain(t *testing.T) {
+ if DefaultEndpoint != "https://auth.asymptotelabs.ai/functions/v1/beacon-signup" {
+ t.Fatalf("DefaultEndpoint = %q, want the Asymptote-controlled domain", DefaultEndpoint)
+ }
+ if strings.Contains(DefaultEndpoint, "supabase.co") {
+ t.Fatalf("DefaultEndpoint = %q must not embed the Supabase project host", DefaultEndpoint)
+ }
+ if !strings.HasPrefix(DefaultEndpoint, "https://") {
+ t.Fatalf("DefaultEndpoint = %q must be https", DefaultEndpoint)
+ }
+}
+
+func TestSubmitSendsExpectedRequest(t *testing.T) {
+ var (
+ gotMethod string
+ gotContentType string
+ gotBody Submission
+ )
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotMethod = r.Method
+ gotContentType = r.Header.Get("Content-Type")
+ body, _ := io.ReadAll(r.Body)
+ _ = json.Unmarshal(body, &gotBody)
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer srv.Close()
+ t.Setenv(EndpointEnv, srv.URL)
+
+ sub := NewSubmission("abc123", "[email protected]", UsageWork, "v0.0.31", "user", []string{"claude_code", "cursor"})
+ outcome, err := Submit(context.Background(), sub)
+ if err != nil {
+ t.Fatalf("Submit returned error: %v", err)
+ }
+ if outcome != OutcomeSubmitted {
+ t.Fatalf("outcome = %q, want %q", outcome, OutcomeSubmitted)
+ }
+ if gotMethod != http.MethodPost {
+ t.Fatalf("method = %q, want POST", gotMethod)
+ }
+ if gotContentType != "application/json" {
+ t.Fatalf("Content-Type = %q, want application/json", gotContentType)
+ }
+ if gotBody.Email != "[email protected]" || gotBody.InstallID != "abc123" {
+ t.Fatalf("body = %+v, want the submitted identity", gotBody)
+ }
+ if gotBody.EmailDomain != "asymptotelabs.ai" || gotBody.EmailDomainKind != DomainCorporate {
+ t.Fatalf("body domain = %q/%q, want asymptotelabs.ai/corporate", gotBody.EmailDomain, gotBody.EmailDomainKind)
+ }
+ if gotBody.Source != SourceCLIOnboarding {
+ t.Fatalf("source = %q, want %q", gotBody.Source, SourceCLIOnboarding)
+ }
+ if len(gotBody.DetectedRuntimes) != 2 {
+ t.Fatalf("detected_runtimes = %v, want two entries", gotBody.DetectedRuntimes)
+ }
+ if gotBody.OS != runtime.GOOS || gotBody.Arch != runtime.GOARCH {
+ t.Fatalf("os/arch = %q/%q, want %q/%q", gotBody.OS, gotBody.Arch, runtime.GOOS, runtime.GOARCH)
+ }
+ if _, err := time.Parse(time.RFC3339, gotBody.ClientSentAt); err != nil {
+ t.Fatalf("client_sent_at = %q is not RFC3339: %v", gotBody.ClientSentAt, err)
+ }
+}
+
+// The payload is documented in the README, so an accidental new field is a
+// disclosure bug rather than a harmless addition.
+func TestSubmissionCarriesOnlyDocumentedFields(t *testing.T) {
+ sub := NewSubmission("abc123", "[email protected]", UsagePersonal, "v0.0.31", "user", nil)
+ data, err := json.Marshal(sub)
+ if err != nil {
+ t.Fatalf("Marshal: %v", err)
+ }
+ var raw map[string]any
+ if err := json.Unmarshal(data, &raw); err != nil {
+ t.Fatalf("Unmarshal: %v", err)
+ }
+
+ allowed := map[string]bool{
+ "install_id": true, "email": true, "usage": true, "email_domain": true,
+ "email_domain_kind": true, "os": true, "arch": true, "os_version": true,
+ "beacon_version": true, "install_method": true, "install_mode": true,
+ "detected_runtimes": true, "source": true, "client_sent_at": true,
+ }
+ for key := range raw {
+ if !allowed[key] {
+ t.Fatalf("undocumented field %q in the signup payload", key)
+ }
+ }
+}
+
+func TestNewSubmissionAlwaysEncodesRuntimesAsArray(t *testing.T) {
+ sub := NewSubmission("abc123", "[email protected]", UsageWork, "v0.0.31", "system", nil)
+ if sub.DetectedRuntimes == nil {
+ t.Fatalf("DetectedRuntimes = nil, want an empty slice so it encodes as []")
+ }
+ data, _ := json.Marshal(sub)
+ if !strings.Contains(string(data), `"detected_runtimes":[]`) {
+ t.Fatalf("payload = %s, want detected_runtimes as an empty array", data)
+ }
+}
+
+func TestSubmitOutcomeByStatus(t *testing.T) {
+ cases := []struct {
+ name string
+ status int
+ want string
+ wantErr bool
+ }{
+ {"ok", http.StatusOK, OutcomeSubmitted, false},
+ {"created", http.StatusCreated, OutcomeSubmitted, false},
+ {"no content", http.StatusNoContent, OutcomeSubmitted, false},
+ {"bad request is terminal", http.StatusBadRequest, OutcomeRejected, true},
+ {"rate limited is terminal", http.StatusTooManyRequests, OutcomeRejected, true},
+ {"payload too large is terminal", http.StatusRequestEntityTooLarge, OutcomeRejected, true},
+ {"server error is retryable", http.StatusInternalServerError, OutcomePending, true},
+ {"bad gateway is retryable", http.StatusBadGateway, OutcomePending, true},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(tc.status)
+ }))
+ defer srv.Close()
+ t.Setenv(EndpointEnv, srv.URL)
+
+ outcome, err := Submit(context.Background(), Submission{})
+ if outcome != tc.want {
+ t.Fatalf("outcome = %q, want %q", outcome, tc.want)
+ }
+ if tc.wantErr && err == nil {
+ t.Fatalf("Submit returned nil error for status %d", tc.status)
+ }
+ if !tc.wantErr && err != nil {
+ t.Fatalf("Submit returned error for status %d: %v", tc.status, err)
+ }
+ })
+ }
+}
+
+// A network failure must be retryable, never terminal: the lead is still good, the
+// endpoint just was not reachable this minute.
+func TestSubmitUnreachableEndpointIsPending(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
+ url := srv.URL
+ srv.Close()
+ t.Setenv(EndpointEnv, url)
+
+ outcome, err := Submit(context.Background(), Submission{})
+ if outcome != OutcomePending {
+ t.Fatalf("outcome = %q, want %q", outcome, OutcomePending)
+ }
+ if err == nil {
+ t.Fatalf("Submit returned nil error for an unreachable endpoint")
+ }
+}
+
+func TestSubmitRespectsContextCancellation(t *testing.T) {
+ // The handler waits on an explicit release rather than only the request context:
+ // a cancelled client does not always tear the connection down fast enough for
+ // httptest.Server.Close to return, which would hang the suite instead of the
+ // code under test.
+ release := make(chan struct{})
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case <-release:
+ case <-r.Context().Done():
+ }
+ }))
+ defer srv.Close()
+ defer close(release)
+ t.Setenv(EndpointEnv, srv.URL)
+
+ ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
+ defer cancel()
+
+ start := time.Now()
+ outcome, err := Submit(ctx, Submission{})
+ if elapsed := time.Since(start); elapsed > submitTimeout {
+ t.Fatalf("Submit blocked for %s, want the context deadline to win", elapsed)
+ }
+ if outcome != OutcomePending || err == nil {
+ t.Fatalf("outcome = %q err = %v, want pending with an error", outcome, err)
+ }
+}
+
+func TestSubmitMalformedEndpointIsRejected(t *testing.T) {
+ t.Setenv(EndpointEnv, "://not a url")
+ outcome, err := Submit(context.Background(), Submission{})
+ if outcome != OutcomeRejected || err == nil {
+ t.Fatalf("outcome = %q err = %v, want rejected with an error", outcome, err)
+ }
+}
+
+func TestInstallMethodClassifiesKnownPrefixes(t *testing.T) {
+ // InstallMethod reads os.Executable, which in a test is the test binary, so this
+ // asserts the classification is at least a known value rather than a guess.
+ switch got := InstallMethod(); got {
+ case MethodHomebrew, MethodPackage, MethodSource:
+ default:
+ t.Fatalf("InstallMethod() = %q, want one of homebrew/package/source", got)
+ }
+}
+
+func TestLinuxOSVersionParsesOSRelease(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "os-release")
+ content := `NAME="Ubuntu"
+VERSION="22.04.3 LTS (Jammy Jellyfish)"
+ID=ubuntu
+VERSION_ID="22.04"
+PRETTY_NAME="Ubuntu 22.04.3 LTS"
+`
+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
+ t.Fatalf("WriteFile: %v", err)
+ }
+ if got := linuxOSVersion(path); got != "ubuntu 22.04" {
+ t.Fatalf("linuxOSVersion() = %q, want %q", got, "ubuntu 22.04")
+ }
+}
+
+func TestLinuxOSVersionFallsBackToPrettyName(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "os-release")
+ if err := os.WriteFile(path, []byte(`PRETTY_NAME="Some Distro"`+"\n"), 0o644); err != nil {
+ t.Fatalf("WriteFile: %v", err)
+ }
+ if got := linuxOSVersion(path); got != "Some Distro" {
+ t.Fatalf("linuxOSVersion() = %q, want %q", got, "Some Distro")
+ }
+}
+
+// OS version is decoration. A missing or unreadable file returns empty and the field
+// is dropped from the payload rather than failing anything.
+func TestLinuxOSVersionMissingFileIsEmpty(t *testing.T) {
+ if got := linuxOSVersion(filepath.Join(t.TempDir(), "absent")); got != "" {
+ t.Fatalf("linuxOSVersion() = %q for a missing file, want empty", got)
+ }
+}
diff --git a/cli/beacon/internal/onboarding/validate.go b/cli/beacon/internal/onboarding/validate.go
new file mode 100644
index 00000000..41ed2e27
--- /dev/null
+++ b/cli/beacon/internal/onboarding/validate.go
@@ -0,0 +1,231 @@
+package onboarding
+
+import (
+ "errors"
+ "strings"
+)
+
+// Domain classifications reported alongside a submitted address.
+const (
+ DomainCorporate = "corporate"
+ DomainFree = "free"
+ DomainUnknown = "unknown"
+)
+
+// Usage values describe how the operator is running Beacon.
+const (
+ UsageWork = "work"
+ UsagePersonal = "personal"
+ UsageEvaluating = "evaluating"
+)
+
+// ValidUsages lists the accepted usage values in menu order.
+var ValidUsages = []string{UsageWork, UsagePersonal, UsageEvaluating}
+
+// UsageLabels are the human-facing menu entries, indexed alongside ValidUsages.
+var UsageLabels = []string{
+ "Work — at my company",
+ "Personal projects",
+ "Evaluating for my team",
+}
+
+// NormalizeUsage maps loose input onto a canonical usage value.
+func NormalizeUsage(value string) (string, bool) {
+ switch strings.ToLower(strings.TrimSpace(value)) {
+ case "work", "company", "1":
+ return UsageWork, true
+ case "personal", "2":
+ return UsagePersonal, true
+ case "evaluating", "evaluation", "team", "3":
+ return UsageEvaluating, true
+ default:
+ return "", false
+ }
+}
+
+// Email validation is deliberately hand-written rather than a single regex. The
+// point of this check is to produce a message that tells the user what to fix, and a
+// regex can only ever say "no".
+var (
+ ErrEmailEmpty = errors.New("an email address is required")
+ ErrEmailNoAt = errors.New("an email address needs an @ (for example: [email protected])")
+ ErrEmailMultipleAt = errors.New("an email address can only contain one @")
+ ErrEmailNoLocalPart = errors.New("there's nothing before the @")
+ ErrEmailLocalTooLong = errors.New("the part before the @ is too long")
+ ErrEmailLocalBadChar = errors.New("the part before the @ contains a space or control character")
+ ErrEmailNoDomain = errors.New("there's nothing after the @")
+ ErrEmailDomainTooLong = errors.New("the domain is too long")
+ ErrEmailNoDot = errors.New("the domain needs a dot (for example: company.com)")
+ ErrEmailEmptyLabel = errors.New("the domain has an empty part, like a doubled or trailing dot")
+ ErrEmailBadTLD = errors.New("the domain doesn't end in a valid extension")
+ ErrEmailPlaceholder = errors.New("that looks like a placeholder address")
+)
+
+const (
+ maxLocalPart = 64
+ maxDomain = 255
+)
+
+// placeholderDomains are domains that cannot belong to a real mailbox. Accepting one
+// would mean the lead list quietly fills with rows nobody can act on.
+//
+// This list is deliberately short and limited to reserved names (RFC 2606 and RFC
+// 6761) plus documentation stand-ins. Guessing that a registered domain "looks fake"
+// is not worth it: a wrong guess hard-blocks a real user behind an error message,
+// while a junk row only costs us a filter downstream. The server-side MX check is the
+// right place to catch domains that merely cannot receive mail.
+var placeholderDomains = map[string]bool{
+ "example.com": true,
+ "example.net": true,
+ "example.org": true,
+ "example.edu": true,
+ "yourdomain.com": true,
+ "mydomain.com": true,
+ "domain.tld": true,
+ "email.tld": true,
+}
+
+// reservedTLDs can never resolve to a real mailbox (RFC 2606, RFC 6761).
+var reservedTLDs = map[string]bool{
+ "test": true,
+ "invalid": true,
+ "localhost": true,
+ "example": true,
+ "local": true,
+}
+
+// freeProviders are consumer mailbox providers. An address here is not worth less —
+// plenty of contractors and solo developers use one — but it does mean the domain
+// says nothing about which company the user belongs to, so per-domain rate limits and
+// company attribution both have to treat it differently.
+var freeProviders = map[string]bool{
+ "gmail.com": true,
+ "googlemail.com": true,
+ "outlook.com": true,
+ "hotmail.com": true,
+ "hotmail.co.uk": true,
+ "live.com": true,
+ "msn.com": true,
+ "yahoo.com": true,
+ "yahoo.co.uk": true,
+ "ymail.com": true,
+ "icloud.com": true,
+ "me.com": true,
+ "mac.com": true,
+ "aol.com": true,
+ "proton.me": true,
+ "protonmail.com": true,
+ "pm.me": true,
+ "gmx.com": true,
+ "gmx.de": true,
+ "web.de": true,
+ "mail.com": true,
+ "zoho.com": true,
+ "yandex.com": true,
+ "yandex.ru": true,
+ "fastmail.com": true,
+ "hey.com": true,
+ "tutanota.com": true,
+ "tuta.io": true,
+ "qq.com": true,
+ "163.com": true,
+ "126.com": true,
+ "naver.com": true,
+ "duck.com": true,
+}
+
+// NormalizeEmail validates an address and returns it in canonical lowercase form.
+//
+// The returned error is meant to be shown to the user verbatim, so each failure mode
+// gets its own message.
+func NormalizeEmail(input string) (string, error) {
+ email := strings.TrimSpace(input)
+ // People paste addresses out of mail clients, which often wrap them.
+ email = strings.Trim(email, "<>")
+ email = strings.TrimSpace(email)
+ if email == "" {
+ return "", ErrEmailEmpty
+ }
+
+ at := strings.Count(email, "@")
+ switch at {
+ case 0:
+ return "", ErrEmailNoAt
+ case 1:
+ default:
+ return "", ErrEmailMultipleAt
+ }
+
+ local, domain, _ := strings.Cut(email, "@")
+ if local == "" {
+ return "", ErrEmailNoLocalPart
+ }
+ if len(local) > maxLocalPart {
+ return "", ErrEmailLocalTooLong
+ }
+ for _, r := range local {
+ if r <= ' ' || r == 0x7f {
+ return "", ErrEmailLocalBadChar
+ }
+ }
+
+ domain = strings.ToLower(domain)
+ if domain == "" {
+ return "", ErrEmailNoDomain
+ }
+ if len(domain) > maxDomain {
+ return "", ErrEmailDomainTooLong
+ }
+ if !strings.Contains(domain, ".") {
+ return "", ErrEmailNoDot
+ }
+ labels := strings.Split(domain, ".")
+ for _, label := range labels {
+ if label == "" {
+ return "", ErrEmailEmptyLabel
+ }
+ for _, r := range label {
+ isLower := r >= 'a' && r <= 'z'
+ isDigit := r >= '0' && r <= '9'
+ if !isLower && !isDigit && r != '-' {
+ return "", ErrEmailBadTLD
+ }
+ }
+ }
+ tld := labels[len(labels)-1]
+ if len(tld) < 2 {
+ return "", ErrEmailBadTLD
+ }
+ for _, r := range tld {
+ if r < 'a' || r > 'z' {
+ return "", ErrEmailBadTLD
+ }
+ }
+
+ if placeholderDomains[domain] || reservedTLDs[tld] {
+ return "", ErrEmailPlaceholder
+ }
+
+ return strings.ToLower(local) + "@" + domain, nil
+}
+
+// EmailDomain returns the domain of an already-normalized address.
+func EmailDomain(email string) string {
+ _, domain, found := strings.Cut(email, "@")
+ if !found {
+ return ""
+ }
+ return domain
+}
+
+// ClassifyDomain reports whether a domain belongs to a consumer mailbox provider.
+func ClassifyDomain(domain string) string {
+ domain = strings.ToLower(strings.TrimSpace(domain))
+ if domain == "" {
+ return DomainUnknown
+ }
+ if freeProviders[domain] {
+ return DomainFree
+ }
+ return DomainCorporate
+}
diff --git a/cli/beacon/internal/onboarding/validate_test.go b/cli/beacon/internal/onboarding/validate_test.go
new file mode 100644
index 00000000..308a6696
--- /dev/null
+++ b/cli/beacon/internal/onboarding/validate_test.go
@@ -0,0 +1,161 @@
+package onboarding
+
+import (
+ "errors"
+ "testing"
+)
+
+func TestNormalizeEmailAccepts(t *testing.T) {
+ cases := []struct {
+ name string
+ input string
+ want string
+ }{
+ {"uppercase domain", "[email protected]", "[email protected]"},
+ {"uppercase local", "[email protected]", "[email protected]"},
+ {"surrounding space", " [email protected] ", "[email protected]"},
+ {"angle brackets from a mail client", "<[email protected]>", "[email protected]"},
+ {"plus addressing", "[email protected]", "[email protected]"},
+ {"subdomain", "[email protected]", "[email protected]"},
+ {"hyphenated domain", "[email protected]", "[email protected]"},
+ {"digits in domain", "[email protected]", "[email protected]"},
+ {"free provider is still valid", "[email protected]", "[email protected]"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := NormalizeEmail(tc.input)
+ if err != nil {
+ t.Fatalf("NormalizeEmail(%q) returned error: %v", tc.input, err)
+ }
+ if got != tc.want {
+ t.Fatalf("NormalizeEmail(%q) = %q, want %q", tc.input, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestNormalizeEmailRejects(t *testing.T) {
+ cases := []struct {
+ name string
+ input string
+ want error
+ }{
+ {"empty", "", ErrEmailEmpty},
+ {"whitespace only", " ", ErrEmailEmpty},
+ {"no at", "shukan.asymptotelabs.ai", ErrEmailNoAt},
+ {"two ats", "shukan@@asymptotelabs.ai", ErrEmailMultipleAt},
+ {"no local part", "@asymptotelabs.ai", ErrEmailNoLocalPart},
+ {"no domain", "shukan@", ErrEmailNoDomain},
+ {"no dot in domain", "shukan@localhost", ErrEmailNoDot},
+ {"trailing dot", "[email protected].", ErrEmailEmptyLabel},
+ {"doubled dot", "[email protected]", ErrEmailEmptyLabel},
+ {"single character tld", "[email protected]", ErrEmailBadTLD},
+ {"numeric tld", "[email protected]", ErrEmailBadTLD},
+ {"space in local part", "shukan [email protected]", ErrEmailLocalBadChar},
+ {"rfc2606 example domain", "[email protected]", ErrEmailPlaceholder},
+ {"reserved test tld", "[email protected]", ErrEmailPlaceholder},
+ {"reserved invalid tld", "[email protected]", ErrEmailPlaceholder},
+ {"documentation stand-in", "[email protected]", ErrEmailPlaceholder},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := NormalizeEmail(tc.input)
+ if err == nil {
+ t.Fatalf("NormalizeEmail(%q) = %q, want error %v", tc.input, got, tc.want)
+ }
+ if !errors.Is(err, tc.want) {
+ t.Fatalf("NormalizeEmail(%q) error = %v, want %v", tc.input, err, tc.want)
+ }
+ })
+ }
+}
+
+func TestNormalizeEmailRejectsOverlongParts(t *testing.T) {
+ long := make([]byte, maxLocalPart+1)
+ for i := range long {
+ long[i] = 'a'
+ }
+ if _, err := NormalizeEmail(string(long) + "@company.com"); !errors.Is(err, ErrEmailLocalTooLong) {
+ t.Fatalf("overlong local part error = %v, want %v", err, ErrEmailLocalTooLong)
+ }
+}
+
+// A registered domain that merely looks suspicious must still be accepted. A wrong
+// guess hard-blocks a real user; a junk row only costs a downstream filter.
+func TestNormalizeEmailAcceptsRealButOddDomains(t *testing.T) {
+ for _, input := range []string{"[email protected]", "[email protected]", "[email protected]", "[email protected]"} {
+ if _, err := NormalizeEmail(input); err != nil {
+ t.Fatalf("NormalizeEmail(%q) returned error %v, want it accepted", input, err)
+ }
+ }
+}
+
+func TestEmailDomain(t *testing.T) {
+ if got := EmailDomain("[email protected]"); got != "asymptotelabs.ai" {
+ t.Fatalf("EmailDomain() = %q, want %q", got, "asymptotelabs.ai")
+ }
+ if got := EmailDomain("not-an-email"); got != "" {
+ t.Fatalf("EmailDomain() = %q for a malformed address, want empty", got)
+ }
+}
+
+func TestClassifyDomain(t *testing.T) {
+ cases := []struct {
+ domain string
+ want string
+ }{
+ {"asymptotelabs.ai", DomainCorporate},
+ {"some-startup.io", DomainCorporate},
+ {"gmail.com", DomainFree},
+ {"GMAIL.COM", DomainFree},
+ {"icloud.com", DomainFree},
+ {"proton.me", DomainFree},
+ {"", DomainUnknown},
+ {" ", DomainUnknown},
+ }
+ for _, tc := range cases {
+ if got := ClassifyDomain(tc.domain); got != tc.want {
+ t.Fatalf("ClassifyDomain(%q) = %q, want %q", tc.domain, got, tc.want)
+ }
+ }
+}
+
+func TestNormalizeUsage(t *testing.T) {
+ cases := []struct {
+ input string
+ want string
+ ok bool
+ }{
+ {"1", UsageWork, true},
+ {"work", UsageWork, true},
+ {"WORK", UsageWork, true},
+ {" 2 ", UsagePersonal, true},
+ {"personal", UsagePersonal, true},
+ {"3", UsageEvaluating, true},
+ {"evaluating", UsageEvaluating, true},
+ {"team", UsageEvaluating, true},
+ {"", "", false},
+ {"4", "", false},
+ {"maybe", "", false},
+ }
+ for _, tc := range cases {
+ got, ok := NormalizeUsage(tc.input)
+ if ok != tc.ok || got != tc.want {
+ t.Fatalf("NormalizeUsage(%q) = (%q, %t), want (%q, %t)", tc.input, got, ok, tc.want, tc.ok)
+ }
+ }
+}
+
+// The menu prints UsageLabels against ValidUsages by index, so they must stay aligned.
+func TestUsageLabelsMatchValidUsages(t *testing.T) {
+ if len(UsageLabels) != len(ValidUsages) {
+ t.Fatalf("len(UsageLabels) = %d, len(ValidUsages) = %d; they are indexed together", len(UsageLabels), len(ValidUsages))
+ }
+ for i, usage := range ValidUsages {
+ if _, ok := NormalizeUsage(usage); !ok {
+ t.Fatalf("ValidUsages[%d] = %q is not accepted by NormalizeUsage", i, usage)
+ }
+ }
+}
diff --git a/docs/cli/endpoint-onboarding.mdx b/docs/cli/endpoint-onboarding.mdx
new file mode 100644
index 00000000..1bfed617
--- /dev/null
+++ b/docs/cli/endpoint-onboarding.mdx
@@ -0,0 +1,107 @@
+---
+title: "beacon endpoint onboarding"
+description: "Show, reset, or resend the one-time Beacon onboarding record"
+---
+
+## Command Overview
+
+`beacon endpoint onboarding` inspects the one-time onboarding record written the first
+time `beacon endpoint install` runs in a terminal.
+
+```bash title="Command syntax"
+beacon endpoint onboarding [flags]
+```
+
+The record lives in `~/.beacon/profile.json`. It survives uninstall, so reinstalling
+Beacon does not ask again.
+
+## First-run onboarding
+
+The first interactive `beacon endpoint install` asks two questions — how you are using
+Beacon, and your email — and sends the answers to Asymptote once. This is how we decide
+which agent runtimes and integrations to build next.
+
+What is sent, and nothing else:
+
+| Field | Example |
+|-------|---------|
+| Email you enter | `[email protected]` |
+| Work, personal, or evaluating | `work` |
+| OS, architecture, OS version | `darwin`, `arm64`, `15.5` |
+| Beacon version and install method | `v0.0.31`, `homebrew` |
+| Names of agent runtimes on this machine | `claude_code`, `cursor` |
+| A random install ID | `64871b2b…` |
+
+Prompts, file contents, commands, telemetry events, and repository names are never
+sent. The endpoint agent itself stays local-only; this is one request at install time,
+not an ongoing channel.
+
+The prompt never appears non-interactively. Package postinstall scripts, MDM
+deployments, `--system` installs, CI, `--dry-run`, and any piped or redirected stdin
+skip it silently.
+
+## Flags
+
+| Flag | Description |
+|------|-------------|
+| `--reset` | Clear the onboarding record so the question is asked again |
+| `--resend` | Retry a signup that could not be delivered |
+| `--json` | Print the onboarding record as JSON |
+| `--user` | Use per-user endpoint paths. Enabled by default |
+| `--system` | Use system endpoint paths |
+
+## Unattended installs
+
+Set `BEACON_ONBOARDING=0` to suppress the prompt on an install that would otherwise be
+interactive. There is no CLI flag for this: it exists for unattended CI and MDM
+workflows.
+
+```bash title="Suppress the prompt"
+BEACON_ONBOARDING=0 beacon endpoint install
+```
+
+For a fleet rollout where you do want attribution but have no terminal, supply both
+answers up front and Beacon records them without prompting:
+
+```bash title="Headless attribution for MDM"
[email protected] BEACON_ONBOARDING_USAGE=work \
+ beacon endpoint install
+```
+
+`BEACON_ONBOARDING_USAGE` accepts `work`, `personal`, or `evaluating`. An invalid value
+is reported on stderr and ignored rather than failing the install.
+
+## Examples
+
+Show what was recorded:
+
+```bash title="Show the onboarding record"
+beacon endpoint onboarding
+```
+
+Clear it so the next install asks again:
+
+```bash title="Reset the onboarding record"
+beacon endpoint onboarding --reset
+```
+
+Retry a submission that could not reach Asymptote. A failed submission never fails an
+install; the payload is kept and retried automatically on the next install or repair.
+
+```bash title="Resend a queued signup"
+beacon endpoint onboarding --resend
+```
+
+To have your record deleted, email the install ID shown by this command to
+
+## Related
+
+<Columns cols={2}>
+ <Card title="Endpoint install" icon="download" href="/cli/endpoint-install">
+ Configure endpoint telemetry and collector service files.
+ </Card>
+ <Card title="Endpoint config" icon="gear" href="/cli/endpoint-config">
+ Inspect, validate, and update endpoint configuration.
+ </Card>
+</Columns>
diff --git a/docs/cli/endpoint.mdx b/docs/cli/endpoint.mdx
index 1af163b4..7e5b1a4e 100644
--- a/docs/cli/endpoint.mdx
+++ b/docs/cli/endpoint.mdx
@@ -23,6 +23,7 @@ beacon endpoint [command]
<span id="beacon-endpoint-repair" />
<span id="beacon-endpoint-uninstall" />
<span id="beacon-endpoint-config" />
+<span id="beacon-endpoint-onboarding" />
<Columns cols={2}>
<Card title="beacon endpoint install" icon="download" href="/cli/endpoint-install">
@@ -43,6 +44,9 @@ beacon endpoint [command]
<Card title="beacon endpoint config" icon="gear" href="/cli/endpoint-config">
Inspect, validate, and update endpoint configuration.
</Card>
+ <Card title="beacon endpoint onboarding" icon="envelope" href="/cli/endpoint-onboarding">
+ Show, reset, or resend the one-time onboarding record.
+ </Card>
<Card title="beacon scan" icon="magnifying-glass" href="/cli/scan">
Run threat-detection rules over local endpoint telemetry.
</Card>
diff --git a/docs/docs.json b/docs/docs.json
index 6aa99510..d5cc04c7 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -346,6 +346,7 @@
"cli/endpoint-repair",
"cli/endpoint-uninstall",
"cli/endpoint-config",
+ "cli/endpoint-onboarding",
"cli/dashboard",
"cli/wazuh",
"cli/elastic",
diff --git a/packaging/macos/smoke-endpoint.sh b/packaging/macos/smoke-endpoint.sh
index 45905be0..6a74e774 100755
--- a/packaging/macos/smoke-endpoint.sh
+++ b/packaging/macos/smoke-endpoint.sh
@@ -48,11 +48,15 @@ echo "Building temporary beacon..."
go build -o "$BEACON_BIN" .
)
+# stdin comes from /dev/null so this behaves the same whether a developer runs it from
+# a terminal or CI runs it headless. `endpoint install --user` is the one command here
+# that would otherwise prompt for onboarding on a tty and hang the smoke test.
run_beacon() {
- HOME="$HOME_DIR" "$BEACON_BIN" "$@"
+ HOME="$HOME_DIR" "$BEACON_BIN" "$@" </dev/null
}
echo "Installing endpoint config in temporary HOME..."
+INSTALL_OUTPUT="$TMP_DIR/install-output.txt"
run_beacon endpoint install \
--user \
--no-start \
@@ -60,13 +64,27 @@ run_beacon endpoint install \
--log-path "$LOG_PATH" \
--harness claude,codex \
--otlp-grpc-port 55317 \
- --otlp-http-port 55318
+ --otlp-http-port 55318 >"$INSTALL_OUTPUT" 2>&1
+cat "$INSTALL_OUTPUT"
test -f "$HOME_DIR/.beacon/endpoint/config.json"
test -f "$HOME_DIR/.beacon/endpoint/otelcol.yaml"
test -f "$HOME_DIR/Library/LaunchAgents/com.beacon.endpoint.collector.user.plist"
test -f "$LOG_PATH"
+# A non-interactive install must never ask for an email or record an onboarding
+# answer. Package postinstall scripts, MDM deployments, and CI all reach `endpoint
+# install` without a terminal, so a prompt here is a broken fleet rollout.
+if grep -qi 'How are you using Beacon\|^Email:' "$INSTALL_OUTPUT"; then
+ echo "non-interactive endpoint install must not prompt for onboarding" >&2
+ cat "$INSTALL_OUTPUT" >&2
+ exit 1
+fi
+if [ -e "$HOME_DIR/.beacon/profile.json" ]; then
+ echo "non-interactive endpoint install must not write an onboarding profile" >&2
+ exit 1
+fi
+
echo "Checking endpoint status..."
run_beacon endpoint status --user --log-path "$LOG_PATH" >/dev/null