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
Merge the trace.v1 share contract into share --follow
Claudef68941b116e4
diff --cc CLAUDE.mdindex dcce2146,f562ab25..2c50f49d--- a/CLAUDE.md+++ b/CLAUDE.md@@@ -69,8 -69,8 +69,8 @@@ 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`. 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. A note line may carry the session's share URL as its first trailing field (`beacon:<harness>/<id> <url>`; an identifier, not content): `gitlink.ValidShareURL` admits only https URLs on beacon.sh or the configured Beacon host (`AllowShareHost`, fed by `gitAllowShareHosts`), on write and on read, and `MergeNote`/`ParseNote` prefer the line with the URL over the bare one. Post-commit and `link` take URLs only from local `session.shared` events (`localShareURLs`). `setup --share-sessions [--share-visibility]` (implies `--share-notes`; stored as `beacon.shareSessions`/`beacon.shareVisibility` in local git config; public needs confirmation or `--yes`) makes the pre-push hook, which now receives git's stdin, share sessions linked to pushed commits that have no URL (at most 100 commits/10 sessions, inside the 10 s budget less 3 s kept for the notes push, silent without credentials, never failing the push) through `shareUpload` (`cmd/share_upload.go`: `alignShareSource` + `messagesAfter`), then write the URLs into the notes before pushing them. `beacon share --follow [--interval]` (`cmd/share_follow.go`) polls the session locally, uploads through `shareUpload` only when the projected messages' fingerprint changed, stops at `session.ended` or Ctrl+C (`shareFollowWait`/`shareFollowSignals` are the test seams), and records `session.shared` once at the start and once at the end; `docs/cli/share.mdx` carries the API-key CI walkthrough with GitHub Actions and GitLab CI examples.+ - 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, except the opted-in pre-push sharing below. 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. A note line may carry the session's share URL as its first trailing field (`beacon:<harness>/<id> <url>`; an identifier, not content): `gitlink.ValidShareURL` admits only https URLs on beacon.sh or the configured Beacon host (`AllowShareHost`, fed by `gitAllowShareHosts`), on write and on read, and `MergeNote`/`ParseNote` prefer the line with the URL over the bare one. Post-commit and `link` take URLs only from local `session.shared` events (`localShareURLs`). `setup --share-sessions [--share-visibility]` (implies `--share-notes`; stored as `beacon.shareSessions`/`beacon.shareVisibility` in local git config; public needs confirmation or `--yes`) makes the pre-push hook, which now receives git's stdin, share sessions linked to pushed commits that have no URL (at most 100 commits/10 sessions, inside the 10 s budget less 3 s kept for the notes push, silent without credentials, never failing the push) through `shareUpload` (`cmd/share_upload.go`: `alignShareSource` + `ShareEventsAfter`), then write the URLs into the notes before pushing them.++- 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. A note line may carry the session's share URL as its first trailing field (`beacon:<harness>/<id> <url>`; an identifier, not content): `gitlink.ValidShareURL` admits only https URLs on beacon.sh or the configured Beacon host (`AllowShareHost`, fed by `gitAllowShareHosts`), on write and on read, and `MergeNote`/`ParseNote` prefer the line with the URL over the bare one. Post-commit and `link` take URLs only from local `session.shared` events (`localShareURLs`). `setup --share-sessions [--share-visibility]` (implies `--share-notes`; stored as `beacon.shareSessions`/`beacon.shareVisibility` in local git config; public needs confirmation or `--yes`) makes the pre-push hook, which now receives git's stdin, share sessions linked to pushed commits that have no URL (at most 100 commits/10 sessions, inside the 10 s budget less 3 s kept for the notes push, silent without credentials, never failing the push) through `shareUpload` (`cmd/share_upload.go`: `alignShareSource` + `ShareEventsAfter`), then write the URLs into the notes before pushing them. `beacon share --follow [--interval]` (`cmd/share_follow.go`) polls the session locally, uploads through `shareUpload` only when the fingerprint of the projected trace events changed (the events only: the trace body carries its build time), stops at `session.ended` or Ctrl+C (`shareFollowWait`/`shareFollowSignals` are the test seams), and records `session.shared` after each upload, later ones as refreshes that keep the share date; `docs/cli/share.mdx` carries the API-key CI walkthrough with GitHub Actions and GitLab CI examples.- 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 --cc cli/beacon/cmd/share.goindex dffba899,d4321671..ad70f782--- a/cli/beacon/cmd/share.go+++ b/cli/beacon/cmd/share.go@@@ -37,9 -38,6 +38,9 @@@ import// trace list and dashboard show the session as shared. That event is inferred bookkeeping: no// harness collected it.- // errShareNothingYet is a session with no messages to share yet. --follow waits for some.++// errShareNothingYet is a session with no events to share yet. --follow waits for some.+var errShareNothingYet = errors.New("has nothing to share yet")+// SessionSharedAction is the runtime-log action recorded after a session is shared or refreshed.const SessionSharedAction = "session.shared"@@@ -163,8 -161,6 +166,8 @@@ func init()f.BoolVar(&shareOpts.list, "list", false, "List the sessions that could be shared, newest first, and share nothing")f.IntVar(&shareOpts.limit, "limit", 20, "With --list, the most sessions to show (0 for all)")f.BoolVar(&shareOpts.yes, "yes", false, "Share publicly without asking")- f.BoolVar(&shareOpts.follow, "follow", false, "Keep uploading the session's new messages until it ends or Ctrl+C")- f.DurationVar(&shareOpts.interval, "interval", shareFollowDefaultInterval, "With --follow, how often to check the session for new messages")++ f.BoolVar(&shareOpts.follow, "follow", false, "Keep uploading the session's new events until it ends or Ctrl+C")++ f.DurationVar(&shareOpts.interval, "interval", shareFollowDefaultInterval, "With --follow, how often to check the session for new events")shareCmd.MarkFlagsMutuallyExclusive("session", "source-path", "cwd", "current")}@@@ -240,20 -242,15 +249,22 @@@ func runShare(cmd *cobra.Command) erroif err != nil {return err}+ if shareOpts.follow {+ visibility := ""+ if cmd.Flags().Changed("visibility") {+ visibility = shareOpts.visibility+ }+ return runShareFollow(cmd, client, subject, visibility)+ }if !shareOpts.jsonOutput {- fmt.Fprintf(errOut, "Sharing %s session %s (%d messages)%s.\n", subject.session.Harness, subject.session.ID, len(payload.Messages), shareSourceNote(subject))+ fmt.Fprintf(errOut, "Sharing %s session %s (%d events)%s.\n", subject.session.Harness, subject.session.ID, len(payload.Events), shareSourceNote(subject))}ctx := commandContext(cmd)- if state, found, err := client.GetTrace(ctx, payload.ExternalID); err != nil {+ state, found, err := client.GetTrace(ctx, payload.ExternalID)+ if err != nil {return err- } else if found {+ }+ if found {if subject, payload, err = alignShareSource(subject, payload, state); err != nil {return err}@@@ -805,16 -857,18 +876,33 @@@ func shareEvents(subject shareSubject)if err == nil {return subject, events, nil}- if !errors.Is(err, handoff.ErrNotFound) {- return subject, nil, fmt.Errorf("read %s session %s: %w", subject.session.Harness, subject.session.ID, err)- }+ // The store lost the session, or cannot be read (locked, corrupt, no permission): the runtime+ // log may still have it.logSubject, logErr := resolveShareLog(subject.session)++ if logErr == nil && !errors.Is(err, handoff.ErrNotFound) && !shareHasProjectable(logSubject.logEvents) {++ // The log holds nothing of the session but Beacon's own bookkeeping (a session.shared++ // record from an earlier upload): it is no copy of the session, so the store's error stands.++ logErr = fmt.Errorf("%s session %s is not in the runtime log %s", subject.session.Harness, subject.session.ID, shareLogPath())++ }if logErr != nil {- return subject, nil, logErr+ if errors.Is(err, handoff.ErrNotFound) {+ return subject, nil, logErr+ }+ return subject, nil, fmt.Errorf("read %s session %s: %w (and the runtime log: %v)", subject.session.Harness, subject.session.ID, err, logErr)}return logSubject, logSubject.logEvents, nil}++// shareHasProjectable reports whether any of events would be carried by a shared trace.++func shareHasProjectable(events []schema.Event) bool {++ for _, event := range events {++ if asymptoteobserve.ShareProjects(event) {++ return true++ }++ }++ return false++}++func buildSharePayload(subject shareSubject) (sharePayload, error) {subject, events, err := shareEvents(subject)if err != nil {@@@ -822,18 -876,22 +910,22 @@@}session := subject.sessionsort.SliceStable(events, func(i, j int) bool { return shareEventTime(events[i]).Before(shareEventTime(events[j])) })- opts := asymptoteobserve.ShareOptions{WorkingDirectory: session.Directory}- messages := asymptoteobserve.BuildShareMessagesWithOptions(events, opts)- if len(messages) == 0 {+ bundle := asymptoteobserve.BuildShareBundle(events, asymptoteobserve.ShareOptions{+ WorkingDirectory: session.Directory,+ BeaconVersion: version.GetVersion(),+ GeneratedAt: shareNow(),+ })+ if len(bundle.Events) == 0 {- return sharePayload{}, fmt.Errorf("%s session %s has nothing to share yet", session.Harness, session.ID)+ return sharePayload{}, fmt.Errorf("%s session %s %w", session.Harness, session.ID, errShareNothingYet)}- trace := asymptoteobserve.ShareMetadataFromEventsWithOptions(events, opts)- agent := asymptoteobserve.NormalizeHarnessName(session.Harness)- if agent == "" {- agent = session.Harness+ // Visibility is set only when the person names one, so a re-share keeps the trace's own.+ trace := asymptoteobserve.NewShareTrace(bundle, "")+ if trace.Summary.Harness.Name == "" {+ trace.Summary.Harness.Name = session.Harness+ }+ if name := asymptoteobserve.NormalizeHarnessName(trace.Summary.Harness.Name); name != "" {+ trace.Summary.Harness.Name = name}- trace.AgentID = agent- trace.SourceSessionID = session.IDif title := strings.TrimSpace(shareOpts.title); title != "" {trace.Title = asymptoteobserve.ShareTitle(title)} else if title := asymptoteobserve.ShareTitle(session.Title); title != "" {diff --cc cli/beacon/cmd/share_follow.goindex 0feda297,00000000..41c74900mode 100644,000000..100644--- a/cli/beacon/cmd/share_follow.go+++ b/cli/beacon/cmd/share_follow.go@@@ -1,273 -1,0 +1,275 @@@+package cmd++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os"+ "os/signal"+ "syscall"+ "time"++ "github.com/spf13/cobra"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/account"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/gitlink"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/handoff"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/shareauto"+)++// `beacon share --follow` keeps a shared trace current while its session runs: it re-reads the+// session every --interval and uploads what changed, until the session records its end or the- // command is interrupted. Each poll is local; a request is made only when the session's messages++// command is interrupted. Each poll is local; a request is made only when the session's events+// changed since the last upload, and it goes through shareUpload, the same align-and-resume path+// as `beacon share refresh`.++const (+ shareFollowDefaultInterval = 10 * time.Second+ shareFollowMinInterval = time.Second+ // shareFollowFinalRetries bounds how many more times --follow tries to upload a session's last- // messages after the session ended, one interval apart, before it gives up with an error.++ // events after the session ended, one interval apart, before it gives up with an error.+ shareFollowFinalRetries = 3+ // shareFollowMaxReadFailures is how many polls in a row may fail to read the session, after+ // the first upload, before --follow gives up with an error.+ shareFollowMaxReadFailures = 5+)++var (+ // shareFollowWait sleeps between polls; tests replace it to drive the loop without a clock.+ shareFollowWait = func(ctx context.Context, d time.Duration) error {+ timer := time.NewTimer(d)+ defer timer.Stop()+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-timer.C:+ return nil+ }+ }+ // shareFollowSignals wires Ctrl+C and SIGTERM to the follow loop's context.+ shareFollowSignals = func(ctx context.Context) (context.Context, context.CancelFunc) {+ return signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)+ }+)++// shareFollowUpdate is one upload --follow made; --json prints one per line.+type shareFollowUpdate struct {+ shareResult+ Final bool `json:"final,omitempty"`+ // Ended is true when the session recorded its end.+ Ended bool `json:"ended,omitempty"`+}++func runShareFollow(cmd *cobra.Command, client *account.ShareClient, subject shareSubject, visibility string) error {+ interval := shareOpts.interval+ if interval < shareFollowMinInterval {+ interval = shareFollowMinInterval+ }+ ctx, stop := shareFollowSignals(commandContext(cmd))+ defer stop()+ out, errOut := cmd.OutOrStdout(), cmd.ErrOrStderr()+ if !shareOpts.jsonOutput {- fmt.Fprintf(errOut, "Following %s session %s, uploading new messages every %s. Ctrl+C stops.\n", subject.session.Harness, subject.session.ID, interval)++ fmt.Fprintf(errOut, "Following %s session %s, uploading new events every %s. Ctrl+C stops.\n", subject.session.Harness, subject.session.ID, interval)+ }+ var (+ lastPrint string+ last shareResult+ uploads int+ ended bool+ lastErr error+ finalFailures int+ finalErr error+ )+ var (+ readFailures int+ lastReadWarn string+ )+ for {+ var readErr error+ if subject.fromLog {+ // A session read from the runtime log is re-read each time; one from a store is read+ // fresh by buildSharePayload anyway.+ if fresh, err := resolveShareLog(subject.session); err == nil {+ fresh.selectedBy = subject.selectedBy+ subject = fresh+ } else {+ readErr = err+ }+ }+ fingerprint, end, err := shareFollowState(subject)+ ended = end+ if readErr == nil && err != nil && !errors.Is(err, errShareNothingYet) {+ readErr = err+ }+ if uploads > 0 {+ // After the first upload a read failure is not fatal at once (a store or log being+ // rewritten under us), but it is never silent, and it is not retried forever.+ if readErr != nil {+ readFailures+++ if readFailures >= shareFollowMaxReadFailures {- return fmt.Errorf("stopped following: the session could not be read %d times in a row (%s holds %d messages): %w", readFailures, last.SharedURL, last.MessageCount, readErr)++ return fmt.Errorf("stopped following: the session could not be read %d times in a row (%s holds %d events): %w", readFailures, last.SharedURL, last.EventCount, readErr)+ }+ if msg := readErr.Error(); msg != lastReadWarn {+ fmt.Fprintf(errOut, "warning: could not read the session, retrying in %s: %v\n", interval, readErr)+ lastReadWarn = msg+ }+ } else {+ readFailures, lastReadWarn = 0, ""+ }+ }+ if err == nil && fingerprint != lastPrint {- // Every upload that sends messages records a session.shared refresh, so a session++ // Every upload that sends events records a session.shared refresh, so a session+ // being followed never looks out of date locally; it is at most one per interval.+ opts := shareUploadOptions{Record: true}+ if uploads == 0 {+ // An explicit --visibility or --title applies once, to the trace as it is now+ // (created or existing). Later uploads leave both alone, so a rename on beacon.sh+ // while following is kept.+ opts.Visibility = visibility+ opts.ExplicitVisibility = visibility != ""+ if f := cmd.Flags().Lookup("title"); f != nil && f.Changed {+ opts.ExplicitTitle = true+ }+ }+ result, aligned, upErr := shareUpload(ctx, client, subject, opts)+ var recordErr *shareRecordError+ if errors.As(upErr, &recordErr) {+ // The trace is up; only the local session.shared event is missing. Say so and keep+ // following, as a later upload's record failure does.+ fmt.Fprintf(errOut, "warning: the session was shared, but the runtime log was not updated: %v\n", recordErr.err)+ upErr = nil+ }+ switch {+ case upErr == nil:+ subject, last, lastPrint = aligned, result, fingerprint+ uploads+++ if err := printShareFollow(out, errOut, result, uploads == 1, false, ended); err != nil {+ return err+ }+ case ctx.Err() != nil:+ // Interrupted mid-upload; the loop ends below.+ case uploads == 0:+ return upErr+ default:+ // beacon.sh or the network failed after the first upload: say so and retry on the+ // next poll, since the next upload resends whatever this one lacked.+ lastErr = upErr+ fmt.Fprintf(errOut, "warning: upload failed, retrying in %s: %v\n", interval, upErr)+ }+ } else if err != nil && uploads == 0 && !errors.Is(err, errShareNothingYet) {+ return err+ }+ if ctx.Err() != nil {+ break+ }+ if ended {+ if err != nil || fingerprint == lastPrint {+ break+ }- // The session ended with messages beacon.sh does not have yet. There is no next poll++ // The session ended with events beacon.sh does not have yet. There is no next poll+ // to catch up on, so retry a few times and then fail rather than report a trace that+ // is missing its end.+ finalFailures+++ if finalFailures > shareFollowFinalRetries {- finalErr = fmt.Errorf("the session ended, but its last messages were not uploaded after %d attempts (%s holds %d messages): %w", finalFailures, last.SharedURL, last.MessageCount, lastErr)++ finalErr = fmt.Errorf("the session ended, but its last events were not uploaded after %d attempts (%s holds %d events): %w", finalFailures, last.SharedURL, last.EventCount, lastErr)+ break+ }+ }+ if shareFollowWait(ctx, interval) != nil {+ break+ }+ }+ if uploads == 0 {+ if ctx.Err() != nil {+ return errors.New("stopped before the session had anything to share")+ }+ return fmt.Errorf("%s session %s has nothing to share", subject.session.Harness, subject.session.ID)+ }+ if finalErr != nil {+ return finalErr+ }+ return printShareFollow(out, errOut, last, false, true, ended)+}+- // shareFollowState is a fingerprint of the session's messages as they would be uploaded now, and++// shareFollowState is a fingerprint of the session's trace events as they would be uploaded now, and+// whether the session recorded its end.+func shareFollowState(subject shareSubject) (string, bool, error) {+ _, events, err := shareEvents(subject)+ if err != nil {+ return "", false, err+ }+ // A resumed session keeps its old session.ended, so only an end that nothing but Beacon's own+ // bookkeeping follows counts.+ ended, latest := shareSessionEnd(events)+ if !ended && !subject.fromLog {+ ended = shareLogRecordsEnd(subject.session, latest)+ }+ payload, err := buildSharePayload(subject)+ if err != nil {+ return "", ended, err+ }- data, err := json.Marshal(payload)++ // The events alone: the trace body carries the time it was built, which differs on every poll,++ // and everything else in it is folded from these events.++ data, err := json.Marshal(payload.Events)+ if err != nil {+ return "", ended, err+ }+ sum := sha256.Sum256(data)+ return hex.EncodeToString(sum[:]), ended, nil+}++func printShareFollow(out, errOut io.Writer, result shareResult, first, final, ended bool) error {+ if shareOpts.jsonOutput {+ return json.NewEncoder(out).Encode(map[string]any{"ok": true, "data": shareFollowUpdate{shareResult: result, Final: final, Ended: ended}})+ }+ switch {+ case first:+ fmt.Fprintln(out, result.SharedURL)- fmt.Fprintf(errOut, "%s, %d messages. External id: %s\n", result.Visibility, result.MessageCount, result.ExternalID)++ fmt.Fprintf(errOut, "%s, %d events. External id: %s\n", result.Visibility, result.EventCount, result.ExternalID)+ case final && ended:- fmt.Fprintf(errOut, "The session ended; %s holds %d messages.\n", result.SharedURL, result.MessageCount)++ fmt.Fprintf(errOut, "The session ended; %s holds %d events.\n", result.SharedURL, result.EventCount)+ case final:- fmt.Fprintf(errOut, "Stopped following; %s holds %d messages.\n", result.SharedURL, result.MessageCount)++ fmt.Fprintf(errOut, "Stopped following; %s holds %d events.\n", result.SharedURL, result.EventCount)+ default:- fmt.Fprintf(errOut, "Uploaded %d message(s); %d in total.\n", result.Uploaded, result.MessageCount)++ fmt.Fprintf(errOut, "Uploaded %d event(s); %d in total.\n", result.Uploaded, result.EventCount)+ }+ return nil+}++// shareLogRecordsEnd reports whether the runtime log records the end of session, which most store+// mappers do not emit: the runtime's hooks write session.ended to the log, not to its own store.+// The end counts only when it is the log's newest activity for the session and is no older than+// storeLatest, the newest activity in the store (a resumed session has an old end in both). A log+// that cannot be read says nothing.+func shareLogRecordsEnd(session handoff.Session, storeLatest time.Time) bool {+ found, events, ok, err := handoff.LogSession(shareLogPath(), session.ID, session.Harness)+ if err != nil || !ok || found.ID != session.ID || found.Harness != session.Harness {+ return false+ }+ ended, endAt := shareSessionEnd(events)+ return ended && !endAt.Before(storeLatest)+}++// shareSessionEnd reports whether events, in order, end with session.ended followed by nothing but+// Beacon's bookkeeping (session.shared, session.share_requested, session.commit_linked), and the+// newest timestamp among the activity it considered (the end's, when it ended).+func shareSessionEnd(events []schema.Event) (bool, time.Time) {+ ended := false+ var latest time.Time+ for _, e := range events {+ switch e.Event.Action {+ case SessionSharedAction, shareauto.ActionShareRequested, gitlink.LinkAction:+ continue+ }+ ended = e.Event.Action == "session.ended"+ if ts, err := schema.ParseTimestamp(e.Timestamp); err == nil && ts.After(latest) {+ latest = ts+ }+ }+ return ended, latest+}diff --cc cli/beacon/cmd/share_follow_test.goindex 9dde4ba9,00000000..d5ac928fmode 100644,000000..100644--- a/cli/beacon/cmd/share_follow_test.go+++ b/cli/beacon/cmd/share_follow_test.go@@@ -1,483 -1,0 +1,487 @@@+package cmd++import (+ "context"+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/account"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/handoff"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+)++// growingSource is a Claude Code store whose one session gains events while --follow runs.+type growingSource struct {+ mu sync.Mutex+ session handoff.Session+ events []schema.Event+ // fail, when set, is what reading the session's events returns.+ fail error+}++func (g *growingSource) Harness() string { return handoff.HarnessClaude }+func (g *growingSource) List() ([]handoff.Session, error) {+ return []handoff.Session{g.session}, nil+}+func (g *growingSource) Events(handoff.Session) ([]schema.Event, error) {+ g.mu.Lock()+ defer g.mu.Unlock()+ if g.fail != nil {+ return nil, g.fail+ }+ return append([]schema.Event(nil), g.events...), nil+}+func (g *growingSource) add(e schema.Event) {+ g.mu.Lock()+ g.events = append(g.events, e)+ g.mu.Unlock()+}++func followEvent(dir, ts, action string) schema.Event {+ e := schema.NewEvent(schema.NewEventOptions{Action: action, Category: "agent", Harness: schema.HarnessInfo{Name: handoff.HarnessClaude, CollectionMethod: schema.CollectionMethodPoll}})+ e.Timestamp = ts+ e.Session = &schema.SessionInfo{ID: shareTestSession, WorkingDirectory: dir}+ return e+}++func TestShareFollowUploadsNewMessagesUntilTheSessionEnds(t *testing.T) {+ env := newShareEnv(t)+ src := &growingSource{+ session: handoff.Session{Harness: handoff.HarnessClaude, ID: shareTestSession, Directory: env.projectDir, UpdatedAt: time.Now()},+ events: shareFixtureEvents(env.projectDir),+ }+ stubHandoffSources(t, src)+ srv := newFakeShareServer(t)+ srv.signIn(account.ScopeTracesWrite)++ // The fake clock: each wait is one poll. Polls 1 and 3 add to the session, poll 2 adds+ // nothing (no request may be made for it), and poll 4 records the session's end.+ polls := 0+ requestsAt := map[int]int{}+ prevWait := shareFollowWait+ shareFollowWait = func(ctx context.Context, d time.Duration) error {+ if d != 2*time.Second {+ t.Errorf("interval = %s", d)+ }+ polls+++ srv.mu.Lock()+ requestsAt[polls] = len(srv.requests)+ srv.mu.Unlock()+ switch polls {+ case 1:+ m := followEvent(env.projectDir, "2026-10-01T10:01:00.000000000Z", "agent.message")+ m.GenAI = &schema.GenAIInfo{Output: &schema.GenAIOutputInfo{Messages: asymptoteobserve.TextOutputMessages("Second answer.")}}+ src.add(m)+ case 3:+ p := followEvent(env.projectDir, "2026-10-01T10:02:00.000000000Z", "prompt.submitted")+ p.Event.Category = "prompt"+ p.Prompt = &schema.PromptInfo{Text: "One more thing"}+ src.add(p)+ case 4:+ src.add(followEvent(env.projectDir, "2026-10-01T10:03:00.000000000Z", "session.ended"))+ case 10:+ return errors.New("the loop did not stop at the session's end")+ }+ return nil+ }+ t.Cleanup(func() { shareFollowWait = prevWait })++ stdout, stderr, err := runShareCommand(t, "--follow", "--interval", "2s", "--json", "--cwd", env.projectDir, "--log-path", env.logPath)+ if err != nil {+ t.Fatalf("follow: %v\n%s", err, stderr)+ }+ if polls != 4 {+ t.Fatalf("polls = %d, want 4", polls)+ }+ srv.mu.Lock()+ if requestsAt[3] != requestsAt[2] {+ t.Errorf("an unchanged poll made requests: %v", srv.requests[requestsAt[2]:requestsAt[3]])+ }- messages := len(srv.messages)++ events := len(srv.events)+ srv.mu.Unlock()+ // The fixture's four, the second answer, the new prompt, and the session's end.- if messages != 7 {- t.Fatalf("server has %d messages, want 7", messages)++ if events != 7 {++ t.Fatalf("server has %d events, want 7", events)+ }+ lines := strings.Split(strings.TrimSpace(stdout), "\n")+ var final struct {+ OK bool `json:"ok"`+ Data shareFollowUpdate `json:"data"`+ }+ if err := json.Unmarshal([]byte(lines[len(lines)-1]), &final); err != nil || !final.Data.Final || !final.Data.Ended || final.Data.SharedURL != "https://beacon.sh/s/k3xabc" {+ t.Fatalf("last line %q (%v)", lines[len(lines)-1], err)+ }+ // One per upload: the share, the second answer, the new prompt and the end. Each later one is+ // a refresh, so a followed session is never shown as out of date.+ records := shareEventsIn(t, env.logPath)+ if len(records) != 4 {+ t.Fatalf("session.shared events = %d, want one per upload", len(records))+ }+ for i, r := range records {+ if _, ok := r.Raw["shared_through"].(string); !ok {+ t.Fatalf("record %d has no shared_through: %v", i, r.Raw)+ }- if _, first := r.Raw["shared_at"]; first != (i == 0) {- t.Fatalf("record %d shared_at present = %v", i, first)++ // Every record names the share date; the refreshes take it from the trace's creation on++ // beacon.sh, so it never moves past the first upload.++ sharedAt, _ := r.Raw["shared_at"].(string)++ first, _ := records[0].Raw["shared_at"].(string)++ if sharedAt == "" || sharedAt > first {++ t.Fatalf("record %d shared_at = %q, first %q", i, sharedAt, first)+ }+ }+}++func TestShareFollowStopsOnInterrupt(t *testing.T) {+ env := newShareEnv(t)+ srv := newFakeShareServer(t)+ srv.signIn(account.ScopeTracesWrite)+ prevWait, prevSignals := shareFollowWait, shareFollowSignals+ var cancel context.CancelFunc+ shareFollowSignals = func(ctx context.Context) (context.Context, context.CancelFunc) {+ ctx, cancel = context.WithCancel(ctx)+ return ctx, cancel+ }+ shareFollowWait = func(ctx context.Context, d time.Duration) error {+ cancel() // Ctrl+C during the first wait+ return ctx.Err()+ }+ t.Cleanup(func() { shareFollowWait, shareFollowSignals = prevWait, prevSignals })+ stdout, stderr, err := runShareCommand(t, "--follow", "--cwd", env.projectDir, "--log-path", env.logPath)+ if err != nil {+ t.Fatalf("follow: %v", err)+ }+ if !strings.HasPrefix(stdout, "https://beacon.sh/s/k3xabc") || !strings.Contains(stderr, "Stopped following") {+ t.Fatalf("stdout=%q stderr=%q", stdout, stderr)+ }+ if _, _, err := runShareCommand(t, "--follow", "--print"); err == nil {+ t.Fatal("--follow --print accepted")+ }+}++func shareEventsIn(t *testing.T, logPath string) []schema.Event {+ t.Helper()+ data, err := os.ReadFile(logPath)+ if err != nil {+ t.Fatal(err)+ }+ var out []schema.Event+ for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {+ var e schema.Event+ if json.Unmarshal([]byte(line), &e) == nil && e.Event.Action == SessionSharedAction {+ out = append(out, e)+ }+ }+ return out+}++// When the poll that sees the session end cannot upload its last messages, --follow retries a+// bounded number of times and then fails, rather than reporting a trace that lacks its end.+func TestShareFollowRetriesTheFinalUploadThenFails(t *testing.T) {+ env := newShareEnv(t)+ src := &growingSource{+ session: handoff.Session{Harness: handoff.HarnessClaude, ID: shareTestSession, Directory: env.projectDir, UpdatedAt: time.Now()},+ events: shareFixtureEvents(env.projectDir),+ }+ stubHandoffSources(t, src)+ srv := newFakeShareServer(t)+ srv.signIn(account.ScopeTracesWrite)+ polls := 0+ prevWait := shareFollowWait+ shareFollowWait = func(ctx context.Context, d time.Duration) error {+ polls+++ if polls == 1 {+ // The session ends while beacon.sh is down.+ src.add(followEvent(env.projectDir, "2026-10-01T10:03:00.000000000Z", "session.ended"))+ srv.mu.Lock()+ srv.failBatches = true+ srv.mu.Unlock()+ }+ if polls > 10 {+ return errors.New("the loop did not give up")+ }+ return nil+ }+ t.Cleanup(func() { shareFollowWait = prevWait })++ _, stderr, err := runShareCommand(t, "--follow", "--cwd", env.projectDir, "--log-path", env.logPath)- if err == nil || !strings.Contains(err.Error(), "last messages were not uploaded") {++ if err == nil || !strings.Contains(err.Error(), "last events were not uploaded") {+ t.Fatalf("follow err = %v\n%s", err, stderr)+ }+ // One wait before the end, then one per retry.+ if polls != 1+shareFollowFinalRetries {+ t.Fatalf("waits = %d, want %d", polls, 1+shareFollowFinalRetries)+ }+ if n := strings.Count(stderr, "warning: upload failed"); n != 1+shareFollowFinalRetries {+ t.Fatalf("failed uploads reported = %d\n%s", n, stderr)+ }+ if strings.Contains(stderr, "The session ended;") {+ t.Fatalf("reported success:\n%s", stderr)+ }++ // The outage ends during the retries: the end is uploaded and follow succeeds.+ env = newShareEnv(t)+ src = &growingSource{+ session: handoff.Session{Harness: handoff.HarnessClaude, ID: shareTestSession, Directory: env.projectDir, UpdatedAt: time.Now()},+ events: shareFixtureEvents(env.projectDir),+ }+ stubHandoffSources(t, src)+ srv = newFakeShareServer(t)+ srv.signIn(account.ScopeTracesWrite)+ polls = 0+ shareFollowWait = func(ctx context.Context, d time.Duration) error {+ polls+++ srv.mu.Lock()+ defer srv.mu.Unlock()+ switch polls {+ case 1:+ src.add(followEvent(env.projectDir, "2026-10-01T10:03:00.000000000Z", "session.ended"))+ srv.failBatches = true+ case 2:+ srv.failBatches = false+ case 10:+ return errors.New("the loop did not stop")+ }+ return nil+ }+ _, stderr, err = runShareCommand(t, "--follow", "--cwd", env.projectDir, "--log-path", env.logPath)+ if err != nil || !strings.Contains(stderr, "The session ended;") {+ t.Fatalf("recovered follow: err=%v\n%s", err, stderr)+ }+ srv.mu.Lock()+ defer srv.mu.Unlock()- if len(srv.messages) != 5 {- t.Fatalf("server has %d messages, want the fixture's four and the end", len(srv.messages))++ if len(srv.events) != 5 {++ t.Fatalf("server has %d events, want the fixture's four and the end", len(srv.events))+ }+}++// A first upload that succeeds but cannot write its session.shared event warns, prints the link+// and keeps following.+func TestShareFollowKeepsGoingWhenTheFirstRecordFails(t *testing.T) {+ env := newShareEnv(t)+ src := &growingSource{+ session: handoff.Session{Harness: handoff.HarnessClaude, ID: shareTestSession, Directory: env.projectDir, UpdatedAt: time.Now()},+ events: shareFixtureEvents(env.projectDir),+ }+ stubHandoffSources(t, src)+ srv := newFakeShareServer(t)+ srv.signIn(account.ScopeTracesWrite)+ // A log path under a regular file cannot be written.+ blocker := filepath.Join(env.home, "not-a-dir")+ if err := os.WriteFile(blocker, []byte("x"), 0o600); err != nil {+ t.Fatal(err)+ }+ logPath := filepath.Join(blocker, "runtime.jsonl")+ polls := 0+ prevWait := shareFollowWait+ shareFollowWait = func(ctx context.Context, d time.Duration) error {+ polls+++ switch polls {+ case 1:+ src.add(followEvent(env.projectDir, "2026-10-01T10:03:00.000000000Z", "session.ended"))+ case 10:+ return errors.New("the loop did not stop")+ }+ return nil+ }+ t.Cleanup(func() { shareFollowWait = prevWait })+ stdout, stderr, err := runShareCommand(t, "--follow", "--cwd", env.projectDir, "--log-path", logPath)+ if err != nil {+ t.Fatalf("follow: %v\n%s", err, stderr)+ }+ if !strings.HasPrefix(stdout, "https://beacon.sh/s/k3xabc") || !strings.Contains(stderr, "runtime log was not updated") || !strings.Contains(stderr, "The session ended;") {+ t.Fatalf("stdout=%q stderr=%q", stdout, stderr)+ }+ if polls != 1 {+ t.Fatalf("waits = %d, want 1", polls)+ }+ srv.mu.Lock()+ defer srv.mu.Unlock()- if len(srv.messages) != 5 {- t.Fatalf("server has %d messages, want 5", len(srv.messages))++ if len(srv.events) != 5 {++ t.Fatalf("server has %d events, want 5", len(srv.events))+ }+}++// --follow to a trace that already exists keeps the title set on it earlier, and applies an+// explicit --visibility to it as plain share does.+func TestShareFollowKeepsTitleAndAppliesExplicitVisibility(t *testing.T) {+ env := newShareEnv(t)+ src := &growingSource{+ session: handoff.Session{Harness: handoff.HarnessClaude, ID: shareTestSession, Directory: env.projectDir, UpdatedAt: time.Now()},+ events: shareFixtureEvents(env.projectDir),+ }+ stubHandoffSources(t, src)+ srv := newFakeShareServer(t)+ srv.signIn(account.ScopeTracesWrite)+ if _, stderr, err := runShareCommand(t, "--cwd", env.projectDir, "--title", "Login fix", "--visibility", "public", "--yes", "--log-path", env.logPath); err != nil {+ t.Fatalf("share: %v\n%s", err, stderr)+ }+ polls := 0+ prevWait := shareFollowWait+ shareFollowWait = func(ctx context.Context, d time.Duration) error {+ polls+++ switch polls {+ case 1:+ m := followEvent(env.projectDir, "2026-10-01T10:01:00.000000000Z", "agent.message")+ m.GenAI = &schema.GenAIInfo{Output: &schema.GenAIOutputInfo{Messages: asymptoteobserve.TextOutputMessages("Second answer.")}}+ src.add(m)+ case 2:+ src.add(followEvent(env.projectDir, "2026-10-01T10:03:00.000000000Z", "session.ended"))+ case 10:+ return errors.New("the loop did not stop")+ }+ return nil+ }+ t.Cleanup(func() { shareFollowWait = prevWait })+ if _, stderr, err := runShareCommand(t, "--follow", "--visibility", "private", "--cwd", env.projectDir, "--log-path", env.logPath); err != nil {+ t.Fatalf("follow: %v\n%s", err, stderr)+ }+ srv.mu.Lock()+ defer srv.mu.Unlock()+ if srv.trace.Title != "Login fix" {+ t.Fatalf("title = %q, want the one set with --title", srv.trace.Title)+ }+ if srv.trace.Visibility != "private" {+ t.Fatalf("visibility = %q, want the explicit --visibility", srv.trace.Visibility)+ }+}++// Most store mappers never emit session.ended; the runtime's hooks write it to the runtime log.+// --follow on a store-backed session stops when the log records the end.+func TestShareFollowStopsWhenTheRuntimeLogRecordsTheEnd(t *testing.T) {+ env := newShareEnv(t)+ src := &growingSource{+ session: handoff.Session{Harness: handoff.HarnessClaude, ID: shareTestSession, Directory: env.projectDir, UpdatedAt: time.Now()},+ events: shareFixtureEvents(env.projectDir),+ }+ stubHandoffSources(t, src)+ srv := newFakeShareServer(t)+ srv.signIn(account.ScopeTracesWrite)+ polls := 0+ prevWait := shareFollowWait+ shareFollowWait = func(ctx context.Context, d time.Duration) error {+ polls+++ switch polls {+ case 1:+ // Another session's end must not stop this one.+ other := followEvent(env.projectDir, "2026-10-01T10:02:00.000000000Z", "session.ended")+ other.Session.ID = "someone-else"+ appendLogEvent(t, env.logPath, other)+ case 2:+ appendLogEvent(t, env.logPath, followEvent(env.projectDir, "2026-10-01T10:03:00.000000000Z", "session.ended"))+ case 10:+ return errors.New("the loop did not stop at the end the runtime log recorded")+ }+ return nil+ }+ t.Cleanup(func() { shareFollowWait = prevWait })+ _, stderr, err := runShareCommand(t, "--follow", "--cwd", env.projectDir, "--log-path", env.logPath)+ if err != nil {+ t.Fatalf("follow: %v\n%s", err, stderr)+ }+ if polls != 2 || !strings.Contains(stderr, "The session ended;") {+ t.Fatalf("polls = %d, stderr:\n%s", polls, stderr)+ }+}++// After the first upload, a session that cannot be read is reported (once per distinct error,+// not every poll), and --follow gives up after shareFollowMaxReadFailures polls in a row.+func TestShareFollowReportsReadFailuresAndGivesUp(t *testing.T) {+ env := newShareEnv(t)+ src := &growingSource{+ session: handoff.Session{Harness: handoff.HarnessClaude, ID: shareTestSession, Directory: env.projectDir, UpdatedAt: time.Now()},+ events: shareFixtureEvents(env.projectDir),+ }+ stubHandoffSources(t, src)+ srv := newFakeShareServer(t)+ srv.signIn(account.ScopeTracesWrite)+ polls := 0+ prevWait := shareFollowWait+ shareFollowWait = func(ctx context.Context, d time.Duration) error {+ polls+++ if polls == 1 {+ src.mu.Lock()+ src.fail = errors.New("store is being rewritten")+ src.mu.Unlock()+ }+ if polls > 20 {+ return errors.New("the loop did not give up")+ }+ return nil+ }+ t.Cleanup(func() { shareFollowWait = prevWait })+ _, stderr, err := runShareCommand(t, "--follow", "--cwd", env.projectDir, "--log-path", env.logPath)+ if err == nil || !strings.Contains(err.Error(), "could not be read") || !strings.Contains(err.Error(), "store is being rewritten") {+ t.Fatalf("follow err = %v\n%s", err, stderr)+ }+ if polls != shareFollowMaxReadFailures {+ t.Fatalf("waits = %d, want %d", polls, shareFollowMaxReadFailures)+ }+ if n := strings.Count(stderr, "warning: could not read the session"); n != 1 {+ t.Fatalf("read warnings = %d, want one for the repeated error\n%s", n, stderr)+ }+}++func appendLogEvent(t *testing.T, path string, e schema.Event) {+ t.Helper()+ data, err := json.Marshal(e)+ if err != nil {+ t.Fatal(err)+ }+ f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)+ if err != nil {+ t.Fatal(err)+ }+ defer f.Close()+ if _, err := f.Write(append(data, '\n')); err != nil {+ t.Fatal(err)+ }+}++// A resumed session keeps its old session.ended; --follow keeps going while newer activity follows+// it, and stops when a new end arrives after that activity.+func TestShareFollowIgnoresAnOldEndOfAResumedSession(t *testing.T) {+ env := newShareEnv(t)+ events := append(shareFixtureEvents(env.projectDir),+ followEvent(env.projectDir, "2026-10-01T10:00:30.000000000Z", "session.ended"))+ resumed := followEvent(env.projectDir, "2026-10-01T10:05:00.000000000Z", "prompt.submitted")+ resumed.Event.Category = "prompt"+ resumed.Prompt = &schema.PromptInfo{Text: "picking this back up"}+ events = append(events, resumed)+ src := &growingSource{+ session: handoff.Session{Harness: handoff.HarnessClaude, ID: shareTestSession, Directory: env.projectDir, UpdatedAt: time.Now()},+ events: events,+ }+ stubHandoffSources(t, src)+ srv := newFakeShareServer(t)+ srv.signIn(account.ScopeTracesWrite)+ // The runtime log has the old end too.+ appendLogEvent(t, env.logPath, followEvent(env.projectDir, "2026-10-01T10:00:30.000000000Z", "session.ended"))+ polls := 0+ prevWait := shareFollowWait+ shareFollowWait = func(ctx context.Context, d time.Duration) error {+ polls+++ switch polls {+ case 3:+ // The resumed session ends; its hooks write the end to the runtime log.+ appendLogEvent(t, env.logPath, followEvent(env.projectDir, "2026-10-01T10:09:00.000000000Z", "session.ended"))+ case 10:+ return errors.New("the loop did not stop at the new end")+ }+ return nil+ }+ t.Cleanup(func() { shareFollowWait = prevWait })+ _, stderr, err := runShareCommand(t, "--follow", "--cwd", env.projectDir, "--log-path", env.logPath)+ if err != nil {+ t.Fatalf("follow: %v\n%s", err, stderr)+ }+ if polls != 3 || !strings.Contains(stderr, "The session ended;") {+ t.Fatalf("polls = %d, want 3 (the old end must not stop it)\n%s", polls, stderr)+ }+}diff --cc cli/beacon/cmd/share_test.goindex 03b647a8,cc3c7539..c12158b5--- a/cli/beacon/cmd/share_test.go+++ b/cli/beacon/cmd/share_test.go@@@ -235,11 -253,10 +253,12 @@@ type fakeShareServer structmu sync.Mutexserver *httptest.Servertrace *asymptoteobserve.ShareTraceV1- messages []asymptoteobserve.ShareMessageV1+ events []asymptoteobserve.TraceEventV1+ created stringrequests []stringauth map[string]bool- // failBatches makes every message upload fail, as an outage would.++ // failBatches makes every event upload fail, as an outage would.+ failBatches bool}func newFakeShareServer(t *testing.T) *fakeShareServer {@@@ -264,13 -281,13 +283,17 @@@if trace.Visibility == "" {trace.Visibility = "direct"}+ if created {+ // beacon.sh stamps the trace when it creates it; the test clock stands in for it.+ f.created = shareNow().UTC().Format(time.RFC3339)+ }f.trace = &trace- fmt.Fprintf(w, `{"id":"k3xabc","external_id":%q,"url":"https://beacon.sh/s/k3xabc","visibility":%q,"message_count":%d,"created":%v}`, id, trace.Visibility, len(f.messages), created)- case r.Method == http.MethodPost && strings.HasSuffix(id, "/messages/batch"):+ fmt.Fprintf(w, `{"id":"k3xabc","external_id":%q,"url":"https://beacon.sh/s/k3xabc","visibility":%q,"event_count":%d,"created":%v}`, id, trace.Visibility, len(f.events), created)+ case r.Method == http.MethodPost && strings.HasSuffix(id, "/events/batch"):+ if f.failBatches {+ http.Error(w, "unavailable", http.StatusServiceUnavailable)+ return+ }zr, err := gzip.NewReader(r.Body)if err != nil {http.Error(w, "want gzip", 400)diff --cc docs/cli/share.mdxindex 421b66c9,543a0596..4a8886a3--- a/docs/cli/share.mdx+++ b/docs/cli/share.mdx@@@ -118,17 -118,6 +119,17 @@@ beacon share refresh 5f0c1d2beacon share refresh # this session, found like --current```+## Follow a running session+- `--follow` keeps the trace current while the session runs. It shares the session, then checks it again every `--interval` (default `10s`, at least `1s`) and uploads what changed, until the session records its end (`session.ended`, in the runtime's store or in the runtime log, where the hooks write it; a resumed session's earlier end does not count once newer activity follows it) or you press Ctrl+C. A check is a local read; a request is made only when the session's messages changed, and it sends only what beacon.sh lacks, the same way `refresh` does. A failed upload after the first is reported and retried on the next check. When the session has ended and its last messages cannot be uploaded, `--follow` retries three more times, one interval apart, and then exits non-zero naming what the trace holds. If the runtime log cannot be written after an upload, `--follow` warns and keeps going. A check that cannot read the session is reported once per distinct error, and after five failed checks in a row `--follow` exits non-zero.++`--follow` keeps the trace current while the session runs. It shares the session, then checks it again every `--interval` (default `10s`, at least `1s`) and uploads what changed, until the session records its end (`session.ended`, in the runtime's store or in the runtime log, where the hooks write it; a resumed session's earlier end does not count once newer activity follows it) or you press Ctrl+C. A check is a local read; a request is made only when the session's trace events changed, and it sends only the events beacon.sh lacks, the same way `refresh` does. A failed upload after the first is reported and retried on the next check. When the session has ended and its last events cannot be uploaded, `--follow` retries three more times, one interval apart, and then exits non-zero naming what the trace holds. If the runtime log cannot be written after an upload, `--follow` warns and keeps going. A check that cannot read the session is reported once per distinct error, and after five failed checks in a row `--follow` exits non-zero.++```bash+beacon share --follow # this session, until it ends+beacon share --follow --session 5f0c1d2e --interval 30s+```+- `--follow` waits for a session that has nothing to share yet. The link is printed after the first upload; with `--json`, each upload prints one JSON document per line, and the last carries `"final":true` (and `"ended":true` when the session ended). The runtime log gets one `session.shared` event when the trace is first shared and one after each later upload that sent messages, so the dashboard does not show a followed session as out of date. `--follow` cannot be combined with `--print` or `--list`.++`--follow` waits for a session that has nothing to share yet. The link is printed after the first upload; with `--json`, each upload prints one JSON document per line, and the last carries `"final":true` (and `"ended":true` when the session ended). The runtime log gets one `session.shared` event when the trace is first shared and one after each later upload that sent events (a refresh, which keeps the share date), so the dashboard does not show a followed session as out of date. `--follow` cannot be combined with `--print` or `--list`.+## 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:@@@ -284,8 -180,6 +285,8 @@@ The link goes to stdout and a summary t| `--limit <n>` | With `--list`, the most sessions to show || `--print`, `--dry-run` | Print the payload and send nothing || `--yes` | Share publicly without asking |- | `--follow` | Keep uploading new messages until the session ends or Ctrl+C |++| `--follow` | Keep uploading new events until the session ends or Ctrl+C |+| `--interval <duration>` | With `--follow`, how often to check the session (default `10s`) || `--json` | Print the result as JSON || `--store-dir <runtime>=<path>` | Read a runtime's sessions from this directory (repeatable) || `--log-path <path>` | Runtime log to read from and record the share in |