The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
Make the user-wide auto-share switch three-state and stop rewriting projects
Claudea2b5fc3e55e2
diff --git a/CLAUDE.md b/CLAUDE.mdindex f9caa025..e822829e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -69,7 +69,7 @@ Supported runtime surfaces today:- Token usage and runtime-reported cost capture across spans, logs, and metric datapoints, normalized into `gen_ai.usage`, with attribution rollups served by the dashboard token view (`/api/tokens`) and the `beacon token-usage` report command for local and CI logs. Every report row carries three costs (`cli/beacon/internal/tokens/cost.go`): `cost_usd` (runtime-reported, unchanged), `estimated_cost_usd` (list price of every priced token, from `internal/pricing`, computed after dedup and cumulative resolution) and `effective_cost_usd` with `cost_source` (per endpoint/harness/session scope, reported cost wins wholesale when the scope has any; otherwise the estimate; session-less events per event), plus `unpriced_events`/`unpriced_tokens` and a report-level `pricing` block (catalog provenance, per-model key, match, base rates, bands applied, fallbacks, unpriced models). Long-context bands apply only to events `requestScoped` classifies as one model request; it defaults to aggregate, so a new capture path is priced at base rates until it is added there with a test. Lens data (`LensDataV1`) carries no estimate.- Local threat detection via `beacon scan`, which runs the open Threat Rules format (`spec/threat-rules`; CEL match conditions over the endpoint event schema, with embedded conformance fixtures) over the runtime JSONL. The engine (`pkg/asymptoteobserve/threatrules`) ships in the binary; the rule corpus is external data loaded from a local store (`~/.beacon/endpoint/rules`) managed by `beacon rules`, so the corpus can grow without enlarging the binary. `scan` is read-only and offline; only the explicit, user-initiated `beacon rules pull <url>` reaches the network. A small frozen baseline is embedded so `scan` works before any rules are installed.- Session handoff via `beacon handoff list|export|resume` (`cli/beacon/internal/handoff`, `cli/beacon/cmd/handoff*.go`; docs in `docs/cli/handoff.mdx` and `docs/concepts/session-handoff.mdx`). Every runtime is one entry in the registry in `cli/beacon/internal/handoff/runtimes.go`: its session source, the names it answers to, and the commands that reopen it or start it from a brief; `TestRegistryIsConsistent` checks the entries. Handoff reads the session stores of Claude Code, Codex CLI, OpenCode, Cline, Pi, Prime Agent, Factory Droid, GitHub Copilot CLI, Hermes Agent, DeepSeek Harness, fx, Grok Build, OpenClaw Gateway and Cursor read-only and never touches the network. Oh My Pi, Gemini CLI, Qwen Code, Kiro, Antigravity CLI, Devin CLI, Muse Code, OpenHands and goose have no store Beacon reads: their sessions come from the runtime log, and they take a brief as the target of `--agent`. `resume` reopens a session natively with its runtime's own command when it can, and otherwise writes a brief to `~/.beacon/endpoint/handoffs` (0700/0600) and starts a new session pointed at it. DeepSeek Harness cannot be started, and Hermes Agent and fx only reopen their own sessions, so their sessions continue in another runtime. fx, Grok Build and Cursor find a session by the directory they run in, so they are reopened natively only in the session's own directory. The brief is passed by absolute path, never inlined on a command line. Every launch keeps the runtime's approvals on: Beacon never passes a flag that turns them off, names the approval mode that asks where a CLI takes one (Cline always gets `--auto-approve false`, because Cline defaults to approving every tool call), and removes or overrides environment switches that would approve everything (`COPILOT_ALLOW_ALL`, `COPILOT_PLAN_THEN_AUTOPILOT`, `HERMES_YOLO_MODE`, `GOOSE_MODE`); `--print` shows them under `env`. Briefs run every event through `SanitizeEvent`, and quoted content goes in fences longer than any backtick run it contains, with inline fields reduced to one line, so quoted content cannot forge brief structure. A new session's first prompt ends with the `[beacon-handoff from=<harness> session=<id>]` marker (`pkg/asymptoteobserve/handoff.go`). The hook and plugin prompt paths and the session-store mappers record a `session.handoff` event with `handoff.{source_harness,source_session_id}` when they see it; that is an observed claim, not a verified identity.-- Session sharing via `beacon share` and `beacon share refresh` (`cli/beacon/cmd/share.go`; docs in `docs/cli/share.mdx`). It publishes one session the person names (or the most recent in a directory) to beacon.sh as a shared trace that is a `beacon.trace.v1` trace, the projection the dashboard uses: `BuildShareBundle` (sanitize, scrub, then `TraceEventFromEvent`/`TraceBuilder`), the wire types (`ShareTraceV1` summary body, `ShareEventsBatchV1` of `TraceEventV1`s, `ShareTraceStateV1` with `last_event_id`), `ShareExternalID` (`<harness>:<session-id>`, or a sha256 form), `ShareRelation` and `ShareEventsAfter` live in `pkg/asymptoteobserve/share.go`, and the client in `cli/beacon/internal/account/share.go` (`PUT /v1/traces/{external_id}`, `POST .../events/batch` capped at `ShareMaxEventsPerBatch`, `GET`). The chat view is derived on beacon.sh with `TraceMessages` (`pkg/asymptoteobserve/tracemessages.go`), which pairs a tool invocation and its completion by `tool_call_id` and writes a call reported twice once; messages are never uploaded. Sessions resolve through the handoff registry (store first, then the runtime log). Every event goes through `SanitizeEvent` and session-directory/home paths are rewritten in every projected field before projection, and the shared summary drops the working directory and repository path and names the project by `project.name`. `--print` shows the exact `{external_id, trace, events}` payload with no network, `public` needs confirmation (refused without a terminal unless `--yes`), a re-share upserts by stable event id, and a refresh sends only `ShareEventsAfter` the server's `last_event_id` (re-sending it and any tool call still open). After an upload it writes one `session.shared` event (`event.fidelity=inferred`, no collection method) carrying `shared_url`, `visibility`, `shared_at`/`last_refreshed_at` in raw, which the trace list reads as the sharing state; the projection skips that event. It never runs from hooks or in the background. With no selector (or `--current`) it shares the session it runs inside: `BEACON_SESSION_ID`/`BEACON_HARNESS` (the Claude Code SessionStart hook appends both as `export` lines to `$CLAUDE_ENV_FILE`, plain identifiers only; a child runtime inherits them, so without `--harness` they are refused, naming both sessions, when the named session ran outside this directory and its parents or another runtime worked here more recently: `shareEnvContradiction`), then the active-session record (only when the entry was seen at least as recently as the directory's newest session, since OTLP-only and poll runtimes never write it), then the directory's most recent session. The record is `pkg/asymptoteobserve/activesession` (`~/.beacon/endpoint/active-sessions.json`, 0600 under 0700, atomic and locked, at most 256 entries, 14-day prune, an unchanged entry rewritten at most once a minute), written by the hook logger after every endpoint event with a session id, working directory and harness; it holds identifiers and paths only, never content, and hooks write it silently and never touch the network for it. Hook tests point `BEACON_ACTIVE_SESSIONS_FILE` at a temp file in `TestMain`. Auto-share (`beacon share auto enable|disable|status`, `cli/beacon/cmd/share_auto.go`, settings in `pkg/asymptoteobserve/shareauto`) is server-side publishing: when it applies to a session's working directory, the hook logger writes ONE local `session.share_requested` event per session (`event.fidelity=inferred`, `share.visibility`; deduplicated under the active-session record's lock) and Beacon Cloud forwarding ships it; beacon.sh builds and refreshes the trace with the same `BuildShareBundle` projection and `ShareExternalID`. Hooks never upload. The user file `~/.beacon/endpoint/share.json` (0600, CLI-written) holds the user-wide switch and per-project choices by path; a project marker `<repo>/.beacon/share.json` may disable on its own but enables only when the user's file trusts that project, with the user's visibility, so a cloned repository can never publish someone's sessions. `ForHook` costs one failed read when nothing is enabled. Hook tests point `BEACON_SHARE_SETTINGS_FILE` at a temp file. The share projection and `handoff.LogSessions` recency skip `session.share_requested`.+- Session sharing via `beacon share` and `beacon share refresh` (`cli/beacon/cmd/share.go`; docs in `docs/cli/share.mdx`). It publishes one session the person names (or the most recent in a directory) to beacon.sh as a shared trace that is a `beacon.trace.v1` trace, the projection the dashboard uses: `BuildShareBundle` (sanitize, scrub, then `TraceEventFromEvent`/`TraceBuilder`), the wire types (`ShareTraceV1` summary body, `ShareEventsBatchV1` of `TraceEventV1`s, `ShareTraceStateV1` with `last_event_id`), `ShareExternalID` (`<harness>:<session-id>`, or a sha256 form), `ShareRelation` and `ShareEventsAfter` live in `pkg/asymptoteobserve/share.go`, and the client in `cli/beacon/internal/account/share.go` (`PUT /v1/traces/{external_id}`, `POST .../events/batch` capped at `ShareMaxEventsPerBatch`, `GET`). The chat view is derived on beacon.sh with `TraceMessages` (`pkg/asymptoteobserve/tracemessages.go`), which pairs a tool invocation and its completion by `tool_call_id` and writes a call reported twice once; messages are never uploaded. Sessions resolve through the handoff registry (store first, then the runtime log). Every event goes through `SanitizeEvent` and session-directory/home paths are rewritten in every projected field before projection, and the shared summary drops the working directory and repository path and names the project by `project.name`. `--print` shows the exact `{external_id, trace, events}` payload with no network, `public` needs confirmation (refused without a terminal unless `--yes`), a re-share upserts by stable event id, and a refresh sends only `ShareEventsAfter` the server's `last_event_id` (re-sending it and any tool call still open). After an upload it writes one `session.shared` event (`event.fidelity=inferred`, no collection method) carrying `shared_url`, `visibility`, `shared_at`/`last_refreshed_at` in raw, which the trace list reads as the sharing state; the projection skips that event. It never runs from hooks or in the background. With no selector (or `--current`) it shares the session it runs inside: `BEACON_SESSION_ID`/`BEACON_HARNESS` (the Claude Code SessionStart hook appends both as `export` lines to `$CLAUDE_ENV_FILE`, plain identifiers only; a child runtime inherits them, so without `--harness` they are refused, naming both sessions, when the named session ran outside this directory and its parents or another runtime worked here more recently: `shareEnvContradiction`), then the active-session record (only when the entry was seen at least as recently as the directory's newest session, since OTLP-only and poll runtimes never write it), then the directory's most recent session. The record is `pkg/asymptoteobserve/activesession` (`~/.beacon/endpoint/active-sessions.json`, 0600 under 0700, atomic and locked, at most 256 entries, 14-day prune, an unchanged entry rewritten at most once a minute), written by the hook logger after every endpoint event with a session id, working directory and harness; it holds identifiers and paths only, never content, and hooks write it silently and never touch the network for it. Hook tests point `BEACON_ACTIVE_SESSIONS_FILE` at a temp file in `TestMain`. Auto-share (`beacon share auto enable|disable|status`, `cli/beacon/cmd/share_auto.go`, settings in `pkg/asymptoteobserve/shareauto`) is server-side publishing: when it applies to a session's working directory, the hook logger writes ONE local `session.share_requested` event per session (`event.fidelity=inferred`, `share.visibility`; deduplicated under the active-session record's lock) and Beacon Cloud forwarding ships it; beacon.sh builds and refreshes the trace with the same `BuildShareBundle` projection and `ShareExternalID`. Hooks never upload. The user file `~/.beacon/endpoint/share.json` (0600, CLI-written) holds the user-wide switch, three-state (unset, on, or off as a kill switch over every project; `auto.state`, with `auto.enabled` kept in step so older files read) and per-project choices by path, which a user-wide enable or disable never rewrites; a project marker `<repo>/.beacon/share.json` may disable on its own but enables only when the user's file trusts that project, with the user's visibility, so a cloned repository can never publish someone's sessions. `ForHook` costs one failed read when nothing is enabled. Hook tests point `BEACON_SHARE_SETTINGS_FILE` at a temp file. The share projection and `handoff.LogSessions` recency skip `session.share_requested`.- Commit-to-session links via `beacon git setup|status|remove|link|notes` (`cli/beacon/internal/gitlink`, `cli/beacon/cmd/git*.go`; docs in `docs/cli/git.mdx`). A link is a `beacon:<harness>/<session-id>` line in a git note under `refs/notes/beacon`; it carries identifiers only, never content, because notes can be pushed. Which sessions to link is inferred from the local runtime log: a session is linked when, between the parent commit and the commit (at least two hours, at most 24), it wrote a file the commit changes (for a merge, only files that differ from every parent, so a clean merge or pull links nothing). Evidence is file write events, write-type `file.operation`s, plainly readable shell targets, and `apply_patch` envelopes; reads never count. Note updates are a compare-and-swap on the notes ref through a private `refs/notes/beacon-tx/` working ref, and every existing note line, a teammate's or a person's, is kept verbatim. `setup` installs post-commit (links HEAD in the foreground with a 3 s budget, silent, never fails the commit, skips rebase/cherry-pick/revert) and post-rewrite (normalizes the note git concatenates on amend) as standalone `beacon-<hook>` scripts called from a marked block inserted after the shebang of the repository's own hook; only shell hooks are edited, `core.hooksPath` is refused without `--hooks-path`, and `notes.rewriteRef` carries links through amend and rebase. `BEACON_GIT_HOOKS=0` disables the hooks for one command. Every link a run adds is also written to the runtime log as one `session.commit_linked` event in the linked session's timeline (`event.fidelity=inferred`, no collection method), with commit id, branch and credential-stripped remote in the OTel-shaped `vcs` block and overlap counts in `vcs.attribution`; the event deliberately carries no file, command or tool fields so it can never become attribution evidence. Sharing is opt-in (`setup --share-notes`, off by default): a non-destructive fetch refspec `+refs/notes/beacon:refs/notes/beacon-remotes/<remote>` so git's own fetch brings teammates' links into a read-only tracking ref that `beacon git notes` unions with the local one (never force-fetch into `refs/notes/beacon`: it would destroy unpushed links), and a pre-push hook that fetches, merges with `cat_sort_uniq` through the same CAS, and pushes only the notes ref with `--no-verify`, within a 10 s budget and never failing the push. That pre-push hook is the only Beacon git hook that touches the network, and only during a push the person started; `beacon git notes push|fetch` do the same by hand.- Beacon Cloud MCP registration via `beacon mcp connect|disconnect|status` (`cli/beacon/internal/mcpconnect`, `cli/beacon/cmd/mcp_connect.go`; docs in `docs/cli/mcp-connect.mdx`). It registers the Beacon Cloud MCP server as `beacon-managed`, a different name from the local stdio server `beacon`, in the user-level config of Claude Code, Codex CLI, Cursor, VS Code, Gemini CLI and OpenCode. It prints manual steps for runtimes without confirmed MCP OAuth support. OAuth is the default and writes only the URL; `--token-env` writes a reference to an environment variable in each harness's own syntax, never a value. `connect` never reads or copies the account token and never writes a token; minting one is the separate, explicit `beacon mcp token create`. It is explicit and interactive: never run by an unattended install; the onboarding wizard runs it only after the person chose Beacon Cloud and left "Beacon Cloud MCP" selected (that screen is the confirmation), and otherwise the install only suggests it. It is refused as root, and refused in CI or without a terminal unless `--yes` is given. Its one network request is the RFC 9728 resource-metadata check of the URL, which `--dry-run` skips. Configs are edited like the Kimi Code writer: never re-serialized, spliced as text, parsed back and compared before an atomic replace, backed up first. What was written is recorded in `~/.beacon/mcp/connections.json`, and `disconnect` removes only entries recorded there that still point at the recorded URL. `cmd/mcp_connect_e2e_test.go` runs the real harness CLIs when they are installed; re-run it when a harness changes its MCP config format.- An optional, off-by-default policy seam in the hook path (`cli/beacon-hooks/internal/policy`) governed by the stable contract in `pkg/asymptoteobserve/policycontract`. When `BEACON_POLICY_PROVIDER` names an executable, the `pre-tool` and `permission-request` hooks send it a JSON request describing the imminent tool call and honor an allow/deny response, returning the runtime's native deny shape and `policy.enforcement=enforce` telemetry on a deny. The seam is inert when unset and fail-open on any error (timeout, non-zero exit, malformed output), so the open build ships no enforcement of its own; all audit/enforce decision logic lives in the external provider. `rules/agent-control/agent-permission-bypass-spawn.rule.yaml` is the open detect twin that flags the same pattern in `beacon scan`.diff --git a/cli/beacon/cmd/share_auto.go b/cli/beacon/cmd/share_auto.goindex 4011cf62..3d8281f0 100644--- a/cli/beacon/cmd/share_auto.go+++ b/cli/beacon/cmd/share_auto.go@@ -103,20 +103,42 @@ func init() {}type shareAutoStatus struct {- SettingsPath string `json:"settings_path"`- Directory string `json:"directory"`- Enabled bool `json:"enabled"`- Visibility string `json:"visibility,omitempty"`- Source string `json:"source,omitempty"`- Project string `json:"project,omitempty"`- UntrustedMarker string `json:"untrusted_marker,omitempty"`- UserEnabled bool `json:"user_enabled"`- UserVisibility string `json:"user_visibility,omitempty"`- CloudConnected bool `json:"cloud_connected"`- CloudPrivacyMode string `json:"cloud_privacy_mode,omitempty"`- Warnings []string `json:"warnings,omitempty"`- // ProjectsTurnedOff are the project entries a user-wide disable turned off with it.- ProjectsTurnedOff []string `json:"projects_turned_off,omitempty"`+ SettingsPath string `json:"settings_path"`+ Directory string `json:"directory"`+ Enabled bool `json:"enabled"`+ Visibility string `json:"visibility,omitempty"`+ Source string `json:"source,omitempty"`+ Project string `json:"project,omitempty"`+ UntrustedMarker string `json:"untrusted_marker,omitempty"`+ // Overridden is the project whose enabled entry the user-wide off switch overrides here.+ Overridden string `json:"overridden,omitempty"`+ UserEnabled bool `json:"user_enabled"`+ UserState string `json:"user_state"`+ UserVisibility string `json:"user_visibility,omitempty"`+ // Projects are the user's project entries, each with whether the user-wide off switch+ // overrides it.+ Projects []shareAutoProject `json:"projects,omitempty"`+ CloudConnected bool `json:"cloud_connected"`+ CloudPrivacyMode string `json:"cloud_privacy_mode,omitempty"`+ Warnings []string `json:"warnings,omitempty"`+ // GlobalOffCleared is set when enable --project cleared the user-wide off switch.+ GlobalOffCleared bool `json:"global_off_cleared,omitempty"`+}++// shareAutoProject is one project entry in the status.+type shareAutoProject struct {+ Path string `json:"path"`+ Enabled bool `json:"enabled"`+ Visibility string `json:"visibility,omitempty"`+ Overridden bool `json:"overridden,omitempty"`+}++// shareAutoUserState names the user-wide switch's state for people: "on", "off" or "not set".+func shareAutoUserState(state string) string {+ if state == shareauto.GlobalUnset {+ return "not set"+ }+ return state}func runShareAutoSet(cmd *cobra.Command, enable bool) error {@@ -150,7 +172,7 @@ func shareAutoSet(cmd *cobra.Command, enable bool) error {return fmt.Errorf("read %s: %w (fix or remove it, then retry)", path, err)}project := ""- var turnedOff []string+ globalOffCleared := falseif strings.TrimSpace(shareAutoOpts.project) != "" {project, err = filepath.Abs(shareAutoOpts.project)if err != nil {@@ -168,21 +190,20 @@ func shareAutoSet(cmd *cobra.Command, enable bool) error {if !replaced {settings.Projects = append(settings.Projects, entry)}- } else {- settings.Auto.Enabled = enable- if enable {- settings.Auto.Visibility = visibility- } else {- // Off for every new session means every project too: a project entry is checked- // before the user-wide switch, so one left enabled would keep publishing. The entries- // stay, turned off, so `enable --project` can bring one back.- for i := range settings.Projects {- if settings.Projects[i].Enabled {- settings.Projects[i].Enabled = false- turnedOff = append(turnedOff, settings.Projects[i].Path)- }- }+ // Opting a project in while the user-wide switch is off: the person wants it on here, so+ // the kill switch goes back to unset (not on: other sessions stay off).+ if enable && settings.Global() == shareauto.GlobalOff {+ settings.SetGlobal(shareauto.GlobalUnset)+ globalOffCleared = true}+ } else if enable {+ // Project entries are left as they are, so turning auto-share back on restores exactly+ // what was there before it was turned off.+ settings.SetGlobal(shareauto.GlobalOn)+ settings.Auto.Visibility = visibility+ } else {+ // Off is a kill switch over every project (shareauto.Resolve); the entries stay untouched.+ settings.SetGlobal(shareauto.GlobalOff)}if err := shareauto.Save(path, settings); err != nil {return err@@ -197,7 +218,7 @@ func shareAutoSet(cmd *cobra.Command, enable bool) error {dir, _ = filepath.Abs(".")}status := buildShareAutoStatus(path, settings, dir)- status.ProjectsTurnedOff = turnedOff+ status.GlobalOffCleared = globalOffClearedreturn printShareAutoResult(cmd, status, enable, project)}@@ -223,15 +244,23 @@ func buildShareAutoStatus(path string, settings shareauto.Settings, dir string)Source: decision.Source,Project: decision.Project,UntrustedMarker: decision.UntrustedMarker,- UserEnabled: settings.Auto.Enabled,+ Overridden: decision.Overridden,+ UserEnabled: settings.Global() == shareauto.GlobalOn,+ UserState: settings.Global(),UserVisibility: settings.Auto.Visibility,CloudConnected: connected,CloudPrivacyMode: mode,}+ for _, p := range settings.Projects {+ status.Projects = append(status.Projects, shareAutoProject{+ Path: p.Path, Enabled: p.Enabled, Visibility: p.Visibility,+ Overridden: p.Enabled && settings.Global() == shareauto.GlobalOff,+ })+ }if status.Enabled && status.Visibility == "" {status.Visibility = asymptoteobserve.ShareVisibilityDirect}- if status.Enabled || settings.Auto.Enabled {+ if status.Enabled || status.UserEnabled {if !connected {status.Warnings = append(status.Warnings, "this endpoint is not connected to Beacon Cloud, so nothing is published: auto-share works only through Beacon Cloud forwarding (`beacon endpoint connect`); `beacon share` publishes a session by hand")} else if mode == managedprivacy.MetadataOnly {@@ -256,10 +285,24 @@ func printShareAutoResult(cmd *cobra.Command, status shareAutoStatus, enable booif enable {fmt.Fprintf(out, "Auto-share is on for %s (%s).\n", scope, status.Visibility)fmt.Fprintln(out, "Sessions that are already running are shared on their next event; earlier sessions are not. Use `beacon share` for those.")+ if status.GlobalOffCleared {+ fmt.Fprintln(out, "Auto-share was turned off for every session; that switch is now cleared, so projects you turned on publish again and other sessions stay off.")+ }} else {fmt.Fprintf(out, "Auto-share is off for %s. Traces already published stay published; delete them on beacon.sh.\n", scope)- for _, p := range status.ProjectsTurnedOff {- fmt.Fprintf(out, "Turned off for the project %s too.\n", p)+ if project == "" {+ var overridden []string+ for _, p := range status.Projects {+ if p.Overridden {+ overridden = append(overridden, p.Path)+ }+ }+ if len(overridden) > 0 {+ fmt.Fprintf(out, "This overrides %d project setting(s), which are kept and apply again after `beacon share auto enable`:\n", len(overridden))+ for _, p := range overridden {+ fmt.Fprintf(out, " %s\n", p)+ }+ }}}if project != "" {@@ -300,7 +343,29 @@ func runShareAutoStatus(cmd *cobra.Command, args []string) error {case "marker":fmt.Fprintf(out, " turned off by %s\n", shareauto.MarkerPath(status.Project))case "user":- fmt.Fprintln(out, " decided by your setting for every session")+ if status.Overridden != "" {+ fmt.Fprintf(out, " turned off for every session, which overrides your setting for the project %s\n", status.Overridden)+ } else {+ fmt.Fprintln(out, " decided by your setting for every session")+ }+ }+ userState := shareAutoUserState(status.UserState)+ if status.UserState == shareauto.GlobalOn && status.UserVisibility != "" {+ userState += " (" + status.UserVisibility + ")"+ }+ fmt.Fprintf(out, "Every session: %s\n", userState)+ for _, p := range status.Projects {+ state := "off"+ if p.Enabled {+ state = "on"+ if p.Visibility != "" {+ state += " (" + p.Visibility + ")"+ }+ }+ if p.Overridden {+ state += ", overridden by the off switch for every session"+ }+ fmt.Fprintf(out, "Project %s: %s\n", p.Path, state)}cloud := "not connected"if status.CloudConnected {diff --git a/cli/beacon/cmd/share_auto_test.go b/cli/beacon/cmd/share_auto_test.goindex 57374915..dc98a1f6 100644--- a/cli/beacon/cmd/share_auto_test.go+++ b/cli/beacon/cmd/share_auto_test.go@@ -137,10 +137,9 @@ func TestShareAutoProjectScopeAndStatus(t *testing.T) {}}-// A user-wide disable turns off projects enabled with --project too: their entries are checked-// before the user-wide switch, so leaving one on would keep publishing after "off for every new-// session".-func TestShareAutoGlobalDisableTurnsOffProjects(t *testing.T) {+// The user-wide off switch overrides projects enabled with --project without rewriting their+// entries, so turning auto-share back on restores exactly what was there.+func TestShareAutoGlobalDisableOverridesProjects(t *testing.T) {path := shareAutoTestEnv(t, true, managedprivacy.Standard)project := t.TempDir()if _, _, err := runShareAuto(t, "enable", "--project", project); err != nil {@@ -153,19 +152,49 @@ func TestShareAutoGlobalDisableTurnsOffProjects(t *testing.T) {if err != nil {t.Fatalf("disable: %v", err)}- if !strings.Contains(stdout, "Auto-share is off for every new session") || !strings.Contains(stdout, "Turned off for the project "+project) {+ if !strings.Contains(stdout, "Auto-share is off for every new session") || !strings.Contains(stdout, "overrides 1 project setting") || !strings.Contains(stdout, project) {t.Fatalf("stdout = %q", stdout)}settings, _ := shareauto.Load(path)- if entry, ok := settings.Project(project); !ok || entry.Enabled {- t.Fatalf("project entry = %+v %v, want kept and off", entry, ok)+ if entry, ok := settings.Project(project); !ok || !entry.Enabled || settings.Global() != shareauto.GlobalOff {+ t.Fatalf("settings = %+v, want the project entry untouched and the switch off", settings)}// What the hook adapter decides: no session.share_requested is written in the project.if d := shareauto.ForHook(path, filepath.Join(project, "sub")); d.Enabled {- t.Fatalf("hook decision after a global disable = %+v", d)+ t.Fatalf("hook decision under the off switch = %+v", d)}stdout, _, err = runShareAuto(t, "status", "--project", project)- if err != nil || !strings.Contains(stdout, "Auto-share in "+project+": off") {+ if err != nil || !strings.Contains(stdout, "Auto-share in "+project+": off") || !strings.Contains(stdout, "Every session: off") || !strings.Contains(stdout, "overridden by the off switch") {t.Fatalf("status = %q (%v)", stdout, err)}+ // Turning it back on restores the project.+ if _, _, err := runShareAuto(t, "enable"); err != nil {+ t.Fatalf("enable: %v", err)+ }+ if d := shareauto.ForHook(path, project); !d.Enabled || d.Source != "project" {+ t.Fatalf("project after re-enable = %+v", d)+ }+}++// Opting a project in while the off switch is set clears the switch back to unset.+func TestShareAutoProjectEnableClearsTheOffSwitch(t *testing.T) {+ path := shareAutoTestEnv(t, true, managedprivacy.Standard)+ project, other := t.TempDir(), t.TempDir()+ if _, _, err := runShareAuto(t, "disable"); err != nil {+ t.Fatalf("disable: %v", err)+ }+ stdout, _, err := runShareAuto(t, "enable", "--project", project)+ if err != nil {+ t.Fatalf("enable --project: %v", err)+ }+ if !strings.Contains(stdout, "now cleared") {+ t.Fatalf("stdout = %q", stdout)+ }+ settings, _ := shareauto.Load(path)+ if settings.Global() != shareauto.GlobalUnset {+ t.Fatalf("global = %q, want unset", settings.Global())+ }+ if !shareauto.ForHook(path, project).Enabled || shareauto.ForHook(path, other).Enabled {+ t.Fatal("want the project on and other directories off")+ }}diff --git a/docs/cli/share.mdx b/docs/cli/share.mdxindex ed67a727..d4750788 100644--- a/docs/cli/share.mdx+++ b/docs/cli/share.mdx@@ -133,9 +133,9 @@ beacon share auto statusbeacon share auto disable```-`enable` warns when the endpoint is not connected to Beacon Cloud, because then nothing is published (the event is written and stays local), and when forwarding is in metadata-only mode, because the trace then has no prompts, answers, reasoning or tool output. `--visibility public` lists every new session in Discover; it asks first, and without a terminal it is refused unless you pass `--yes`. Sessions already running are requested on their next event; earlier sessions are not, so share those with `beacon share`. Turning auto-share off stops new requests; traces already published stay until you delete them on beacon.sh. `disable` without `--project` turns it off everywhere, including every project you enabled with `--project` (the entries are kept, turned off, and named in the output); `disable --project <dir>` turns off only that project.+`enable` warns when the endpoint is not connected to Beacon Cloud, because then nothing is published (the event is written and stays local), and when forwarding is in metadata-only mode, because the trace then has no prompts, answers, reasoning or tool output. `--visibility public` lists every new session in Discover; it asks first, and without a terminal it is refused unless you pass `--yes`. Sessions already running are requested on their next event; earlier sessions are not, so share those with `beacon share`. Turning auto-share off stops new requests; traces already published stay until you delete them on beacon.sh. `disable` without `--project` turns it off everywhere: it overrides every project you enabled with `--project`, which it names, without changing their settings, so a later `enable` brings back exactly what was on before. `disable --project <dir>` turns off only that project. `enable --project <dir>` while it is off everywhere clears that switch (other sessions stay off) and says so.-The setting is in `~/.beacon/endpoint/share.json` (0600). `--project <dir>` applies the choice to one project: it is recorded there for you by path, and `<dir>/.beacon/share.json` records it in the repository so it can be committed. A project file can turn auto-share off on its own, but it turns it on only for someone who ran `beacon share auto enable --project` in that project, and the visibility always comes from that person's own setting. A cloned repository can never publish your sessions. The nearest project with a choice decides; elsewhere, the setting for every session does. `status` shows which applies in the current directory (or `--project`), why, and the forwarding state; `--json` prints it as a document.+The setting is in `~/.beacon/endpoint/share.json` (0600). `--project <dir>` applies the choice to one project: it is recorded there for you by path, and `<dir>/.beacon/share.json` records it in the repository so it can be committed. A project file can turn auto-share off on its own, but it turns it on only for someone who ran `beacon share auto enable --project` in that project, and the visibility always comes from that person's own setting. A cloned repository can never publish your sessions. The nearest project with a choice decides; elsewhere, the setting for every session does. `status` shows which applies in the current directory (or `--project`) and why, the setting for every session (on, off or not set), each project you set and whether the off switch overrides it, and the forwarding state; `--json` prints it as a document.The `session.share_requested` event is marked `event.fidelity=inferred` because Beacon originated it rather than a runtime reporting it, and it is not itself part of any shared trace.diff --git a/pkg/asymptoteobserve/shareauto/shareauto.go b/pkg/asymptoteobserve/shareauto/shareauto.goindex f7b2b734..3fa38f72 100644--- a/pkg/asymptoteobserve/shareauto/shareauto.go+++ b/pkg/asymptoteobserve/shareauto/shareauto.go@@ -45,12 +45,22 @@ const ()// Auto is one auto-share switch and the visibility it shares with ("" means the server default,-// direct).+// direct). In the user file the switch has three states (State): unset, on, or off; off is a kill+// switch over every project. Enabled is kept equal to State == on, so a file written by an older+// Beacon (enabled only) still reads: enabled true is on, false is unset. A marker uses Enabled only.type Auto struct {Enabled bool `json:"enabled"`+ State string `json:"state,omitempty"`Visibility string `json:"visibility,omitempty"`}+// The user-wide switch's states.+const (+ GlobalUnset = ""+ GlobalOn = "on"+ GlobalOff = "off"+)+// Project is the user's choice for one project directory.type Project struct {Path string `json:"path"`@@ -75,15 +85,36 @@ type Marker struct {type Decision struct {Enabled boolVisibility string- // Source is "user", "project" (the user's entry for a project), "marker" (a project marker- // turned it off) or "" when nothing is configured.+ // Source is "user" (the user-wide switch, on, or off as the kill switch), "project" (the user's+ // entry for a project), "marker" (a project marker turned it off) or "" when nothing is+ // configured.Source string// Project is the project directory the decision came from, when it came from one.Project string+ // Overridden is the project whose enabled entry the user-wide off switch overrides here.+ Overridden string// UntrustedMarker is a marker that asks for auto-share in a project the user has not opted in.UntrustedMarker string}+// Global is the user-wide switch's state: GlobalOn, GlobalOff or GlobalUnset.+func (s Settings) Global() string {+ switch s.Auto.State {+ case GlobalOn, GlobalOff:+ return s.Auto.State+ }+ if s.Auto.Enabled {+ return GlobalOn+ }+ return GlobalUnset+}++// SetGlobal sets the user-wide switch, keeping Enabled in step for older readers.+func (s *Settings) SetGlobal(state string) {+ s.Auto.State = state+ s.Auto.Enabled = state == GlobalOn+}+// DefaultPath is BEACON_SHARE_SETTINGS_FILE, or ~/.beacon/endpoint/share.json.func DefaultPath() string {if p := strings.TrimSpace(os.Getenv(PathEnv)); p != "" {@@ -135,7 +166,10 @@ func LoadMarker(dir string) (Marker, bool) {// anyEnabled reports whether anything in s could turn auto-share on, so the hook path can skip// the directory walk entirely when the feature is not in use.func (s Settings) anyEnabled() bool {- if s.Auto.Enabled {+ switch s.Global() {+ case GlobalOff:+ return false+ case GlobalOn:return true}for _, p := range s.Projects {@@ -159,10 +193,24 @@ func (s Settings) Project(dir string) (Project, bool) {return Project{}, false}-// Resolve decides whether auto-share applies in workDir. The nearest enclosing directory that has-// a user entry or a marker decides; a marker that asks for auto-share without a user entry is-// reported and otherwise ignored. With neither, the user-wide switch decides.+// Resolve decides whether auto-share applies in workDir. The user-wide switch turned off is a kill+// switch: nothing applies anywhere, and the project entry it overrides is reported. Otherwise the+// nearest enclosing directory that has a user entry or a marker decides; a marker that asks for+// auto-share without a user entry is reported and otherwise ignored. With neither, the user-wide+// switch decides (on, or unset meaning off).func Resolve(s Settings, workDir string) Decision {+ d := resolveProjects(s, workDir)+ if s.Global() == GlobalOff {+ off := Decision{Source: "user", UntrustedMarker: d.UntrustedMarker}+ if d.Enabled && d.Source == "project" {+ off.Overridden = d.Project+ }+ return off+ }+ return d+}++func resolveProjects(s Settings, workDir string) Decision {var d Decisiondir := filepath.Clean(workDir)if workDir != "" && rooted(dir) {@@ -193,7 +241,7 @@ func Resolve(s Settings, workDir string) Decision {dir = parent}}- if s.Auto.Enabled {+ if s.Global() == GlobalOn {d.Enabled, d.Visibility, d.Source = true, s.Auto.Visibility, "user"}return ddiff --git a/pkg/asymptoteobserve/shareauto/shareauto_test.go b/pkg/asymptoteobserve/shareauto/shareauto_test.goindex b0f2ee3d..4db445e6 100644--- a/pkg/asymptoteobserve/shareauto/shareauto_test.go+++ b/pkg/asymptoteobserve/shareauto/shareauto_test.go@@ -103,3 +103,55 @@ func TestResolveMatchesEquivalentPaths(t *testing.T) {t.Fatalf("rooted path: %+v", d)}}++// The user-wide off switch overrides every project; on or unset leaves project entries deciding.+func TestGlobalOffIsAKillSwitch(t *testing.T) {+ repo := t.TempDir()+ s := Settings{Projects: []Project{{Path: repo, Enabled: true, Visibility: "direct"}}}+ if d := Resolve(s, repo); !d.Enabled || d.Source != "project" {+ t.Fatalf("unset = %+v", d)+ }+ s.SetGlobal(GlobalOff)+ if d := Resolve(s, repo); d.Enabled || d.Source != "user" || d.Overridden != repo {+ t.Fatalf("off = %+v", d)+ }+ path := filepath.Join(t.TempDir(), FileName)+ if err := Save(path, s); err != nil {+ t.Fatal(err)+ }+ if d := ForHook(path, repo); d.Enabled {+ t.Fatalf("ForHook under the kill switch = %+v", d)+ }+ s.SetGlobal(GlobalOn)+ off := Settings{Auto: s.Auto, Projects: []Project{{Path: repo, Enabled: false}}}+ if d := Resolve(off, repo); d.Enabled || d.Source != "project" {+ t.Fatalf("project off under global on = %+v", d)+ }+}++// A file written before the switch had three states (enabled only) still reads.+func TestLoadReadsTheOldFormat(t *testing.T) {+ dir := t.TempDir()+ repo := t.TempDir()+ for _, tc := range []struct {+ body string+ want string+ }{+ {`{"schema_version":"beacon.share_settings.v1","auto":{"enabled":true,"visibility":"private"}}`, GlobalOn},+ {`{"schema_version":"beacon.share_settings.v1","auto":{"enabled":false},"projects":[{"path":"` + filepath.ToSlash(repo) + `","enabled":true}]}`, GlobalUnset},+ } {+ path := filepath.Join(dir, FileName)+ if err := os.WriteFile(path, []byte(tc.body), 0o600); err != nil {+ t.Fatal(err)+ }+ s, err := Load(path)+ if err != nil || s.Global() != tc.want {+ t.Fatalf("%s: global = %q (err %v), want %q", tc.body, s.Global(), err, tc.want)+ }+ if tc.want == GlobalUnset {+ if d := Resolve(s, repo); !d.Enabled || d.Source != "project" {+ t.Fatalf("old project entry = %+v", d)+ }+ }+ }+}