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
Add auto-share through Beacon Cloud: beacon share auto enable|disable|status
Claude55acb0967ad1
diff --git a/CLAUDE.md b/CLAUDE.mdindex 2cc7b182..c4fd68f8 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 under the `beacon.share.v1` contract: the types, `ShareExternalID` (`<harness>:<session-id>`, or a sha256 form) and the event-to-message projection `BuildShareMessages` live in `pkg/asymptoteobserve/share.go`, and the client in `cli/beacon/internal/account/share.go`. Sessions resolve through the handoff registry (store first, then the runtime log). Every event goes through `SanitizeEvent` and session-directory/home paths are rewritten before projection; a tool invocation and its completion become a `tool_call` and a `tool_result` message sharing one callId, and a call reported twice is written once. `--print` shows the exact payload with no network, `public` needs confirmation (refused without a terminal unless `--yes`), and a re-share upserts by stable message id. 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), then the active-session record, 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`.+- 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 under the `beacon.share.v1` contract: the types, `ShareExternalID` (`<harness>:<session-id>`, or a sha256 form) and the event-to-message projection `BuildShareMessages` live in `pkg/asymptoteobserve/share.go`, and the client in `cli/beacon/internal/account/share.go`. Sessions resolve through the handoff registry (store first, then the runtime log). Every event goes through `SanitizeEvent` and session-directory/home paths are rewritten before projection; a tool invocation and its completion become a `tool_call` and a `tool_result` message sharing one callId, and a call reported twice is written once. `--print` shows the exact payload with no network, `public` needs confirmation (refused without a terminal unless `--yes`), and a re-share upserts by stable message id. 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), then the active-session record, 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 `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`.- 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-hooks/cmd/main_test.go b/cli/beacon-hooks/cmd/main_test.goindex 6e11e486..273a06ce 100644--- a/cli/beacon-hooks/cmd/main_test.go+++ b/cli/beacon-hooks/cmd/main_test.go@@ -6,6 +6,7 @@ import ("testing""github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/activesession"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/shareauto")// TestMain keeps the active-session record every endpoint event updates out of the real home@@ -16,6 +17,8 @@ func TestMain(m *testing.M) {panic(err)}os.Setenv(activesession.PathEnv, filepath.Join(dir, activesession.FileName))+ // Auto-share is off unless a test turns it on in a settings file of its own.+ os.Setenv(shareauto.PathEnv, filepath.Join(dir, "share-settings.json"))// A suite run from inside a Claude Code session must not append to that session's env file.os.Unsetenv("CLAUDE_ENV_FILE")code := m.Run()diff --git a/cli/beacon-hooks/cmd/share_auto_test.go b/cli/beacon-hooks/cmd/share_auto_test.gonew file mode 100644index 00000000..13f787d3--- /dev/null+++ b/cli/beacon-hooks/cmd/share_auto_test.go@@ -0,0 +1,123 @@+package cmd++import (+ "errors"+ "net/http"+ "path/filepath"+ "testing"++ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/activesession"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/shareauto"+)++type failingTransport struct{ t *testing.T }++func (f failingTransport) RoundTrip(r *http.Request) (*http.Response, error) {+ f.t.Errorf("hook made a network request: %s %s", r.Method, r.URL)+ return nil, errors.New("no network from hooks")+}++// shareAutoHookEnv points the runtime log, the active-session record and the share settings at a+// temp directory, and fails the test on any HTTP request made through the default transport.+func shareAutoHookEnv(t *testing.T, settings *shareauto.Settings) string {+ t.Helper()+ setupHookConfigDirs(t)+ platformFlag = "claude"+ t.Cleanup(func() { platformFlag = "claude" })+ dir := t.TempDir()+ logPath := filepath.Join(dir, "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_MODE", "1")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)+ t.Setenv(activesession.PathEnv, filepath.Join(dir, activesession.FileName))+ settingsPath := filepath.Join(dir, "share.json")+ t.Setenv(shareauto.PathEnv, settingsPath)+ if settings != nil {+ if err := shareauto.Save(settingsPath, *settings); err != nil {+ t.Fatal(err)+ }+ }+ prev := http.DefaultTransport+ http.DefaultTransport = failingTransport{t}+ t.Cleanup(func() { http.DefaultTransport = prev })+ return logPath+}++func runClaudeSessionHooks(t *testing.T, sessionID string) {+ t.Helper()+ runHookWithInput(t, runSessionStart, map[string]interface{}{+ "hook_event_name": "SessionStart", "session_id": sessionID, "cwd": "/work/project",+ })+ runHookWithInput(t, runPromptSubmit, map[string]interface{}{+ "hook_event_name": "UserPromptSubmit", "session_id": sessionID, "cwd": "/work/project", "prompt": "hello",+ })+ runHookWithInput(t, runPostTool, map[string]interface{}{+ "hook_event_name": "PostToolUse", "session_id": sessionID, "cwd": "/work/project",+ "tool_name": "Bash", "tool_input": map[string]interface{}{"command": "ls"}, "tool_response": map[string]interface{}{"stdout": "a"},+ })+}++func shareRequests(t *testing.T, logPath string) []map[string]interface{} {+ t.Helper()+ var out []map[string]interface{}+ for _, event := range endpointEvents(t, logPath) {+ if info, _ := event["event"].(map[string]interface{}); info["action"] == shareauto.ActionShareRequested {+ out = append(out, event)+ }+ }+ return out+}++func TestAutoShareWritesOneRequestPerSession(t *testing.T) {+ logPath := shareAutoHookEnv(t, &shareauto.Settings{Auto: shareauto.Auto{Enabled: true, Visibility: "private"}})+ runClaudeSessionHooks(t, "sess-a")+ runClaudeSessionHooks(t, "sess-a")+ runClaudeSessionHooks(t, "sess-b")++ requests := shareRequests(t, logPath)+ if len(requests) != 2 {+ t.Fatalf("share requests = %d, want one per session", len(requests))+ }+ first := requests[0]+ if got := first["session"].(map[string]interface{})["id"]; got != "sess-a" {+ t.Fatalf("session = %v", got)+ }+ if got := first["share"].(map[string]interface{})["visibility"]; got != "private" {+ t.Fatalf("share.visibility = %v", got)+ }+ info := first["event"].(map[string]interface{})+ if info["fidelity"] != "inferred" || info["category"] != "session" {+ t.Fatalf("event block = %v", info)+ }+ if got := first["harness"].(map[string]interface{})["name"]; got != "claude_code" {+ t.Fatalf("harness = %v", got)+ }+ // It follows the session's first event, which is SessionStart here.+ events := endpointEvents(t, logPath)+ if events[0]["event"].(map[string]interface{})["action"] != "session.started" || events[1]["event"].(map[string]interface{})["action"] != shareauto.ActionShareRequested {+ t.Fatalf("order: %v then %v", events[0]["event"], events[1]["event"])+ }+}++func TestAutoShareOffWritesNothing(t *testing.T) {+ logPath := shareAutoHookEnv(t, nil)+ runClaudeSessionHooks(t, "sess-a")+ if n := len(shareRequests(t, logPath)); n != 0 {+ t.Fatalf("share requests with auto-share off = %d", n)+ }+ logPath = shareAutoHookEnv(t, &shareauto.Settings{Auto: shareauto.Auto{Enabled: false}})+ runClaudeSessionHooks(t, "sess-c")+ if n := len(shareRequests(t, logPath)); n != 0 {+ t.Fatalf("share requests with auto-share disabled = %d", n)+ }+}++func TestAutoShareHonorsProjectOptOut(t *testing.T) {+ logPath := shareAutoHookEnv(t, &shareauto.Settings{+ Auto: shareauto.Auto{Enabled: true},+ Projects: []shareauto.Project{{Path: "/work/project", Enabled: false}},+ })+ runClaudeSessionHooks(t, "sess-a")+ if n := len(shareRequests(t, logPath)); n != 0 {+ t.Fatalf("share requests in an opted-out project = %d", n)+ }+}diff --git a/cli/beacon-hooks/internal/logging/logging.go b/cli/beacon-hooks/internal/logging/logging.goindex 1529db5a..16dc4501 100644--- a/cli/beacon-hooks/internal/logging/logging.go+++ b/cli/beacon-hooks/internal/logging/logging.go@@ -17,6 +17,7 @@ import ("github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve""github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/activesession""github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/shareauto")// endpointSequence numbers the endpoint events emitted by this hook process, in the order@@ -138,9 +139,58 @@ func (l *Logger) EndpointEventWithFidelity(action, category, severity, message,return err}recordActiveSession(event)+ l.requestShareOnce(event)return nil}+// requestShareOnce writes one session.share_requested event for the event's session when the person+// turned auto-share on for its working directory (`beacon share auto enable`). It is the first event+// of the session the hooks see -- SessionStart where the runtime has one -- and never more than one+// per session, deduplicated under a lock in the active-session record.+//+// The event is only written to the local runtime log. Beacon Cloud forwarding ships it like any+// other line, and beacon.sh publishes the session when it receives it; without forwarding it is an+// inert record. Nothing here touches the network. It is event.fidelity=inferred because Beacon+// originated it: no runtime reported a share request.+func (l *Logger) requestShareOnce(event map[string]interface{}) {+ info, _ := event["event"].(map[string]interface{})+ if action, _ := info["action"].(string); action == shareauto.ActionShareRequested {+ return+ }+ session, _ := event["session"].(map[string]interface{})+ harness, _ := event["harness"].(map[string]interface{})+ if session == nil || harness == nil {+ return+ }+ id, _ := session["id"].(string)+ dir, _ := session["working_directory"].(string)+ name, _ := harness["name"].(string)+ if id == "" || dir == "" || name == "" {+ return+ }+ decision := shareauto.ForHook(shareauto.DefaultPath(), dir)+ if !decision.Enabled {+ return+ }+ first, err := activesession.MarkShareRequested(activesession.DefaultPath(), name, id, time.Now())+ if err != nil || !first {+ return+ }+ fields := map[string]interface{}{+ "session": map[string]interface{}{"id": id, "working_directory": dir},+ }+ if visibility := decision.Visibility; visibility == "public" || visibility == "direct" || visibility == "private" {+ fields["share"] = map[string]interface{}{"visibility": visibility}+ }+ if repo, _ := event["repository"].(string); repo != "" {+ fields["repository"] = repo+ }+ if branch, _ := event["branch"].(string); branch != "" {+ fields["branch"] = branch+ }+ _ = l.EndpointEventWithFidelity(shareauto.ActionShareRequested, "session", "info", "Auto-share requested for this session", asymptoteobserve.FidelityInferred, fields)+}+// recordActiveSession notes the event's session as the one its runtime is running in its working// directory, for `beacon share --current`. It is a local file write and never fails the hook: the// record is a convenience, the event above is what matters. Nothing here touches the network.diff --git a/cli/beacon-hooks/internal/logging/main_test.go b/cli/beacon-hooks/internal/logging/main_test.goindex 3005f2f7..836e7a4a 100644--- a/cli/beacon-hooks/internal/logging/main_test.go+++ b/cli/beacon-hooks/internal/logging/main_test.go@@ -6,6 +6,7 @@ import ("testing""github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/activesession"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/shareauto")// TestMain keeps the active-session record every endpoint event updates out of the real home@@ -16,6 +17,8 @@ func TestMain(m *testing.M) {panic(err)}os.Setenv(activesession.PathEnv, filepath.Join(dir, activesession.FileName))+ // Auto-share is off unless a test turns it on in a settings file of its own.+ os.Setenv(shareauto.PathEnv, filepath.Join(dir, "share-settings.json"))code := m.Run()os.RemoveAll(dir)os.Exit(code)diff --git a/cli/beacon/cmd/share.go b/cli/beacon/cmd/share.goindex ea6f8469..4345c71d 100644--- a/cli/beacon/cmd/share.go+++ b/cli/beacon/cmd/share.go@@ -109,7 +109,8 @@ you; public lists the trace in Discover for anyone, and asks for confirmation fia session updates the same trace and keeps its visibility unless --visibility is given.Sharing needs ` + "`beacon login`" + ` (with the traces:write permission) or a Beacon API key in --key or-BEACON_API_KEY. Nothing is uploaded by hooks or in the background; only this command shares.`,+BEACON_API_KEY. Hooks never upload anything; ` + "`beacon share auto`" + ` asks Beacon Cloud to publish new sessions+from the events it already receives.`,Args: cobra.NoArgs,SilenceUsage: true,RunE: func(cmd *cobra.Command, args []string) error { return shareJSONErrors(cmd, runShare(cmd)) },diff --git a/cli/beacon/cmd/share_auto.go b/cli/beacon/cmd/share_auto.gonew file mode 100644index 00000000..bf5bcb77--- /dev/null+++ b/cli/beacon/cmd/share_auto.go@@ -0,0 +1,298 @@+package cmd++import (+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "path/filepath"+ "strings"++ "github.com/spf13/cobra"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/asymptote"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/managedprivacy"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/shareauto"+)++// `beacon share auto` turns auto-share on or off. Auto-share is server-side publishing: the hook+// adapter writes one local session.share_requested event per session, Beacon Cloud forwarding ships+// it with the rest of the runtime log, and beacon.sh creates the shared trace from the forwarded+// events and keeps it current. Hooks never upload anything, so on an endpoint that is not connected+// to Beacon Cloud the setting does nothing but write that event; enable says so.++// shareAutoCloud reports whether this endpoint forwards to Beacon Cloud (user or system mode) and+// with which privacy mode. A seam for tests.+var shareAutoCloud = func() (connected bool, privacyMode string) {+ for _, userMode := range []bool{true, false} {+ if !asymptote.Connected(userMode) {+ continue+ }+ mode := managedprivacy.Standard+ if enrollment, err := asymptote.LoadEnrollment(userMode); err == nil && enrollment.PrivacyMode != "" {+ if normalized, err := managedprivacy.Normalize(enrollment.PrivacyMode); err == nil {+ mode = normalized+ }+ }+ return true, mode+ }+ return false, ""+}++type shareAutoOptions struct {+ visibility string+ project string+ yes bool+ jsonOutput bool+}++var shareAutoOpts shareAutoOptions++var shareAutoCmd = &cobra.Command{+ Use: "auto",+ Short: "Publish new sessions automatically through Beacon Cloud",+ Long: `Turn auto-share on or off, for every session or for one project.++With auto-share on, Beacon's hooks write one session.share_requested event to the local runtime log+for each new session. Beacon Cloud forwarding ships it like every other event, and beacon.sh+publishes the session as a shared trace and keeps it current as the session goes on. Hooks never+upload anything themselves: on an endpoint that is not connected to Beacon Cloud nothing is+published, and in metadata-only privacy mode the trace has no prompts, answers or output.++--project DIR applies the choice to one project: it is recorded for you, and DIR/.beacon/share.json+records it in the repository. A project file can turn auto-share off by itself, but it turns it on+only for people who ran ` + "`beacon share auto enable --project`" + ` there, so a cloned repository can never+publish your sessions.`,+ Args: cobra.NoArgs,+}++var shareAutoEnableCmd = &cobra.Command{+ Use: "enable",+ Short: "Turn auto-share on",+ Args: cobra.NoArgs,+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error { return runShareAutoSet(cmd, true) },+}++var shareAutoDisableCmd = &cobra.Command{+ Use: "disable",+ Short: "Turn auto-share off",+ Args: cobra.NoArgs,+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error { return runShareAutoSet(cmd, false) },+}++var shareAutoStatusCmd = &cobra.Command{+ Use: "status",+ Short: "Show whether auto-share applies here",+ Args: cobra.NoArgs,+ SilenceUsage: true,+ RunE: runShareAutoStatus,+}++func init() {+ shareCmd.AddCommand(shareAutoCmd)+ shareAutoCmd.AddCommand(shareAutoEnableCmd, shareAutoDisableCmd, shareAutoStatusCmd)+ for _, c := range []*cobra.Command{shareAutoEnableCmd, shareAutoDisableCmd, shareAutoStatusCmd} {+ c.Flags().StringVar(&shareAutoOpts.project, "project", "", "Apply to this project directory instead of every session (status: check this directory)")+ c.Flags().BoolVar(&shareAutoOpts.jsonOutput, "json", false, "Print the result as JSON")+ }+ shareAutoEnableCmd.Flags().StringVar(&shareAutoOpts.visibility, "visibility", asymptoteobserve.ShareVisibilityDirect, "Visibility of auto-shared traces: direct (anyone with the link), private or public")+ shareAutoEnableCmd.Flags().BoolVar(&shareAutoOpts.yes, "yes", false, "Enable public auto-share without asking")+}++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"`+}++func runShareAutoSet(cmd *cobra.Command, enable bool) error {+ err := shareAutoSet(cmd, enable)+ if err != nil && shareAutoOpts.jsonOutput {+ _ = json.NewEncoder(cmd.OutOrStdout()).Encode(map[string]any{"ok": false, "error": err.Error()})+ }+ return err+}++func shareAutoSet(cmd *cobra.Command, enable bool) error {+ visibility := strings.ToLower(strings.TrimSpace(shareAutoOpts.visibility))+ if enable {+ if !asymptoteobserve.ValidShareVisibility(visibility) {+ return fmt.Errorf("--visibility must be public, direct or private, not %q", shareAutoOpts.visibility)+ }+ if visibility == asymptoteobserve.ShareVisibilityPublic && !shareAutoOpts.yes {+ if err := confirmPublicAutoShare(cmd.ErrOrStderr()); err != nil {+ return err+ }+ }+ } else {+ visibility = ""+ }+ path := shareauto.DefaultPath()+ if path == "" {+ return errors.New("cannot find the home directory for the auto-share setting")+ }+ settings, err := shareauto.Load(path)+ if err != nil {+ return fmt.Errorf("read %s: %w (fix or remove it, then retry)", path, err)+ }+ project := ""+ if strings.TrimSpace(shareAutoOpts.project) != "" {+ project, err = filepath.Abs(shareAutoOpts.project)+ if err != nil {+ return err+ }+ project = filepath.Clean(project)+ entry := shareauto.Project{Path: project, Enabled: enable, Visibility: visibility}+ replaced := false+ for i, p := range settings.Projects {+ if filepath.Clean(p.Path) == project {+ settings.Projects[i] = entry+ replaced = true+ }+ }+ if !replaced {+ settings.Projects = append(settings.Projects, entry)+ }+ } else {+ settings.Auto.Enabled = enable+ if enable {+ settings.Auto.Visibility = visibility+ }+ }+ if err := shareauto.Save(path, settings); err != nil {+ return err+ }+ if project != "" {+ if err := shareauto.SaveMarker(project, shareauto.Marker{Auto: shareauto.Auto{Enabled: enable, Visibility: visibility}}); err != nil {+ return fmt.Errorf("the setting was saved for you, but %s could not be written: %w", shareauto.MarkerPath(project), err)+ }+ }+ dir := project+ if dir == "" {+ dir, _ = filepath.Abs(".")+ }+ status := buildShareAutoStatus(path, settings, dir)+ return printShareAutoResult(cmd, status, enable, project)+}++func confirmPublicAutoShare(errOut io.Writer) error {+ if !shareIsTTY() || isCIEnvironment() {+ return errors.New("public auto-share lists every new session in Discover for anyone to find; pass --yes to enable it without a terminal to confirm")+ }+ fmt.Fprint(errOut, "Publish every new session publicly? Anyone can find and read them in Discover. [y/N] ")+ if !confirmNo(shareStdin) {+ return errors.New("auto-share not changed")+ }+ return nil+}++func buildShareAutoStatus(path string, settings shareauto.Settings, dir string) shareAutoStatus {+ decision := shareauto.Resolve(settings, dir)+ connected, mode := shareAutoCloud()+ status := shareAutoStatus{+ SettingsPath: path,+ Directory: dir,+ Enabled: decision.Enabled,+ Visibility: decision.Visibility,+ Source: decision.Source,+ Project: decision.Project,+ UntrustedMarker: decision.UntrustedMarker,+ UserEnabled: settings.Auto.Enabled,+ UserVisibility: settings.Auto.Visibility,+ CloudConnected: connected,+ CloudPrivacyMode: mode,+ }+ if status.Enabled && status.Visibility == "" {+ status.Visibility = asymptoteobserve.ShareVisibilityDirect+ }+ if status.Enabled || settings.Auto.Enabled {+ 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 {+ status.Warnings = append(status.Warnings, "Beacon Cloud forwarding is in metadata-only mode, so auto-shared traces have no prompts, answers, reasoning or tool output; reconnect in standard mode, or use `beacon share` for a full trace")+ }+ }+ if status.UntrustedMarker != "" && status.Source != "project" {+ status.Warnings = append(status.Warnings, fmt.Sprintf("%s asks for auto-share, which applies only after you run `beacon share auto enable --project %s`", shareauto.MarkerPath(status.UntrustedMarker), status.UntrustedMarker))+ }+ return status+}++func printShareAutoResult(cmd *cobra.Command, status shareAutoStatus, enable bool, project string) error {+ out := cmd.OutOrStdout()+ if shareAutoOpts.jsonOutput {+ return json.NewEncoder(out).Encode(map[string]any{"ok": true, "data": status})+ }+ scope := "every new session"+ if project != "" {+ scope = "new sessions in " + project+ }+ if 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.")+ } else {+ fmt.Fprintf(out, "Auto-share is off for %s. Traces already published stay published; delete them on beacon.sh.\n", scope)+ }+ if project != "" {+ fmt.Fprintf(out, "Recorded in %s and %s.\n", status.SettingsPath, shareauto.MarkerPath(project))+ }+ for _, w := range status.Warnings {+ fmt.Fprintf(cmd.ErrOrStderr(), "warning: %s\n", w)+ }+ return nil+}++func runShareAutoStatus(cmd *cobra.Command, args []string) error {+ path := shareauto.DefaultPath()+ settings, err := shareauto.Load(path)+ if err != nil {+ return fmt.Errorf("read %s: %w", path, err)+ }+ dir := strings.TrimSpace(shareAutoOpts.project)+ if dir == "" {+ dir = "."+ }+ if dir, err = filepath.Abs(dir); err != nil {+ return err+ }+ status := buildShareAutoStatus(path, settings, dir)+ out := cmd.OutOrStdout()+ if shareAutoOpts.jsonOutput {+ return json.NewEncoder(out).Encode(map[string]any{"ok": true, "data": status})+ }+ state := "off"+ if status.Enabled {+ state = "on (" + status.Visibility + ")"+ }+ fmt.Fprintf(out, "Auto-share in %s: %s\n", status.Directory, state)+ switch status.Source {+ case "project":+ fmt.Fprintf(out, " decided by your setting for the project %s\n", status.Project)+ 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")+ }+ cloud := "not connected"+ if status.CloudConnected {+ cloud = "connected (" + managedprivacy.Label(status.CloudPrivacyMode) + ")"+ }+ fmt.Fprintf(out, "Beacon Cloud forwarding: %s\n", cloud)+ fmt.Fprintf(out, "Settings: %s\n", status.SettingsPath)+ for _, w := range status.Warnings {+ fmt.Fprintf(out, "warning: %s\n", w)+ }+ return nil+}diff --git a/cli/beacon/cmd/share_auto_test.go b/cli/beacon/cmd/share_auto_test.gonew file mode 100644index 00000000..c9c41606--- /dev/null+++ b/cli/beacon/cmd/share_auto_test.go@@ -0,0 +1,138 @@+package cmd++import (+ "bytes"+ "encoding/json"+ "path/filepath"+ "strings"+ "testing"++ "github.com/spf13/pflag"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/managedprivacy"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/shareauto"+)++func runShareAuto(t *testing.T, args ...string) (string, string, error) {+ t.Helper()+ shareAutoOpts = shareAutoOptions{}+ for _, c := range []*pflag.FlagSet{shareAutoEnableCmd.Flags(), shareAutoDisableCmd.Flags(), shareAutoStatusCmd.Flags()} {+ c.VisitAll(func(f *pflag.Flag) { _ = f.Value.Set(f.DefValue); f.Changed = false })+ }+ var stdout, stderr bytes.Buffer+ rootCmd.SetOut(&stdout)+ rootCmd.SetErr(&stderr)+ rootCmd.SetArgs(append([]string{"share", "auto"}, args...))+ t.Cleanup(func() { rootCmd.SetOut(nil); rootCmd.SetErr(nil); rootCmd.SetArgs(nil) })+ err := rootCmd.Execute()+ return stdout.String(), stderr.String(), err+}++func shareAutoTestEnv(t *testing.T, connected bool, mode string) string {+ t.Helper()+ env := newShareEnv(t)+ path := filepath.Join(env.home, ".beacon", "endpoint", shareauto.FileName)+ t.Setenv(shareauto.PathEnv, path)+ prev := shareAutoCloud+ shareAutoCloud = func() (bool, string) { return connected, mode }+ t.Cleanup(func() { shareAutoCloud = prev })+ return path+}++func TestShareAutoEnableAndDisable(t *testing.T) {+ path := shareAutoTestEnv(t, true, managedprivacy.Standard)+ stdout, stderr, err := runShareAuto(t, "enable", "--visibility", "private")+ if err != nil {+ t.Fatalf("enable: %v", err)+ }+ if !strings.Contains(stdout, "Auto-share is on for every new session (private)") || stderr != "" {+ t.Fatalf("stdout=%q stderr=%q", stdout, stderr)+ }+ settings, _ := shareauto.Load(path)+ if !settings.Auto.Enabled || settings.Auto.Visibility != "private" {+ t.Fatalf("settings = %+v", settings)+ }+ if _, _, err := runShareAuto(t, "disable"); err != nil {+ t.Fatalf("disable: %v", err)+ }+ settings, _ = shareauto.Load(path)+ if settings.Auto.Enabled {+ t.Fatalf("still enabled: %+v", settings)+ }+}++func TestShareAutoWarnsWithoutCloudOrContent(t *testing.T) {+ shareAutoTestEnv(t, false, "")+ _, stderr, err := runShareAuto(t, "enable")+ if err != nil || !strings.Contains(stderr, "not connected to Beacon Cloud") {+ t.Fatalf("not connected: err=%v stderr=%q", err, stderr)+ }+ shareAutoTestEnv(t, true, managedprivacy.MetadataOnly)+ _, stderr, err = runShareAuto(t, "enable")+ if err != nil || !strings.Contains(stderr, "metadata-only") {+ t.Fatalf("metadata-only: err=%v stderr=%q", err, stderr)+ }+}++func TestShareAutoPublicNeedsYesWithoutATerminal(t *testing.T) {+ path := shareAutoTestEnv(t, true, managedprivacy.Standard)+ if _, _, err := runShareAuto(t, "enable", "--visibility", "public"); err == nil || !strings.Contains(err.Error(), "--yes") {+ t.Fatalf("public without --yes: %v", err)+ }+ if settings, _ := shareauto.Load(path); settings.Auto.Enabled {+ t.Fatal("refused public enable still wrote the setting")+ }+ if _, _, err := runShareAuto(t, "enable", "--visibility", "public", "--yes"); err != nil {+ t.Fatalf("public --yes: %v", err)+ }+ if _, _, err := runShareAuto(t, "enable", "--visibility", "everyone"); err == nil {+ t.Fatal("bad visibility accepted")+ }+}++func TestShareAutoProjectScopeAndStatus(t *testing.T) {+ path := shareAutoTestEnv(t, true, managedprivacy.Standard)+ project := t.TempDir()+ if _, _, err := runShareAuto(t, "enable", "--project", project); err != nil {+ t.Fatalf("enable --project: %v", err)+ }+ settings, _ := shareauto.Load(path)+ if entry, ok := settings.Project(project); !ok || !entry.Enabled || entry.Visibility != "direct" || settings.Auto.Enabled {+ t.Fatalf("settings = %+v", settings)+ }+ if marker, ok := shareauto.LoadMarker(project); !ok || !marker.Auto.Enabled {+ t.Fatalf("marker = %+v %v", marker, ok)+ }+ stdout, _, err := runShareAuto(t, "status", "--project", filepath.Join(project), "--json")+ if err != nil {+ t.Fatalf("status: %v", err)+ }+ var doc struct {+ OK bool `json:"ok"`+ Data shareAutoStatus `json:"data"`+ }+ if err := json.Unmarshal([]byte(stdout), &doc); err != nil || !doc.Data.Enabled || doc.Data.Source != "project" || !doc.Data.CloudConnected {+ t.Fatalf("status = %s (%v)", stdout, err)+ }++ // Someone else's clone: the marker alone does not enable anything, and status says why.+ other := t.TempDir()+ if err := shareauto.SaveMarker(other, shareauto.Marker{Auto: shareauto.Auto{Enabled: true, Visibility: "public"}}); err != nil {+ t.Fatal(err)+ }+ stdout, _, err = runShareAuto(t, "status", "--project", other)+ if err != nil || !strings.Contains(stdout, "Auto-share in "+other+": off") || !strings.Contains(stdout, "applies only after you run") {+ t.Fatalf("untrusted status = %q (%v)", stdout, err)+ }++ if _, _, err := runShareAuto(t, "disable", "--project", project); err != nil {+ t.Fatalf("disable --project: %v", err)+ }+ settings, _ = shareauto.Load(path)+ if entry, _ := settings.Project(project); entry.Enabled {+ t.Fatalf("project still enabled: %+v", settings)+ }+ if marker, _ := shareauto.LoadMarker(project); marker.Auto.Enabled {+ t.Fatal("marker still enabled")+ }+}diff --git a/cli/beacon/internal/endpoint/schema/event.go b/cli/beacon/internal/endpoint/schema/event.goindex 6a980cac..82a34cc5 100644--- a/cli/beacon/internal/endpoint/schema/event.go+++ b/cli/beacon/internal/endpoint/schema/event.go@@ -91,6 +91,7 @@ type MCPResourceInfo = asymptoteobserve.MCPResourceInfotype MCPSessionInfo = asymptoteobserve.MCPSessionInfotype ApprovalInfo = asymptoteobserve.ApprovalInfotype HandoffInfo = asymptoteobserve.HandoffInfo+type ShareInfo = asymptoteobserve.ShareInfotype VCSInfo = asymptoteobserve.VCSInfotype VCSRefInfo = asymptoteobserve.VCSRefInfotype VCSRefHeadInfo = asymptoteobserve.VCSRefHeadInfodiff --git a/cli/beacon/internal/handoff/runtimelog.go b/cli/beacon/internal/handoff/runtimelog.goindex a5768ebb..40f04501 100644--- a/cli/beacon/internal/handoff/runtimelog.go+++ b/cli/beacon/internal/handoff/runtimelog.go@@ -91,7 +91,7 @@ func logSessionForPrefix(logPath, prefix, harness string) (string, error) {// after the fact (sharing it, linking it to a commit). Those are stamped when Beacon wrote them, so// counting them would move an old session to the top of "most recent" the moment it is shared.func beaconBookkeeping(action string) bool {- return action == "session.shared" || action == "session.commit_linked"+ return action == "session.shared" || action == "session.share_requested" || action == "session.commit_linked"}// LogSessions lists the sessions in Beacon's runtime log, newest first, narrowed by filter the waydiff --git a/docs/cli/share.mdx b/docs/cli/share.mdxindex 748a9d93..fcbb419c 100644--- a/docs/cli/share.mdx+++ b/docs/cli/share.mdx@@ -11,6 +11,9 @@ description: "Share a local agent session as a trace on beacon.sh"beacon share [--current | --session <id> | --source-path <path> | --cwd <dir>] [flags]beacon share --list [--cwd <dir>] [--harness <runtime>]beacon share refresh [<external-id> | <session-id>] [flags]+beacon share auto enable [--visibility direct|private|public] [--project <dir>] [--yes]+beacon share auto disable [--project <dir>]+beacon share auto status [--project <dir>]```Without a session flag, `beacon share` shares the session it runs inside (see [Sharing this session](#sharing-this-session)), and otherwise the most recent session that ran in the current directory. It names the session it picked before uploading anything.@@ -27,7 +30,7 @@ beacon share --current --harness claude_code --jsonbeacon share --print```-Sharing is always something you ask for. Hooks, plugins and background jobs never share a session, and nothing else in Beacon uploads session content to beacon.sh except [Beacon Cloud forwarding](/cli/endpoint-connect) when you connect an endpoint.+Sharing is always something you ask for. Hooks, plugins and background jobs never upload a session, and nothing else in Beacon uploads session content to beacon.sh except [Beacon Cloud forwarding](/cli/endpoint-connect) when you connect an endpoint. [Auto-share](#auto-share), which you turn on, asks Beacon Cloud to publish sessions from the events forwarding already sends.## Choosing the session@@ -114,6 +117,27 @@ beacon share refresh 5f0c1d2ebeacon share refresh # this session, found like --current```+## Auto-share++`beacon share auto enable` publishes new sessions without running `beacon share` each time. It works through [Beacon Cloud forwarding](/cli/endpoint-connect), never from the hooks over the network:++1. On the first event Beacon's hooks see for a session (its `SessionStart` where the runtime has one), they write one `session.share_requested` event to the local runtime log, with the session id, runtime and the chosen visibility in `share.visibility`. One per session: the hooks remember which sessions they requested in `~/.beacon/endpoint/active-sessions.json`.+2. Forwarding ships that line with the rest of the runtime log.+3. beacon.sh creates the shared trace from the session's forwarded events and keeps it current as more arrive. Its external id is the one `beacon share` uses (`<runtime>:<session-id>`), so a session shared both ways is one trace.++```bash+beacon share auto enable # every new session, direct (link only)+beacon share auto enable --project . # only sessions in this repository+beacon share auto status+beacon 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.++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 `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.+## Credentials`beacon share` uses, in this order:diff --git a/docs/telemetry-schema/fields.mdx b/docs/telemetry-schema/fields.mdxindex 1ffa5f29..54a41248 100644--- a/docs/telemetry-schema/fields.mdx+++ b/docs/telemetry-schema/fields.mdx@@ -28,6 +28,7 @@ Beacon models each event as an action plus a set of typed entities. The [`event`| `mcp` | MCP server, tool, method, protocol, resource, and session context | `server`, `tool`, `method.name`, `protocol.version`, `resource.uri`, `session.id` || `approval` | Approval or policy decision context | `required`, `decision`, `reason` || `handoff` | On a `session.handoff` event, the session this one continues from a [handoff brief](/cli/handoff#linking-a-new-session-to-the-one-it-continues) | `source_harness`, `source_session_id` |+| `share` | On a `session.share_requested` event, the visibility [auto-share](/cli/share#auto-share) asks beacon.sh to publish the session with | `visibility` (`direct`, `private`, `public`) || `policy` | Policy metadata when available from a runtime or integration | `id`, `name`, `decision`, `enforcement`, `reason` || `prompt` | Prompt text when the source emits it and content handling allows it | `text` || `system_context` | On a `session.context` event, what the runtime gave the model outside the conversation. Metadata, so it is kept when content is not; the text is in `gen_ai.system_instructions` | `kind` (`skill_listing`), `source` (`system_prompt`, `transcript`), `skills[].skill_name`, `skills[].skill_name_hash` |@@ -77,6 +78,7 @@ Optional context fields add detail when available:| `jsonrpc`, `rpc`, `network`, `server`, `error` | MCP client-span context projected from OpenTelemetry semantic conventions when available || `approval` | Approval requirement, decision, or reason || `handoff` | The session a handed-off session continues: source harness and session id |+| `share` | Auto-share request visibility || `policy` | Policy ID, name, decision, enforcement mode, or reason || `content` | Content inclusion, redaction, and truncation state || `gen_ai` | OpenTelemetry GenAI request, response, usage, message, tool, retrieval, evaluation, provider, and workflow metadata |diff --git a/pkg/asymptoteobserve/activesession/activesession.go b/pkg/asymptoteobserve/activesession/activesession.goindex 99e7b02c..07c2bf83 100644--- a/pkg/asymptoteobserve/activesession/activesession.go+++ b/pkg/asymptoteobserve/activesession/activesession.go@@ -35,6 +35,8 @@ const (MaxAge = 14 * 24 * time.Hour// RefreshInterval is how stale an unchanged entry's timestamp may get before it is rewritten.RefreshInterval = time.Minute+ // MaxRequested bounds the share-request dedupe list; the oldest marks go first.+ MaxRequested = 1024schemaVersion = "beacon.active_sessions.v1")@@ -47,9 +49,17 @@ type Entry struct {LastSeen time.Time `json:"last_seen"`}+// Requested marks a session the hook adapter already wrote a session.share_requested event for.+type Requested struct {+ Harness string `json:"harness"`+ SessionID string `json:"session_id"`+ At time.Time `json:"at"`+}+type document struct {- SchemaVersion string `json:"schema_version"`- Sessions []Entry `json:"sessions"`+ SchemaVersion string `json:"schema_version"`+ Sessions []Entry `json:"sessions"`+ ShareRequested []Requested `json:"share_requested,omitempty"`}// DefaultPath is BEACON_ACTIVE_SESSIONS_FILE, or ~/.beacon/endpoint/active-sessions.json.@@ -134,6 +144,32 @@ func Record(path, harness, session, dir string, now time.Time) error {})}+// MarkShareRequested records that a share request was written for the session and reports whether+// this call was the first to do so. The check and the mark happen under one lock, so two hooks of+// one session racing each other write one request between them. Marks are kept four times as long+// as active entries (MaxAge) and at most MaxRequested of them.+func MarkShareRequested(path, harness, session string, now time.Time) (bool, error) {+ harness, session = strings.TrimSpace(harness), strings.TrimSpace(session)+ if path == "" || harness == "" || session == "" {+ return false, nil+ }+ first := false+ err := update(path, now, func(doc *document) bool {+ for _, r := range doc.ShareRequested {+ if r.Harness == harness && r.SessionID == session {+ return false+ }+ }+ doc.ShareRequested = append(doc.ShareRequested, Requested{Harness: harness, SessionID: session, At: now.UTC()})+ first = true+ return true+ })+ if err != nil {+ return false, err+ }+ return first, nil+}+func load(path string) (document, error) {doc := document{SchemaVersion: schemaVersion}if path == "" {@@ -226,5 +262,19 @@ func prune(doc *document, now time.Time) bool {doc.Sessions = doc.Sessions[:MaxEntries]changed = true}+ keptReq := doc.ShareRequested[:0]+ for _, r := range doc.ShareRequested {+ if now.Sub(r.At) <= 4*MaxAge {+ keptReq = append(keptReq, r)+ } else {+ changed = true+ }+ }+ doc.ShareRequested = keptReq+ if len(doc.ShareRequested) > MaxRequested {+ sort.SliceStable(doc.ShareRequested, func(i, j int) bool { return doc.ShareRequested[i].At.After(doc.ShareRequested[j].At) })+ doc.ShareRequested = doc.ShareRequested[:MaxRequested]+ changed = true+ }return changed}diff --git a/pkg/asymptoteobserve/activesession/activesession_test.go b/pkg/asymptoteobserve/activesession/activesession_test.goindex 666fb3e1..d505b3a1 100644--- a/pkg/asymptoteobserve/activesession/activesession_test.go+++ b/pkg/asymptoteobserve/activesession/activesession_test.go@@ -123,3 +123,27 @@ func TestDamagedRecordIsReplaced(t *testing.T) {t.Fatalf("doc = %s", data)}}++func TestMarkShareRequestedOncePerSession(t *testing.T) {+ path := filepath.Join(t.TempDir(), FileName)+ now := time.Date(2026, 10, 1, 12, 0, 0, 0, time.UTC)+ first, err := MarkShareRequested(path, "claude_code", "s1", now)+ if err != nil || !first {+ t.Fatalf("first = %v, %v", first, err)+ }+ again, err := MarkShareRequested(path, "claude_code", "s1", now.Add(time.Hour))+ if err != nil || again {+ t.Fatalf("again = %v, %v", again, err)+ }+ other, _ := MarkShareRequested(path, "codex_cli", "s1", now)+ if !other {+ t.Fatal("another runtime's session with the same id was deduplicated")+ }+ // Active-session writes keep the marks.+ if err := Record(path, "claude_code", "s1", "/d", now); err != nil {+ t.Fatal(err)+ }+ if again, _ := MarkShareRequested(path, "claude_code", "s1", now); again {+ t.Fatal("mark lost after a Record")+ }+}diff --git a/pkg/asymptoteobserve/event.go b/pkg/asymptoteobserve/event.goindex 6236564e..fdfddac8 100644--- a/pkg/asymptoteobserve/event.go+++ b/pkg/asymptoteobserve/event.go@@ -647,6 +647,7 @@ type Event struct {Run *RunInfo `json:"run,omitempty"`Session *SessionInfo `json:"session,omitempty"`Handoff *HandoffInfo `json:"handoff,omitempty"`+ Share *ShareInfo `json:"share,omitempty"`Trace *TraceInfo `json:"trace,omitempty"`JSONRPC *JSONRPCInfo `json:"jsonrpc,omitempty"`Network *NetworkInfo `json:"network,omitempty"`diff --git a/pkg/asymptoteobserve/share.go b/pkg/asymptoteobserve/share.goindex bba9f6a5..0c87eef5 100644--- a/pkg/asymptoteobserve/share.go+++ b/pkg/asymptoteobserve/share.go@@ -21,6 +21,14 @@ import (// relative to the session's directory or the home directory, and Beacon's own bookkeeping events// (heartbeats, metric datapoints, the session.shared record itself) are left out.+// ShareInfo is the sharing request an event carries. Today only session.share_requested sets it:+// the hook adapter writes that event once per session when auto-share is on, and Beacon Cloud,+// receiving it through forwarding, publishes the session as a shared trace with this visibility+// ("" means the server default, direct).+type ShareInfo struct {+ Visibility string `json:"visibility,omitempty"`+}+// ShareSchemaVersion names the wire contract.const ShareSchemaVersion = "beacon.share.v1"@@ -538,7 +546,7 @@ func classifyShareEvent(event Event) shareEventClass {action := strings.ToLower(strings.TrimSpace(event.Event.Action))category := strings.ToLower(strings.TrimSpace(event.Event.Category))switch {- case action == "" || action == "session.shared":+ case action == "" || action == "session.shared" || action == "session.share_requested":return shareSkipcase category == "metric" || category == "inventory" || category == "health" || category == "telemetry" ||strings.HasPrefix(action, "endpoint.") || strings.HasPrefix(action, "telemetry.") ||@@ -1325,7 +1333,7 @@ func ShareMetadataFromEventsWithOptions(events []Event, opts ShareOptions) Shareseen := map[string]bool{}for _, item := range items {event := item.event- if strings.EqualFold(event.Event.Action, "session.shared") {+ if strings.EqualFold(event.Event.Action, "session.shared") || strings.EqualFold(event.Event.Action, "session.share_requested") {continue}if meta.AgentID == "" {diff --git a/pkg/asymptoteobserve/shareauto/shareauto.go b/pkg/asymptoteobserve/shareauto/shareauto.gonew file mode 100644index 00000000..5ce79f0a--- /dev/null+++ b/pkg/asymptoteobserve/shareauto/shareauto.go@@ -0,0 +1,240 @@+// Package shareauto holds the auto-share setting: whether the hook adapter records one+// session.share_requested event per session, which Beacon Cloud forwarding ships to beacon.sh and+// beacon.sh turns into a shared trace that it keeps refreshing as more of the session arrives.+//+// The hooks never publish anything themselves and never touch the network: they only write that+// local event, and only when the person turned the setting on with `beacon share auto enable`.+//+// Two files hold the setting:+//+// - The user file, ~/.beacon/endpoint/share.json (0600 under 0700), written only by the CLI. It+// has the user-wide switch and the projects the user opted in or out of, by absolute path.+// - A project marker, <project>/.beacon/share.json, which `--project` writes so a repository can+// record its choice. A marker can turn auto-share off for its project on its own. It can turn it+// on only for someone whose user file trusts that project: a marker arrives with a clone, and a+// repository must never be able to publish the sessions of whoever opens it. The visibility of+// a trusted project always comes from the user file, never from the marker.+package shareauto++import (+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "strings"+)++const (+ // FileName is the user file's name under the endpoint base directory, and the marker's name+ // under a project's .beacon directory.+ FileName = "share.json"+ // MarkerDir is the project directory that holds the marker.+ MarkerDir = ".beacon"+ // PathEnv overrides where the user file lives (tests, unusual homes).+ PathEnv = "BEACON_SHARE_SETTINGS_FILE"+ // SchemaVersion is written into both files.+ SchemaVersion = "beacon.share_settings.v1"++ // ActionShareRequested is the event the hook adapter writes once per session when auto-share+ // applies to it.+ ActionShareRequested = "session.share_requested"++ // maxWalk bounds how many directories are searched above a working directory for a project.+ maxWalk = 64+)++// Auto is one auto-share switch and the visibility it shares with ("" means the server default,+// direct).+type Auto struct {+ Enabled bool `json:"enabled"`+ Visibility string `json:"visibility,omitempty"`+}++// Project is the user's choice for one project directory.+type Project struct {+ Path string `json:"path"`+ Enabled bool `json:"enabled"`+ Visibility string `json:"visibility,omitempty"`+}++// Settings is the user file.+type Settings struct {+ SchemaVersion string `json:"schema_version"`+ Auto Auto `json:"auto"`+ Projects []Project `json:"projects,omitempty"`+}++// Marker is a project's .beacon/share.json.+type Marker struct {+ SchemaVersion string `json:"schema_version"`+ Auto Auto `json:"auto"`+}++// Decision is what applies to one working directory.+type Decision struct {+ Enabled bool+ Visibility 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 string+ // Project is the project directory the decision came from, when it came from one.+ Project string+ // UntrustedMarker is a marker that asks for auto-share in a project the user has not opted in.+ UntrustedMarker string+}++// DefaultPath is BEACON_SHARE_SETTINGS_FILE, or ~/.beacon/endpoint/share.json.+func DefaultPath() string {+ if p := strings.TrimSpace(os.Getenv(PathEnv)); p != "" {+ return p+ }+ home, err := os.UserHomeDir()+ if err != nil || home == "" {+ return ""+ }+ return filepath.Join(home, ".beacon", "endpoint", FileName)+}++// MarkerPath is dir's project marker.+func MarkerPath(dir string) string { return filepath.Join(dir, MarkerDir, FileName) }++// Load reads the user file. A missing file is an empty Settings and no error.+func Load(path string) (Settings, error) {+ s := Settings{SchemaVersion: SchemaVersion}+ if path == "" {+ return s, nil+ }+ data, err := os.ReadFile(path)+ if err != nil {+ if errors.Is(err, os.ErrNotExist) {+ return s, nil+ }+ return s, err+ }+ if err := json.Unmarshal(data, &s); err != nil {+ return Settings{SchemaVersion: SchemaVersion}, err+ }+ s.SchemaVersion = SchemaVersion+ return s, nil+}++// LoadMarker reads dir's project marker; ok is false when there is none or it cannot be read.+func LoadMarker(dir string) (Marker, bool) {+ data, err := os.ReadFile(MarkerPath(dir))+ if err != nil {+ return Marker{}, false+ }+ var m Marker+ if err := json.Unmarshal(data, &m); err != nil {+ return Marker{}, false+ }+ return m, true+}++// 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 {+ return true+ }+ for _, p := range s.Projects {+ if p.Enabled {+ return true+ }+ }+ return false+}++// Project returns the user's entry for dir.+func (s Settings) Project(dir string) (Project, bool) {+ dir = filepath.Clean(dir)+ for _, p := range s.Projects {+ if filepath.Clean(p.Path) == dir {+ return p, true+ }+ }+ 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.+func Resolve(s Settings, workDir string) Decision {+ var d Decision+ dir := filepath.Clean(workDir)+ if workDir != "" && filepath.IsAbs(dir) {+ for i := 0; i < maxWalk; i++ {+ if p, ok := s.Project(dir); ok {+ return Decision{Enabled: p.Enabled, Visibility: p.Visibility, Source: "project", Project: dir}+ }+ if m, ok := LoadMarker(dir); ok {+ if !m.Auto.Enabled {+ return Decision{Source: "marker", Project: dir}+ }+ if d.UntrustedMarker == "" {+ d.UntrustedMarker = dir+ }+ }+ parent := filepath.Dir(dir)+ if parent == dir {+ break+ }+ dir = parent+ }+ }+ if s.Auto.Enabled {+ d.Enabled, d.Visibility, d.Source = true, s.Auto.Visibility, "user"+ }+ return d+}++// ForHook is Resolve for the hook path: it reads the user file and returns a disabled decision at+// the cost of one failed read when nothing could enable auto-share.+func ForHook(path, workDir string) Decision {+ s, err := Load(path)+ if err != nil || !s.anyEnabled() {+ return Decision{}+ }+ return Resolve(s, workDir)+}++// Save writes the user file atomically, 0600 under a 0700 directory.+func Save(path string, s Settings) error {+ s.SchemaVersion = SchemaVersion+ return writeJSON(path, s, 0o700, 0o600)+}++// SaveMarker writes dir's project marker. It is meant to be committed, so it is an ordinary file.+func SaveMarker(dir string, m Marker) error {+ m.SchemaVersion = SchemaVersion+ return writeJSON(MarkerPath(dir), m, 0o755, 0o644)+}++func writeJSON(path string, v any, dirMode, fileMode os.FileMode) error {+ data, err := json.MarshalIndent(v, "", " ")+ if err != nil {+ return err+ }+ dir := filepath.Dir(path)+ if err := os.MkdirAll(dir, dirMode); err != nil {+ return err+ }+ tmp, err := os.CreateTemp(dir, "."+FileName+".*.tmp")+ if err != nil {+ return err+ }+ name := tmp.Name()+ defer os.Remove(name)+ if err := tmp.Chmod(fileMode); err != nil {+ tmp.Close()+ return err+ }+ if _, err := tmp.Write(append(data, '\n')); err != nil {+ tmp.Close()+ return err+ }+ if err := tmp.Close(); err != nil {+ return err+ }+ return os.Rename(name, path)+}diff --git a/pkg/asymptoteobserve/shareauto/shareauto_test.go b/pkg/asymptoteobserve/shareauto/shareauto_test.gonew file mode 100644index 00000000..4b3f0d5b--- /dev/null+++ b/pkg/asymptoteobserve/shareauto/shareauto_test.go@@ -0,0 +1,74 @@+package shareauto++import (+ "os"+ "path/filepath"+ "testing"+)++func TestResolve(t *testing.T) {+ root := t.TempDir()+ repo := filepath.Join(root, "repo")+ sub := filepath.Join(repo, "pkg", "x")+ if err := os.MkdirAll(sub, 0o755); err != nil {+ t.Fatal(err)+ }+ if d := Resolve(Settings{}, sub); d.Enabled || d.Source != "" {+ t.Fatalf("empty = %+v", d)+ }+ user := Settings{Auto: Auto{Enabled: true, Visibility: "private"}}+ if d := Resolve(user, sub); !d.Enabled || d.Visibility != "private" || d.Source != "user" {+ t.Fatalf("user = %+v", d)+ }+ // A marker turning it off wins on its own.+ if err := SaveMarker(repo, Marker{Auto: Auto{Enabled: false}}); err != nil {+ t.Fatal(err)+ }+ if d := Resolve(user, sub); d.Enabled || d.Source != "marker" || d.Project != repo {+ t.Fatalf("marker off = %+v", d)+ }+ // A marker asking for public auto-share does nothing without the user's trust.+ if err := SaveMarker(repo, Marker{Auto: Auto{Enabled: true, Visibility: "public"}}); err != nil {+ t.Fatal(err)+ }+ if d := Resolve(Settings{}, sub); d.Enabled || d.UntrustedMarker != repo {+ t.Fatalf("untrusted marker = %+v", d)+ }+ if d := Resolve(user, sub); d.Visibility != "private" || d.Source != "user" {+ t.Fatalf("untrusted marker overrode the user visibility: %+v", d)+ }+ // The user's project entry decides, with its own visibility.+ trusted := Settings{Projects: []Project{{Path: repo, Enabled: true, Visibility: "direct"}}}+ if d := Resolve(trusted, sub); !d.Enabled || d.Visibility != "direct" || d.Source != "project" {+ t.Fatalf("trusted = %+v", d)+ }+ optOut := Settings{Auto: Auto{Enabled: true}, Projects: []Project{{Path: repo, Enabled: false}}}+ if d := Resolve(optOut, sub); d.Enabled {+ t.Fatalf("project opt-out = %+v", d)+ }+ if d := Resolve(trusted, root); d.Enabled {+ t.Fatalf("outside the project = %+v", d)+ }+}++func TestForHookAndSave(t *testing.T) {+ path := filepath.Join(t.TempDir(), "endpoint", FileName)+ if d := ForHook(path, "/x"); d.Enabled {+ t.Fatal("missing file enabled")+ }+ if err := Save(path, Settings{Auto: Auto{Enabled: true, Visibility: "direct"}}); err != nil {+ t.Fatal(err)+ }+ if d := ForHook(path, "/x"); !d.Enabled || d.Visibility != "direct" {+ t.Fatalf("ForHook = %+v", d)+ }+ if info, err := os.Stat(path); err == nil && os.PathSeparator == '/' && info.Mode().Perm() != 0o600 {+ t.Fatalf("mode = %v", info.Mode())+ }+ if err := os.WriteFile(path, []byte("{bad"), 0o600); err != nil {+ t.Fatal(err)+ }+ if d := ForHook(path, "/x"); d.Enabled {+ t.Fatal("damaged file enabled")+ }+}diff --git a/spec/threat-rules/FIELDS.md b/spec/threat-rules/FIELDS.mdindex 5848053f..9eb912f1 100644--- a/spec/threat-rules/FIELDS.md+++ b/spec/threat-rules/FIELDS.md@@ -144,6 +144,7 @@ Regenerate with `beacon rules fields --markdown > spec/threat-rules/FIELDS.md`.| `e.session.id` | string || `e.session.working_directory` | string || `e.severity` | string |+| `e.share.visibility` | string || `e.system_context.kind` | string || `e.system_context.skills` | list(asymptoteobserve.SkillRefInfo) || `e.system_context.source` | string |