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
Carry share URLs in commit notes and share linked sessions on push
Claude63c278c84e7f
diff --git a/CLAUDE.md b/CLAUDE.mdindex c4fd68f8..f881655d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -70,7 +70,7 @@ Supported runtime surfaces today:- 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.+- 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 Cloud MCP registration via `beacon mcp connect|disconnect|status` (`cli/beacon/internal/mcpconnect`, `cli/beacon/cmd/mcp_connect.go`; docs in `docs/cli/mcp-connect.mdx`). It registers the Beacon Cloud MCP server as `beacon-managed`, a different name from the local stdio server `beacon`, in the user-level config of Claude Code, Codex CLI, Cursor, VS Code, Gemini CLI and OpenCode. It prints manual steps for runtimes without confirmed MCP OAuth support. OAuth is the default and writes only the URL; `--token-env` writes a reference to an environment variable in each harness's own syntax, never a value. `connect` never reads or copies the account token and never writes a token; minting one is the separate, explicit `beacon mcp token create`. It is explicit and interactive: never run by an unattended install; the onboarding wizard runs it only after the person chose Beacon Cloud and left "Beacon Cloud MCP" selected (that screen is the confirmation), and otherwise the install only suggests it. It is refused as root, and refused in CI or without a terminal unless `--yes` is given. Its one network request is the RFC 9728 resource-metadata check of the URL, which `--dry-run` skips. Configs are edited like the Kimi Code writer: never re-serialized, spliced as text, parsed back and compared before an atomic replace, backed up first. What was written is recorded in `~/.beacon/mcp/connections.json`, and `disconnect` removes only entries recorded there that still point at the recorded URL. `cmd/mcp_connect_e2e_test.go` runs the real harness CLIs when they are installed; re-run it when a harness changes its MCP config format.- An optional, off-by-default policy seam in the hook path (`cli/beacon-hooks/internal/policy`) governed by the stable contract in `pkg/asymptoteobserve/policycontract`. When `BEACON_POLICY_PROVIDER` names an executable, the `pre-tool` and `permission-request` hooks send it a JSON request describing the imminent tool call and honor an allow/deny response, returning the runtime's native deny shape and `policy.enforcement=enforce` telemetry on a deny. The seam is inert when unset and fail-open on any error (timeout, non-zero exit, malformed output), so the open build ships no enforcement of its own; all audit/enforce decision logic lives in the external provider. `rules/agent-control/agent-permission-bypass-spawn.rule.yaml` is the open detect twin that flags the same pattern in `beacon scan`.diff --git a/cli/beacon/cmd/git.go b/cli/beacon/cmd/git.goindex d05a8cb5..0a058f7a 100644--- a/cli/beacon/cmd/git.go+++ b/cli/beacon/cmd/git.go@@ -85,6 +85,7 @@ func runGitLink(cmd *cobra.Command, args []string) error {MinLookback: gitOpts.minLookback,MaxLookback: gitOpts.maxLookback,DryRun: gitOpts.dryRun,+ ShareURL: gitShareURLLookup(gitRuntimeLogPath()),})if err != nil {return err@@ -161,6 +162,7 @@ func runGitNotes(cmd *cobra.Command, args []string) error {if len(args) == 1 {rev = args[0]}+ gitAllowShareHosts()commits, err := gitlink.ListLinked(ctx, repo.Git, rev, gitOpts.limit)if err != nil {return err@@ -179,6 +181,10 @@ func runGitNotes(cmd *cobra.Command, args []string) error {for _, c := range commits {fmt.Fprintf(out, "%s %s %s\n", shortSHA(c.SHA), c.CommitTime.Local().Format(time.DateTime), c.Subject)for _, link := range c.Links {+ if link.URL != "" {+ fmt.Fprintf(out, " %s/%s %s\n", link.Harness, link.SessionID, link.URL)+ continue+ }fmt.Fprintf(out, " %s/%s\n", link.Harness, link.SessionID)}}@@ -200,7 +206,7 @@ func shortSHA(sha string) string {func containsLink(links []gitlink.Link, link gitlink.Link) bool {for _, l := range links {- if l == link {+ if l.Key() == link.Key() {return true}}diff --git a/cli/beacon/cmd/git_hooks.go b/cli/beacon/cmd/git_hooks.goindex 9ea9bb3c..34ac7486 100644--- a/cli/beacon/cmd/git_hooks.go+++ b/cli/beacon/cmd/git_hooks.go@@ -14,6 +14,7 @@ import ("github.com/spf13/cobra""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/gitlink"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve")// gitHookBudget bounds the post-commit hook. Linking reads recent runtime log and writes one@@ -78,8 +79,11 @@ var gitHookPostRewriteCmd = &cobra.Command{}var gitSetupOpts struct {- allowHooksPath bool- shareNotes bool+ allowHooksPath bool+ shareNotes bool+ shareSessions bool+ shareVisibility string+ yes bool}func runGitSetup(cmd *cobra.Command, _ []string) error {@@ -96,6 +100,27 @@ func runGitSetup(cmd *cobra.Command, _ []string) error {share := gitSetupOpts.shareNotesopts.ShareNotes = &share}+ shareSessions := cmd.Flags().Changed("share-sessions") && gitSetupOpts.shareSessions+ visibility := strings.ToLower(strings.TrimSpace(gitSetupOpts.shareVisibility))+ if shareSessions {+ if opts.ShareNotes != nil && !*opts.ShareNotes {+ return errors.New("--share-sessions shares sessions from the pre-push hook that --share-notes installs; it cannot be combined with --share-notes=false")+ }+ if !asymptoteobserve.ValidShareVisibility(visibility) {+ return fmt.Errorf("--share-visibility must be public, direct or private, not %q", gitSetupOpts.shareVisibility)+ }+ if visibility == asymptoteobserve.ShareVisibilityPublic && !gitSetupOpts.yes {+ if !shareIsTTY() || isCIEnvironment() {+ return errors.New("public sharing lists every session linked to a pushed commit in Discover; pass --yes to set it up without a terminal to confirm")+ }+ fmt.Fprint(cmd.ErrOrStderr(), "Share every session linked to a pushed commit publicly? Anyone can find and read them in Discover. [y/N] ")+ if !confirmNo(shareStdin) {+ return errors.New("nothing was changed")+ }+ }+ share := true+ opts.ShareNotes = &share+ }result, err := gitlink.InstallHooks(ctx, repo, opts)out := cmd.OutOrStdout()if err != nil {@@ -118,12 +143,36 @@ func runGitSetup(cmd *cobra.Command, _ []string) error {}return err}+ sessionsChanged := ""+ switch {+ case shareSessions:+ if err := gitlink.SetShareSessions(ctx, repo, true, visibility); err != nil {+ return err+ }+ sessionsChanged = "on"+ case cmd.Flags().Changed("share-sessions") || (opts.ShareNotes != nil && !*opts.ShareNotes):+ if enabled, _ := gitlink.ShareSessionsConfig(ctx, repo); enabled {+ if err := gitlink.SetShareSessions(ctx, repo, false, ""); err != nil {+ return err+ }+ sessionsChanged = "off"+ }+ }if gitOpts.jsonOutput {- return writeIndentedJSON(out, result)+ return writeIndentedJSON(out, struct {+ gitlink.InstallResult+ ShareSessions string `json:"share_sessions,omitempty"`+ }{result, sessionsChanged})}for _, r := range result.Reports {fmt.Fprintf(out, "%-9s %s (calls %s)\n", r.Action, r.Path, filepath.Base(r.Script))}+ switch sessionsChanged {+ case "on":+ fmt.Fprintf(out, "set %s = true, %s = %s\n", gitlink.ShareSessionsKey, gitlink.ShareVisibilityKey, visibility)+ case "off":+ fmt.Fprintf(out, "unset %s\n", gitlink.ShareSessionsKey)+ }if result.RewriteRefSet {fmt.Fprintf(out, "set notes.rewriteRef = %s\n", gitlink.NotesRef)}@@ -136,6 +185,9 @@ func runGitSetup(cmd *cobra.Command, _ []string) error {if opts.ShareNotes != nil && *opts.ShareNotes {fmt.Fprintf(out, "Commit links are shared: each `git push` also pushes %s to the same remote, and `git fetch` brings teammates' links.\n", gitlink.NotesRef)}+ if sessionsChanged == "on" {+ fmt.Fprintf(out, "Each `git push` also shares the agent sessions linked to the pushed commits to beacon.sh (%s), using your `beacon login` or BEACON_API_KEY, and writes their links into the notes.\n", visibility)+ }fmt.Fprintln(out, "New commits in this repository are linked to the agent sessions that wrote them.")fmt.Fprintln(out, "See them with `beacon git notes`; link an older commit with `beacon git link <commit>`.")return nil@@ -161,6 +213,9 @@ func runGitRemove(cmd *cobra.Command, _ []string) error {if result.RewriteRefRemoved {fmt.Fprintf(out, "unset notes.rewriteRef = %s\n", gitlink.NotesRef)}+ if result.ShareSessionsRemoved {+ fmt.Fprintf(out, "unset %s\n", gitlink.ShareSessionsKey)+ }for _, remote := range result.FetchRemoved {fmt.Fprintf(out, "unset remote.%s.fetch %s\n", remote, gitlink.FetchRefspec(remote))}@@ -215,6 +270,15 @@ func runGitStatus(cmd *cobra.Command, _ []string) error {for _, remote := range status.FetchRemotes {fmt.Fprintf(out, " fetches from %s bring its links\n", remote)}+ sessions := "off (`beacon git setup --share-sessions` turns it on)"+ if status.ShareSessions {+ vis := status.ShareVisibility+ if vis == "" {+ vis = asymptoteobserve.ShareVisibilityDirect+ }+ sessions = "on: pushes share linked sessions to beacon.sh (" + vis + ")"+ }+ fmt.Fprintf(out, "sessions %s\n", sessions)return nil}@@ -239,7 +303,7 @@ func gitPostCommit(ctx context.Context) (gitlink.Result, bool) {if err != nil || gitlink.ReplayInProgress(ctx, repo) {return gitlink.Result{}, false}- result, err := gitlink.Attribute(ctx, repo, gitlink.Options{LogPath: gitRuntimeLogPath()})+ result, err := gitlink.Attribute(ctx, repo, gitlink.Options{LogPath: gitRuntimeLogPath(), ShareURL: gitShareURLLookup(gitRuntimeLogPath())})if err != nil {return gitlink.Result{}, false}@@ -311,5 +375,8 @@ func init() {}gitHookPostCommitCmd.Flags().StringVar(&gitOpts.logPath, "log-path", "", "Runtime JSONL log to read sessions from (default the local runtime log)")gitSetupCmd.Flags().BoolVar(&gitSetupOpts.allowHooksPath, "hooks-path", false, "Install into core.hooksPath's directory when it is set")+ gitSetupCmd.Flags().BoolVar(&gitSetupOpts.shareSessions, "share-sessions", false, "Also share the sessions linked to pushed commits to beacon.sh during each git push, and note their links (implies --share-notes; --share-sessions=false turns it off)")+ gitSetupCmd.Flags().StringVar(&gitSetupOpts.shareVisibility, "share-visibility", asymptoteobserve.ShareVisibilityDirect, "With --share-sessions, the visibility of new traces: direct (anyone with the link), private or public")+ gitSetupCmd.Flags().BoolVar(&gitSetupOpts.yes, "yes", false, "With --share-visibility public, set it up without asking")gitSetupCmd.Flags().BoolVar(&gitSetupOpts.shareNotes, "share-notes", false, "Share links with remotes: push them with each git push and fetch teammates' (--share-notes=false turns it off)")}diff --git a/cli/beacon/cmd/git_share.go b/cli/beacon/cmd/git_share.goindex dd2ad8ef..9264d32a 100644--- a/cli/beacon/cmd/git_share.go+++ b/cli/beacon/cmd/git_share.go@@ -129,6 +129,16 @@ func runGitHookPrePush(cmd *cobra.Command, args []string) error {// A hook has no terminal to ask for credentials on; git's own push has already authenticated,// and a credential helper answers the same way for this one.repo.Git = repo.Git.WithExtraEnv("GIT_TERMINAL_PROMPT=0")+ stdin := readHookStdin(cmd.InOrStdin())+ if enabled, visibility := gitlink.ShareSessionsConfig(ctx, repo); enabled && stdin != "" {+ // Sharing sessions gets the budget less what pushing the notes ref needs, so the links+ // (with whatever URLs it recorded) still reach the remote.+ shareCtx, cancelShare := context.WithTimeout(ctx, gitShareBudget-gitShareNotesReserve)+ if _, err := gitShareSessionsOnPush(shareCtx, repo, args[0], stdin, visibility); err != nil && shareCtx.Err() == nil {+ fmt.Fprintf(cmd.ErrOrStderr(), "beacon: linked sessions were not all shared: %s\n", gitlink.ErrorSummary(err))+ }+ cancelShare()+ }if _, err := gitlink.PushNotes(ctx, repo, args[0]); err != nil {fmt.Fprintf(cmd.ErrOrStderr(), "beacon: commit links were not shared with %s: %s\n", args[0], gitlink.ErrorSummary(err))}diff --git a/cli/beacon/cmd/git_share_sessions.go b/cli/beacon/cmd/git_share_sessions.gonew file mode 100644index 00000000..86e760a5--- /dev/null+++ b/cli/beacon/cmd/git_share_sessions.go@@ -0,0 +1,212 @@+package cmd++import (+ "bufio"+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/url"+ "os"+ "strings"+ "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/gitlink"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/handoff"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+)++// Share URLs in commit notes.+//+// A note line may carry the linked session's shared-trace URL after the link: `beacon:<harness>/<id>+// <url>`. The URL is an identifier like the session id -- it names a page, it carries no content --+// so it belongs in a note that may be pushed. It is only ever an https URL on beacon.sh or on the+// Beacon service this CLI is configured for (gitlink.ValidShareURL); a note can come from anyone+// who pushes to the remote, so any other URL is neither written nor shown.+//+// The post-commit hook takes URLs only from local session.shared events (it never touches the+// network). The pre-push hook, with `beacon git setup --share-sessions`, shares linked sessions+// that have no URL yet during a push the person started, then records the URLs.++const (+ // gitShareMaxSessions bounds how many sessions one push shares.+ gitShareMaxSessions = 10+ // gitShareMaxCommits bounds how many pushed commits are read for links.+ gitShareMaxCommits = 100+ // gitShareNotesReserve is the part of the pre-push budget kept for pushing the notes ref.+ gitShareNotesReserve = 3 * time.Second+)++// gitAllowShareHosts admits the configured Beacon service's host besides beacon.sh.+func gitAllowShareHosts() {+ for _, raw := range []string{account.ResolveBaseURL("")} {+ if u, err := url.Parse(raw); err == nil && u.Scheme == "https" {+ gitlink.AllowShareHost(u.Host)+ }+ }+ if session, err := shareAccountLoad(); err == nil && session != nil {+ if u, err := url.Parse(session.BaseURL); err == nil && u.Scheme == "https" {+ gitlink.AllowShareHost(u.Host)+ }+ }+}++func gitShareKey(harness, sessionID string) string {+ name := asymptoteobserve.NormalizeHarnessName(harness)+ if name == "" {+ name = harness+ }+ return name + "/" + sessionID+}++// localShareURLs reads the share URL of every session the runtime log records as shared, from its+// session.shared events, keyed by gitShareKey. Only the current log file is read, and only lines+// that mention the action are decoded, so the post-commit hook stays fast.+func localShareURLs(logPath string) map[string]string {+ urls := map[string]string{}+ f, err := os.Open(logPath)+ if err != nil {+ return urls+ }+ defer f.Close()+ marker := []byte(`"` + SessionSharedAction + `"`)+ reader := bufio.NewReaderSize(f, 256*1024)+ for {+ line, err := reader.ReadBytes('\n')+ if len(line) > 0 && bytes.Contains(line, marker) {+ var event schema.Event+ if json.Unmarshal(line, &event) == nil && event.Event.Action == SessionSharedAction && event.Session != nil && event.Session.ID != "" {+ if u, _ := event.Raw["shared_url"].(string); gitlink.ValidShareURL(u) {+ urls[gitShareKey(event.Harness.Name, event.Session.ID)] = u+ }+ }+ }+ if err != nil {+ return urls+ }+ }+}++// gitShareURLLookup answers gitlink.Options.ShareURL from the runtime log, read once and only when+// a link is about to be written.+func gitShareURLLookup(logPath string) func(gitlink.Link) string {+ var urls map[string]string+ return func(link gitlink.Link) string {+ if urls == nil {+ gitAllowShareHosts()+ urls = localShareURLs(logPath)+ }+ return urls[gitShareKey(link.Harness, link.SessionID)]+ }+}++// gitPushShareReport is what sharing sessions during one push did.+type gitPushShareReport struct {+ Shared []string `json:"shared,omitempty"`+ Noted int `json:"noted"`+ Skipped string `json:"skipped,omitempty"`+}++// gitShareSessionsOnPush shares the sessions linked to the commits being pushed that have no share+// URL in their note yet, and writes the URLs into the notes, before the notes ref is pushed. A+// session already shared from this machine only has its URL written. Without a credential it does+// nothing and says nothing. ctx bounds it; every error is returned for one line on stderr, never+// to fail the push.+func gitShareSessionsOnPush(ctx context.Context, repo gitlink.Repo, remote, stdin, visibility string) (gitPushShareReport, error) {+ var report gitPushShareReport+ gitAllowShareHosts()+ commits, err := gitlink.PushedCommits(ctx, repo, remote, stdin, gitShareMaxCommits)+ if err != nil {+ return report, err+ }+ var order []gitlink.Link+ wanted := map[string]bool{}+ notes := map[string]string{}+ for _, sha := range commits {+ note, err := gitlink.ReadNote(ctx, repo.Git, sha)+ if err != nil || note == "" {+ continue+ }+ notes[sha] = note+ for _, link := range gitlink.ParseNote(note) {+ if link.URL == "" && !wanted[link.Key()] {+ wanted[link.Key()] = true+ order = append(order, link)+ }+ }+ }+ if len(order) == 0 {+ return report, nil+ }+ known := localShareURLs(shareLogPath())+ urls := map[string]string{}+ var toShare []gitlink.Link+ for _, link := range order {+ if u := known[gitShareKey(link.Harness, link.SessionID)]; u != "" {+ urls[link.Key()] = u+ } else {+ toShare = append(toShare, link)+ }+ }+ if len(toShare) > gitShareMaxSessions {+ toShare = toShare[:gitShareMaxSessions]+ }+ var shareErr error+ if len(toShare) > 0 {+ client, err := newShareClient()+ if err != nil {+ report.Skipped = "no Beacon credential"+ } else {+ sources := handoffSources(handoff.StoreDirs{})+ for _, link := range toShare {+ if ctx.Err() != nil {+ break+ }+ harness, err := handoff.ParseHarness(link.Harness)+ if err != nil {+ continue+ }+ subject, err := resolveShareID(sources, harness, link.SessionID)+ if err != nil || subject.session.ID != link.SessionID {+ continue // a teammate's session, or one this machine no longer has+ }+ result, _, err := shareUpload(ctx, client, subject, shareUploadOptions{Visibility: visibility, Record: true})+ if err != nil && result.SharedURL == "" {+ if shareErr == nil {+ shareErr = fmt.Errorf("%s: %w", link.Key(), err)+ }+ continue+ }+ if gitlink.ValidShareURL(result.SharedURL) {+ urls[link.Key()] = result.SharedURL+ report.Shared = append(report.Shared, link.Key())+ }+ }+ }+ }+ for sha := range notes {+ changed, err := gitlink.UpdateNote(ctx, repo.Git, sha, func(note string) string { return gitlink.SetLinkURLs(note, urls) })+ if err != nil {+ if shareErr == nil {+ shareErr = err+ }+ continue+ }+ if changed {+ report.Noted+++ }+ }+ return report, shareErr+}++// readHookStdin reads what git passes a pre-push hook on stdin, bounded.+func readHookStdin(r io.Reader) string {+ if r == nil {+ return ""+ }+ data, _ := io.ReadAll(io.LimitReader(r, 1<<20))+ return strings.TrimSpace(string(data))+}diff --git a/cli/beacon/cmd/git_share_sessions_test.go b/cli/beacon/cmd/git_share_sessions_test.gonew file mode 100644index 00000000..d344ea05--- /dev/null+++ b/cli/beacon/cmd/git_share_sessions_test.go@@ -0,0 +1,168 @@+package cmd++import (+ "bytes"+ "encoding/json"+ "os"+ "path/filepath"+ "strings"+ "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/gitlink"+)++func writeSharedEvent(t *testing.T, logPath, harness, session, url string) {+ t.Helper()+ event := schema.NewEvent(schema.NewEventOptions{Action: SessionSharedAction, Category: "session", Harness: schema.HarnessInfo{Name: harness}})+ event.Session = &schema.SessionInfo{ID: session}+ event.Raw = map[string]interface{}{"shared_url": url}+ line, _ := json.Marshal(event)+ f, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)+ if err != nil {+ t.Fatal(err)+ }+ defer f.Close()+ if _, err := f.Write(append(line, '\n')); err != nil {+ t.Fatal(err)+ }+}++func TestGitHookPostCommitWritesAKnownShareURL(t *testing.T) {+ root := gitCommandRepo(t)+ top := mustGit(t, root, "rev-parse", "--show-toplevel")+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ for _, f := range []string{"x.go", "y.go"} {+ if err := os.WriteFile(filepath.Join(root, f), []byte("package x\n"), 0o644); err != nil {+ t.Fatal(err)+ }+ }+ writeRuntimeEvent(t, logPath, top, "cur-1", "x.go")+ writeRuntimeEvent(t, logPath, top, "cur-2", "y.go")+ writeSharedEvent(t, logPath, "cursor", "cur-1", "https://beacon.sh/s/abc123")+ writeSharedEvent(t, logPath, "cursor", "cur-2", "https://evil.example/s/abc123")+ mustGit(t, root, "add", "-A")+ mustGit(t, root, "commit", "-q", "-m", "x")+ if out, err := runGit(t, "hook", "post-commit", "--cwd", root, "--log-path", logPath); err != nil || out != "" {+ t.Fatalf("hook: %v %q", err, out)+ }+ note := mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "show", "HEAD")+ if !strings.Contains(note, "beacon:cursor/cur-1 https://beacon.sh/s/abc123") || !strings.Contains(note, "beacon:cursor/cur-2") || strings.Contains(note, "evil.example") {+ t.Fatalf("note %q", note)+ }+ out, err := runGit(t, "notes", "--cwd", root, "--json")+ if err != nil || !strings.Contains(out, `"url": "https://beacon.sh/s/abc123"`) {+ t.Fatalf("notes --json: %v\n%s", err, out)+ }+ out, _ = runGit(t, "notes", "--cwd", root)+ if !strings.Contains(out, "cursor/cur-1 https://beacon.sh/s/abc123") {+ t.Fatalf("notes:\n%s", out)+ }+}++func TestGitPrePushSharesLinkedSessions(t *testing.T) {+ root, remote := gitCommandTeam(t)+ env := newShareEnv(t)+ srv := newFakeShareServer(t)+ srv.signIn(account.ScopeTracesWrite)+ prevOpts := shareOpts+ shareOpts = shareOptions{logPath: env.logPath}+ t.Cleanup(func() { shareOpts = prevOpts })++ old := mustGit(t, root, "rev-parse", "HEAD")+ mustGit(t, root, "commit", "-q", "--allow-empty", "-m", "agent work")+ sha := mustGit(t, root, "rev-parse", "HEAD")+ mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "add", "-m", "beacon:claude_code/"+shareTestSession+"\nbeacon:cursor/someone-else", sha)+ if out, err := runGit(t, "setup", "--cwd", root, "--share-sessions"); err != nil || !strings.Contains(out, "shares the agent sessions linked") {+ t.Fatalf("setup: %v\n%s", err, out)+ }+ if out, _ := runGit(t, "status", "--cwd", root); !strings.Contains(out, "sessions on: pushes share linked sessions to beacon.sh (direct)") {+ t.Fatalf("status:\n%s", out)+ }++ stdin := "refs/heads/main " + sha + " refs/heads/main " + old + "\n"+ var stderr bytes.Buffer+ rootCmd.SetIn(strings.NewReader(stdin))+ t.Cleanup(func() { rootCmd.SetIn(nil) })+ if _, err := runGitStderr(t, &stderr, "hook", "pre-push", "--cwd", root, "origin", remote); err != nil {+ t.Fatalf("pre-push: %v", err)+ }+ if stderr.Len() != 0 {+ t.Fatalf("stderr %q", stderr.String())+ }+ if len(srv.messages) != 4 {+ t.Fatalf("server messages = %d", len(srv.messages))+ }+ want := "beacon:claude_code/" + shareTestSession + " https://beacon.sh/s/k3xabc\nbeacon:cursor/someone-else"+ if note := mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "show", sha); note != want {+ t.Fatalf("local note %q", note)+ }+ if note := mustGit(t, remote, "notes", "--ref="+gitlink.NotesRef, "show", sha); note != want {+ t.Fatalf("remote note %q", note)+ }+ if urls := localShareURLs(env.logPath); urls["claude_code/"+shareTestSession] != "https://beacon.sh/s/k3xabc" {+ t.Fatalf("session.shared not recorded: %v", urls)+ }++ // A second push has nothing left to share and makes no share request.+ before := len(srv.requests)+ rootCmd.SetIn(strings.NewReader(stdin))+ if _, err := runGitStderr(t, &stderr, "hook", "pre-push", "--cwd", root, "origin", remote); err != nil || stderr.Len() != 0 {+ t.Fatalf("second pre-push: %v %q", err, stderr.String())+ }+ if len(srv.requests) != before {+ t.Fatalf("second push made share requests: %v", srv.requests[before:])+ }+}++func TestGitPrePushWithoutCredentialsSharesNothingQuietly(t *testing.T) {+ root, remote := gitCommandTeam(t)+ env := newShareEnv(t) // signed out, and any request fails the test+ prevOpts := shareOpts+ shareOpts = shareOptions{logPath: env.logPath}+ t.Cleanup(func() { shareOpts = prevOpts })+ old := mustGit(t, root, "rev-parse", "HEAD")+ mustGit(t, root, "commit", "-q", "--allow-empty", "-m", "agent work")+ sha := mustGit(t, root, "rev-parse", "HEAD")+ mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "add", "-m", "beacon:claude_code/"+shareTestSession, sha)+ if _, err := runGit(t, "setup", "--cwd", root, "--share-sessions"); err != nil {+ t.Fatal(err)+ }+ var stderr bytes.Buffer+ rootCmd.SetIn(strings.NewReader("refs/heads/main " + sha + " refs/heads/main " + old + "\n"))+ t.Cleanup(func() { rootCmd.SetIn(nil) })+ start := time.Now()+ if _, err := runGitStderr(t, &stderr, "hook", "pre-push", "--cwd", root, "origin", remote); err != nil || stderr.Len() != 0 {+ t.Fatalf("pre-push: %v %q", err, stderr.String())+ }+ if time.Since(start) > gitShareBudget {+ t.Fatal("pre-push exceeded its budget")+ }+ if note := mustGit(t, remote, "notes", "--ref="+gitlink.NotesRef, "show", sha); note != "beacon:claude_code/"+shareTestSession {+ t.Fatalf("remote note %q", note)+ }+}++func TestGitSetupShareSessionsRules(t *testing.T) {+ root, _ := gitCommandTeam(t)+ if _, err := runGit(t, "setup", "--cwd", root, "--share-sessions", "--share-notes=false"); err == nil {+ t.Fatal("--share-sessions with --share-notes=false accepted")+ }+ prev := shareIsTTY+ shareIsTTY = func() bool { return false }+ t.Cleanup(func() { shareIsTTY = prev })+ if _, err := runGit(t, "setup", "--cwd", root, "--share-sessions", "--share-visibility", "public"); err == nil || !strings.Contains(err.Error(), "--yes") {+ t.Fatalf("public without --yes: %v", err)+ }+ if out, err := runGit(t, "setup", "--cwd", root, "--share-sessions", "--share-visibility", "public", "--yes"); err != nil || !strings.Contains(out, "beacon.shareVisibility = public") {+ t.Fatalf("public --yes: %v\n%s", err, out)+ }+ if out, err := runGit(t, "setup", "--cwd", root, "--share-notes=false"); err != nil || !strings.Contains(out, "unset beacon.shareSessions") {+ t.Fatalf("share-notes off: %v\n%s", err, out)+ }+ if out, _ := runGit(t, "status", "--cwd", root); !strings.Contains(out, "sessions off") {+ t.Fatalf("status:\n%s", out)+ }+}diff --git a/cli/beacon/cmd/share_upload.go b/cli/beacon/cmd/share_upload.gonew file mode 100644index 00000000..142c0267--- /dev/null+++ b/cli/beacon/cmd/share_upload.go@@ -0,0 +1,72 @@+package cmd++import (+ "context"+ "fmt"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/account"+)++// shareUploadOptions configures shareUpload.+type shareUploadOptions struct {+ // Visibility is applied when the trace is created; an existing trace keeps its own.+ Visibility string+ // Record writes the session.shared event after the upload.+ Record bool+}++// shareUpload creates or updates subject's shared trace, sending only what beacon.sh lacks. It is+// the path every non-interactive upload takes (the pre-push hook, --follow), so it applies the same+// rules as `beacon share refresh`: an existing trace is checked against this copy of the session+// (alignShareSource) and only the messages after the last one beacon.sh holds are sent+// (messagesAfter), which re-sends open calls and that last message.+func shareUpload(ctx context.Context, client *account.ShareClient, subject shareSubject, opts shareUploadOptions) (shareResult, shareSubject, error) {+ payload, err := buildSharePayload(subject)+ if err != nil {+ return shareResult{}, subject, err+ }+ state, found, err := client.GetTrace(ctx, payload.ExternalID)+ if err != nil {+ return shareResult{}, subject, err+ }+ pending := payload.Messages+ if found {+ if subject, payload, err = alignShareSource(subject, payload, state); err != nil {+ return shareResult{}, subject, err+ }+ payload.Trace.Visibility = ""+ pending = messagesAfter(payload.Messages, state.LastMessageID, state.MaxOrder)+ } else if opts.Visibility != "" {+ payload.Trace.Visibility = opts.Visibility+ }+ trace, err := client.PutTrace(ctx, payload.ExternalID, payload.Trace)+ if err != nil {+ return shareResult{}, subject, err+ }+ uploaded, err := client.PutMessages(ctx, payload.ExternalID, pending)+ if err != nil {+ return shareResult{}, subject, fmt.Errorf("upload messages to %s: %w", trace.URL, err)+ }+ result := shareResult{+ TraceID: trace.ID,+ ExternalID: payload.ExternalID,+ SharedURL: trace.URL,+ Visibility: trace.Visibility,+ AgentID: payload.Trace.AgentID,+ MessageCount: trace.MessageCount,+ Uploaded: len(pending),+ SelectedBy: subject.selectedBy,+ }+ if found {+ result.MessageCount = state.MessageCount+ }+ if uploaded.Batches > 0 {+ result.MessageCount = uploaded.MessageCount+ }+ if opts.Record {+ if err := recordShareEvent(subject.session, result, found); err != nil {+ return result, subject, fmt.Errorf("shared, but the runtime log was not updated: %w", err)+ }+ }+ return result, subject, nil+}diff --git a/cli/beacon/internal/gitlink/events_test.go b/cli/beacon/internal/gitlink/events_test.goindex a2b94c8d..d8f8638f 100644--- a/cli/beacon/internal/gitlink/events_test.go+++ b/cli/beacon/internal/gitlink/events_test.go@@ -43,10 +43,10 @@ func TestLinkEventsShape(t *testing.T) {RepoRoot: "/work/repo",ChangedFiles: 3,Candidates: []Candidate{- {Link: Link{"claude_code", "s1"}, Files: []string{"a.go", "b.go"}},- {Link: Link{"cursor", "c1"}, Files: []string{"a.go"}, AlreadyLinked: true},+ {Link: Link{Harness: "claude_code", SessionID: "s1"}, Files: []string{"a.go", "b.go"}},+ {Link: Link{Harness: "cursor", SessionID: "c1"}, Files: []string{"a.go"}, AlreadyLinked: true},},- Added: []Link{{"claude_code", "s1"}},+ Added: []Link{{Harness: "claude_code", SessionID: "s1"}},NoteUpdated: true,}events := LinkEvents(result, CommitContext{Branch: "main", RemoteURL: "https://github.com/org/repo.git"}, "1.2.3")@@ -124,8 +124,8 @@ func TestLinkEventsAreNeverEvidence(t *testing.T) {logPath := filepath.Join(t.TempDir(), "runtime.jsonl")events := LinkEvents(Result{Commit: Commit{SHA: strings.Repeat("a", 40)}, RepoRoot: repo.Root, ChangedFiles: 1,- Candidates: []Candidate{{Link: Link{"codex_cli", "s"}, Files: []string{"x.go"}}},- Added: []Link{{"codex_cli", "s"}},+ Candidates: []Candidate{{Link: Link{Harness: "codex_cli", SessionID: "s"}, Files: []string{"x.go"}}},+ Added: []Link{{Harness: "codex_cli", SessionID: "s"}},}, CommitContext{Branch: "main"}, "")var b strings.Builderfor _, e := range events {diff --git a/cli/beacon/internal/gitlink/hooks.go b/cli/beacon/internal/gitlink/hooks.goindex d5f63c92..83f66327 100644--- a/cli/beacon/internal/gitlink/hooks.go+++ b/cli/beacon/internal/gitlink/hooks.go@@ -312,18 +312,19 @@ func HookCall(hook string) string {var hookPurpose = map[string]string{"post-commit": "links the new commit to the agent sessions that wrote it.","post-rewrite": "tidies the Beacon note on commits an amend or rebase rewrote.",- "pre-push": "shares refs/notes/beacon with the remote being pushed to.",+ "pre-push": "shares refs/notes/beacon with the remote being pushed to (and, with --share-sessions, the linked sessions).",}func hookScript(hook, beaconPath string) string {- // post-rewrite reads the rewritten commits from stdin; the others get nothing to read.- // pre-push needs the remote git passes, and keeps stderr so a failure to share says so.+ // post-rewrite reads the rewritten commits from stdin; post-commit gets nothing to read.+ // pre-push needs the remote git passes and the refs being pushed (stdin, which+ // --share-sessions reads), and keeps stderr so a failure to share says so.stdin, args, output := " </dev/null", "", " >/dev/null 2>&1"switch hook {case "post-rewrite":stdin, args = "", ` "$@"`case ShareHook:- args, output = ` "$@"`, " >/dev/null"+ stdin, args, output = "", ` "$@"`, " >/dev/null"}return `#!/bin/sh# Beacon ` + hook + ` hook: ` + hookPurpose[hook] + `@@ -339,7 +340,7 @@ exit 0func hookScope(hook string) string {if hook == ShareHook {- return "Pushes only Beacon's notes ref, only to this push's remote, and never fails the push."+ return "Pushes only Beacon's notes ref, only to this push's remote, and never fails the push. With --share-sessions it also shares the linked sessions to beacon.sh."}return "Reads the local runtime log and writes a git note; never touches the network or fails the commit."}@@ -370,6 +371,8 @@ type RemoveResult struct {Reports []HookReport `json:"reports"`RewriteRefRemoved bool `json:"rewrite_ref_removed"`FetchRemoved []string `json:"fetch_removed,omitempty"`+ // ShareSessionsRemoved is true when pushes had been sharing linked sessions.+ ShareSessionsRemoved bool `json:"share_sessions_removed,omitempty"`}func removeHook(dir, hook string) (HookReport, error) {@@ -418,6 +421,12 @@ func RemoveHooks(ctx context.Context, repo Repo) (RemoveResult, error) {if result.FetchRemoved, err = UnconfigureFetch(ctx, repo); err != nil {return result, err}+ if enabled, _ := ShareSessionsConfig(ctx, repo); enabled {+ if err := SetShareSessions(ctx, repo, false, ""); err != nil {+ return result, err+ }+ result.ShareSessionsRemoved = true+ }removed, err := removeRewriteRef(ctx, repo)if err != nil {return result, err@@ -454,6 +463,10 @@ type Status struct {// fetches bring their links along.Sharing bool `json:"sharing"`FetchRemotes []string `json:"fetch_remotes,omitempty"`+ // ShareSessions is true when pushes also share linked sessions to beacon.sh, with+ // ShareVisibility for new traces ("" for the server default, direct).+ ShareSessions bool `json:"share_sessions"`+ ShareVisibility string `json:"share_visibility,omitempty"`}// Installed is true when every managed hook is installed. Sharing is optional and not counted.@@ -502,6 +515,7 @@ func HookStatus(ctx context.Context, repo Repo) (Status, error) {}}}+ status.ShareSessions, status.ShareVisibility = ShareSessionsConfig(ctx, repo)status.RewriteRef, err = hasRewriteRef(ctx, repo)return status, err}diff --git a/cli/beacon/internal/gitlink/hooks_test.go b/cli/beacon/internal/gitlink/hooks_test.goindex e86ce3bb..c18ebb31 100644--- a/cli/beacon/internal/gitlink/hooks_test.go+++ b/cli/beacon/internal/gitlink/hooks_test.go@@ -372,7 +372,7 @@ func TestAmendCarriesLinksThroughRewriteRef(t *testing.T) {}r.write("a", "1")r.commitWithEnv("c")- if _, err := AddLinks(ctx, repo.Git, r.git("rev-parse", "HEAD"), []Link{{"codex_cli", "s"}}); err != nil {+ if _, err := AddLinks(ctx, repo.Git, r.git("rev-parse", "HEAD"), []Link{{Harness: "codex_cli", SessionID: "s"}}); err != nil {t.Fatal(err)}r.git("commit", "-q", "--amend", "-m", "c (amended)")diff --git a/cli/beacon/internal/gitlink/link.go b/cli/beacon/internal/gitlink/link.goindex 2035122c..8589f299 100644--- a/cli/beacon/internal/gitlink/link.go+++ b/cli/beacon/internal/gitlink/link.go@@ -33,6 +33,10 @@ type Options struct {MaxLookback time.Duration// DryRun computes the links without writing the note.DryRun bool+ // ShareURL, when set, returns a linked session's known share URL ("" when it has none), which+ // is written on the session's note line. It must answer from local state: the post-commit+ // hook never touches the network.+ ShareURL func(Link) string}// Candidate is a session that wrote at least one file the commit changes.@@ -130,7 +134,13 @@ func Attribute(ctx context.Context, repo Repo, opts Options) (Result, error) {result.Candidates = rankCandidates(evidence, changed, existing)for _, c := range result.Candidates {if !c.AlreadyLinked && len(existing)+len(result.Added) < MaxLinks {- result.Added = append(result.Added, c.Link)+ link := c.Link+ if opts.ShareURL != nil {+ if u := opts.ShareURL(link); ValidShareURL(u) {+ link.URL = u+ }+ }+ result.Added = append(result.Added, link)}}if len(result.Added) == 0 || opts.DryRun {diff --git a/cli/beacon/internal/gitlink/note.go b/cli/beacon/internal/gitlink/note.goindex 3f929114..aaaafa04 100644--- a/cli/beacon/internal/gitlink/note.go+++ b/cli/beacon/internal/gitlink/note.go@@ -1,9 +1,11 @@package gitlinkimport (+ "net/url""regexp""sort""strings"+ "sync")// NotesRef is the notes ref Beacon's links live under. It is a contract: `beacon git notes`, the@@ -24,6 +26,51 @@ var harnessPattern = regexp.MustCompile(`^[a-z0-9_]+$`)type Link struct {Harness string `json:"harness"`SessionID string `json:"session_id"`+ // URL is the session's shared trace on beacon.sh, when it has been shared. It is the note+ // line's first reserved trailing field: an identifier like the session id, never content.+ URL string `json:"url,omitempty"`+}++// MaxShareURLLength bounds a share URL in a note line.+const MaxShareURLLength = 512++var (+ shareHostsMu sync.RWMutex+ shareHosts = map[string]bool{"beacon.sh": true}+)++// AllowShareHost adds a host whose https URLs a note line may carry as a share URL, besides+// beacon.sh: the Beacon service the CLI is configured to use.+func AllowShareHost(host string) {+ host = strings.ToLower(strings.TrimSpace(host))+ if host == "" {+ return+ }+ shareHostsMu.Lock()+ shareHosts[host] = true+ shareHostsMu.Unlock()+}++// ValidShareURL reports whether raw may be written into, or read from, a note as a share URL: an+// absolute https URL on an allowed host, with no userinfo, whitespace or control characters. A+// note can come from anyone who pushes to the remote, so a URL on another host is never shown as a+// session's link.+func ValidShareURL(raw string) bool {+ if raw == "" || len(raw) > MaxShareURLLength {+ return false+ }+ for _, r := range raw {+ if r <= ' ' || r >= 0x7f {+ return false+ }+ }+ u, err := url.Parse(raw)+ if err != nil || u.Scheme != "https" || u.User != nil || u.Host == "" || u.Opaque != "" {+ return false+ }+ shareHostsMu.RLock()+ defer shareHostsMu.RUnlock()+ return shareHosts[strings.ToLower(u.Host)]}// Key is the link's identity, harness and session together: two runtimes may reuse an id.@@ -47,8 +94,13 @@ func (l Link) Valid() bool {return true}-// Line is the note line for the link.-func (l Link) Line() string { return linePrefix + l.Key() }+// Line is the note line for the link, with its share URL when it has a valid one.+func (l Link) Line() string {+ if ValidShareURL(l.URL) {+ return linePrefix + l.Key() + " " + l.URL+ }+ return linePrefix + l.Key()+}// ParseLine reads one note line, returning false for a line that is not a Beacon link.func ParseLine(line string) (Link, bool) {@@ -56,9 +108,12 @@ func ParseLine(line string) (Link, bool) {if !ok {return Link{}, false}- // Anything after whitespace is reserved for later fields; readers today ignore it.+ // Fields after whitespace are reserved. The first is a share URL; it is kept only when it is+ // one (ValidShareURL), and anything else there is ignored, so a line written by a newer+ // version still reads as its link.+ trailing := ""if i := strings.IndexAny(rest, " \t"); i >= 0 {- rest = rest[:i]+ rest, trailing = rest[:i], strings.TrimSpace(rest[i:])}harness, session, ok := strings.Cut(rest, "/")if !ok {@@ -68,19 +123,50 @@ func ParseLine(line string) (Link, bool) {if !link.Valid() {return Link{}, false}+ if fields := strings.Fields(trailing); len(fields) > 0 && ValidShareURL(fields[0]) {+ link.URL = fields[0]+ }return link, true}+// SetLinkURLs returns note with a share URL added to each Beacon line that names a session in urls+// (keyed by Link.Key) and has no trailing fields yet. Every other line is kept verbatim, including+// a line that already carries a URL or fields this version does not know.+func SetLinkURLs(note string, urls map[string]string) string {+ if len(urls) == 0 {+ return note+ }+ lines := strings.Split(note, "\n")+ for i, line := range lines {+ link, ok := ParseLine(line)+ if !ok || strings.TrimSpace(strings.TrimRight(line, "\r")) != linePrefix+link.Key() {+ continue+ }+ if u := urls[link.Key()]; ValidShareURL(u) {+ link.URL = u+ lines[i] = link.Line()+ }+ }+ return strings.Join(lines, "\n")+}+// ParseNote returns the Beacon links in a note, in the order they first appear, without repeats.+// A link repeated with a share URL (a teammate's copy of a note, merged) takes the URL.func ParseNote(note string) []Link {var links []Link- seen := map[string]bool{}+ index := map[string]int{}for _, line := range strings.Split(note, "\n") {link, ok := ParseLine(line)- if !ok || seen[link.Key()] {+ if !ok {+ continue+ }+ if i, seen := index[link.Key()]; seen {+ if links[i].URL == "" {+ links[i].URL = link.URL+ }continue}- seen[link.Key()] = true+ index[link.Key()] = len(links)links = append(links, link)}return links@@ -92,29 +178,44 @@ func ParseNote(note string) []Link {// repeat of a link already seen are dropped. New links are appended in the order given. Merging// links a note already has returns it unchanged apart from that normalization.//+// The one exception to "the first line wins" is the share URL: when the kept line is the bare+// `beacon:<harness>/<id>` and a repeat (or a new link) carries a URL, the line with the URL takes+// its place. Git's cat_sort_uniq merge sorts the bare line first, and without this a teammate's+// URL would be dropped by the next normalization.+//// Links are never removed here. A note is shared history, and a teammate's link on the same commit// is as true as ours.func MergeNote(note string, links []Link) string {var lines []string- seen := map[string]bool{}+ index := map[string]int{}+ bare := func(i int, link Link) bool { return strings.TrimSpace(lines[i]) == linePrefix+link.Key() }for _, line := range strings.Split(note, "\n") {line = strings.TrimRight(line, "\r")if strings.TrimSpace(line) == "" {continue}if link, ok := ParseLine(line); ok {- if seen[link.Key()] {+ if i, seen := index[link.Key()]; seen {+ if link.URL != "" && bare(i, link) {+ lines[i] = line+ }continue}- seen[link.Key()] = true+ index[link.Key()] = len(lines)}lines = append(lines, line)}for _, link := range links {- if !link.Valid() || seen[link.Key()] {+ if !link.Valid() {+ continue+ }+ if i, seen := index[link.Key()]; seen {+ if ValidShareURL(link.URL) && bare(i, link) {+ lines[i] = link.Line()+ }continue}- seen[link.Key()] = true+ index[link.Key()] = len(lines)lines = append(lines, link.Line())}if len(lines) == 0 {diff --git a/cli/beacon/internal/gitlink/note_test.go b/cli/beacon/internal/gitlink/note_test.goindex 43400c5e..d5dfbdb2 100644--- a/cli/beacon/internal/gitlink/note_test.go+++ b/cli/beacon/internal/gitlink/note_test.go@@ -57,7 +57,7 @@ func TestParseNoteDedupesInOrder(t *testing.T) {func TestMergeNoteKeepsOtherLinesAndAppends(t *testing.T) {note := "Reviewed-by: a person\nbeacon:codex/a\nbeacon:v2 something newer\n"- got := MergeNote(note, []Link{{"codex", "a"}, {"claude_code", "b"}, {"BAD", "c"}})+ got := MergeNote(note, []Link{{Harness: "codex", SessionID: "a"}, {Harness: "claude_code", SessionID: "b"}, {Harness: "BAD", SessionID: "c"}})want := "Reviewed-by: a person\nbeacon:codex/a\nbeacon:v2 something newer\nbeacon:claude_code/b\n"if got != want {t.Fatalf("got %q\nwant %q", got, want)@@ -65,7 +65,7 @@ func TestMergeNoteKeepsOtherLinesAndAppends(t *testing.T) {}func TestMergeNoteIsIdempotent(t *testing.T) {- links := []Link{{"codex", "a"}, {"cursor", "b"}}+ links := []Link{{Harness: "codex", SessionID: "a"}, {Harness: "cursor", SessionID: "b"}}once := MergeNote("", links)if twice := MergeNote(once, links); twice != once {t.Fatalf("second merge changed the note:\n%q\n%q", once, twice)@@ -86,3 +86,50 @@ func TestMergeNoteNormalizesBlankLinesAndRepeats(t *testing.T) {t.Fatal("an empty note must stay empty")}}++func TestNoteLinesCarryAllowlistedShareURLs(t *testing.T) {+ link, ok := ParseLine("beacon:claude_code/s1 https://beacon.sh/s/k3x future-field")+ if !ok || link.URL != "https://beacon.sh/s/k3x" || link.Key() != "claude_code/s1" {+ t.Fatalf("link = %+v %v", link, ok)+ }+ for _, line := range []string{+ "beacon:claude_code/s1 https://evil.example/s/k3x",+ "beacon:claude_code/s1 http://beacon.sh/s/k3x",+ "beacon:claude_code/s1 https://user:[email protected]/s/k3x",+ "beacon:claude_code/s1 not-a-url",+ } {+ link, ok := ParseLine(line)+ if !ok || link.URL != "" || link.SessionID != "s1" {+ t.Errorf("%q = %+v %v; want the link without a URL", line, link, ok)+ }+ }+ if got := (Link{Harness: "codex", SessionID: "a", URL: "https://evil.example/x"}).Line(); got != "beacon:codex/a" {+ t.Fatalf("disallowed URL written: %q", got)+ }+ AllowShareHost("beacon.internal.example")+ if !ValidShareURL("https://beacon.internal.example/s/1") {+ t.Fatal("configured host refused")+ }+}++func TestMergeNoteAndSetLinkURLsKeepTheURL(t *testing.T) {+ // cat_sort_uniq puts the bare line first; the URL line must win.+ merged := MergeNote("beacon:codex/a\nbeacon:codex/a https://beacon.sh/s/1\nReviewed-by: x\n", nil)+ if merged != "beacon:codex/a https://beacon.sh/s/1\nReviewed-by: x\n" {+ t.Fatalf("merged = %q", merged)+ }+ merged = MergeNote("beacon:codex/a\n", []Link{{Harness: "codex", SessionID: "a", URL: "https://beacon.sh/s/2"}, {Harness: "cursor", SessionID: "b", URL: "https://beacon.sh/s/3"}})+ if merged != "beacon:codex/a https://beacon.sh/s/2\nbeacon:cursor/b https://beacon.sh/s/3\n" {+ t.Fatalf("merged = %q", merged)+ }+ note := "beacon:codex/a\nbeacon:codex/b https://beacon.sh/s/old\nbeacon:codex/c newer-field\nperson line\n"+ got := SetLinkURLs(note, map[string]string{"codex/a": "https://beacon.sh/s/1", "codex/b": "https://beacon.sh/s/2", "codex/c": "https://beacon.sh/s/3", "codex/x": "https://evil.example/"})+ want := "beacon:codex/a https://beacon.sh/s/1\nbeacon:codex/b https://beacon.sh/s/old\nbeacon:codex/c newer-field\nperson line\n"+ if got != want {+ t.Fatalf("SetLinkURLs = %q, want %q", got, want)+ }+ links := ParseNote("beacon:codex/a\nbeacon:codex/a https://beacon.sh/s/1\n")+ if len(links) != 1 || links[0].URL != "https://beacon.sh/s/1" {+ t.Fatalf("ParseNote = %+v", links)+ }+}diff --git a/cli/beacon/internal/gitlink/notes_test.go b/cli/beacon/internal/gitlink/notes_test.goindex 292acbbd..42a8c9d0 100644--- a/cli/beacon/internal/gitlink/notes_test.go+++ b/cli/beacon/internal/gitlink/notes_test.go@@ -181,17 +181,17 @@ func TestAddLinksCreatesMergesAndIsIdempotent(t *testing.T) {if note, err := ReadNote(ctx, g, sha); err != nil || note != "" {t.Fatalf("fresh repo note %q, %v", note, err)}- changed, err := AddLinks(ctx, g, sha, []Link{{"codex", "s1"}})+ changed, err := AddLinks(ctx, g, sha, []Link{{Harness: "codex", SessionID: "s1"}})if err != nil || !changed {t.Fatalf("first add: %v %v", changed, err)}// A person's own note line on the same commit survives Beacon's update.r.git("notes", "--ref="+NotesRef, "append", "-m", "Reviewed-by: someone", sha)- changed, err = AddLinks(ctx, g, sha, []Link{{"codex", "s1"}, {"claude_code", "s2"}})+ changed, err = AddLinks(ctx, g, sha, []Link{{Harness: "codex", SessionID: "s1"}, {Harness: "claude_code", SessionID: "s2"}})if err != nil || !changed {t.Fatalf("second add: %v %v", changed, err)}- changed, err = AddLinks(ctx, g, sha, []Link{{"claude_code", "s2"}})+ changed, err = AddLinks(ctx, g, sha, []Link{{Harness: "claude_code", SessionID: "s2"}})if err != nil || changed {t.Fatalf("repeat add changed=%v err=%v", changed, err)}@@ -203,7 +203,7 @@ func TestAddLinksCreatesMergesAndIsIdempotent(t *testing.T) {if refs := r.git("for-each-ref", "--format=%(refname)", "refs/notes/"); refs != NotesRef {t.Fatalf("leftover refs:\n%s", refs)}- if changed, err := AddLinks(ctx, g, sha, []Link{{"Bad Harness", "x"}}); err != nil || changed {+ if changed, err := AddLinks(ctx, g, sha, []Link{{Harness: "Bad Harness", SessionID: "x"}}); err != nil || changed {t.Fatalf("invalid links must be ignored: %v %v", changed, err)}}@@ -228,7 +228,7 @@ func TestAddLinksConcurrentWritersLoseNothing(t *testing.T) {// Retries are bounded, so a writer may legitimately give up under this much// contention; it must then say so rather than drop the link silently.for attempt := 0; attempt < 10; attempt++ {- _, err := AddLinks(ctx, g, sha, []Link{{"codex", fmt.Sprint("w", w)}})+ _, err := AddLinks(ctx, g, sha, []Link{{Harness: "codex", SessionID: fmt.Sprint("w", w)}})if err == nil {return}@@ -279,10 +279,10 @@ func TestListLinked(t *testing.T) {r.commitAt("second (unlinked)", t0.Add(time.Minute))r.write("a", "3")third := r.commitAt("third", t0.Add(2*time.Minute))- if _, err := AddLinks(ctx, g, first, []Link{{"cursor", "c1"}}); err != nil {+ if _, err := AddLinks(ctx, g, first, []Link{{Harness: "cursor", SessionID: "c1"}}); err != nil {t.Fatal(err)}- if _, err := AddLinks(ctx, g, third, []Link{{"codex", "x"}, {"claude_code", "y"}}); err != nil {+ if _, err := AddLinks(ctx, g, third, []Link{{Harness: "codex", SessionID: "x"}, {Harness: "claude_code", SessionID: "y"}}); err != nil {t.Fatal(err)}// A note on the ref that is not Beacon's is not a linked commit.diff --git a/cli/beacon/internal/gitlink/share.go b/cli/beacon/internal/gitlink/share.goindex 9b1e2161..41cdea4a 100644--- a/cli/beacon/internal/gitlink/share.go+++ b/cli/beacon/internal/gitlink/share.go@@ -265,3 +265,104 @@ func TrackingRefs(ctx context.Context, g Git) ([]string, error) {}return refs, nil}++// Git config keys recording `beacon git setup --share-sessions`. They live in the repository's own+// config (--local), so the choice is per clone and never travels with a push.+const (+ ShareSessionsKey = "beacon.shareSessions"+ ShareVisibilityKey = "beacon.shareVisibility"+)++// ShareSessionsConfig reports whether pushes share the sessions linked to the pushed commits, and+// with which visibility new traces are created.+func ShareSessionsConfig(ctx context.Context, repo Repo) (enabled bool, visibility string) {+ value, err := repo.Git.Run(ctx, nil, "config", "--local", "--type=bool", "--get", ShareSessionsKey)+ if err != nil || strings.TrimSpace(value) != "true" {+ return false, ""+ }+ visibility, _ = repo.Git.Run(ctx, nil, "config", "--local", "--get", ShareVisibilityKey)+ return true, strings.TrimSpace(visibility)+}++// SetShareSessions records (or, with enabled false, removes) the --share-sessions choice.+func SetShareSessions(ctx context.Context, repo Repo, enabled bool, visibility string) error {+ if !enabled {+ for _, key := range []string{ShareSessionsKey, ShareVisibilityKey} {+ if _, err := repo.Git.Run(ctx, nil, "config", "--local", "--unset-all", key); err != nil {+ var gitErr *GitError+ if !errors.As(err, &gitErr) {+ return err+ }+ }+ }+ return nil+ }+ if _, err := repo.Git.Run(ctx, nil, "config", "--local", ShareSessionsKey, "true"); err != nil {+ return err+ }+ if visibility == "" {+ _, err := repo.Git.Run(ctx, nil, "config", "--local", "--unset-all", ShareVisibilityKey)+ var gitErr *GitError+ if err != nil && !errors.As(err, &gitErr) {+ return err+ }+ return nil+ }+ _, err := repo.Git.Run(ctx, nil, "config", "--local", ShareVisibilityKey, visibility)+ return err+}++// PushedCommits lists the commits a pre-push hook's stdin says are being pushed: for each+// `<local-ref> <local-sha> <remote-ref> <remote-sha>` line, the commits reachable from the local+// sha and not from the remote sha (or, for a new remote branch, from any of the remote's+// tracking branches when remote is a configured remote). Deletions push nothing. At most limit+// commits, newest first.+func PushedCommits(ctx context.Context, repo Repo, remote string, stdin string, limit int) ([]string, error) {+ if limit <= 0 {+ limit = 100+ }+ named := isRemote(ctx, repo, remote)+ seen := map[string]bool{}+ var out []string+ for _, line := range strings.Split(stdin, "\n") {+ fields := strings.Fields(line)+ if len(fields) != 4 || !isSHA(fields[1]) || !isSHA(fields[3]) || isZeroSHA(fields[1]) {+ continue+ }+ args := []string{"rev-list", "--max-count=" + strconv.Itoa(limit), fields[1], "--not"}+ switch {+ case !isZeroSHA(fields[3]):+ args = append(args, fields[3])+ case named:+ args = append(args, "--remotes="+remote)+ }+ list, err := repo.Git.Run(ctx, nil, args...)+ if err != nil {+ return out, err+ }+ for _, sha := range strings.Fields(list) {+ if !seen[sha] {+ seen[sha] = true+ out = append(out, sha)+ if len(out) >= limit {+ return out, nil+ }+ }+ }+ }+ return out, nil+}++func isSHA(s string) bool {+ if len(s) != 40 && len(s) != 64 {+ return false+ }+ for _, r := range s {+ if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'f') {+ return false+ }+ }+ return true+}++func isZeroSHA(s string) bool { return strings.Trim(s, "0") == "" }diff --git a/cli/beacon/internal/gitlink/share_test.go b/cli/beacon/internal/gitlink/share_test.goindex cd70814d..e918f472 100644--- a/cli/beacon/internal/gitlink/share_test.go+++ b/cli/beacon/internal/gitlink/share_test.go@@ -49,10 +49,10 @@ func TestPushNotesMergesTeammatesInsteadOfOverwriting(t *testing.T) {tm := newTeam(t)ctx := context.Background()alice, bob := tm.alice.open(), tm.bob.open()- if _, err := AddLinks(ctx, alice.Git, tm.first, []Link{{"codex_cli", "alice"}}); err != nil {+ if _, err := AddLinks(ctx, alice.Git, tm.first, []Link{{Harness: "codex_cli", SessionID: "alice"}}); err != nil {t.Fatal(err)}- if _, err := AddLinks(ctx, bob.Git, tm.first, []Link{{"cursor", "bob"}}); err != nil {+ if _, err := AddLinks(ctx, bob.Git, tm.first, []Link{{Harness: "cursor", SessionID: "bob"}}); err != nil {t.Fatal(err)}res, err := PushNotes(ctx, alice, "origin")@@ -98,7 +98,7 @@ func TestPushNotesEdgeCases(t *testing.T) {t.Fatalf("fetch from a remote without links: %v %v", found, err)}// A push to a URL rather than a named remote uses a throwaway incoming ref.- if _, err := AddLinks(ctx, alice.Git, tm.first, []Link{{"codex_cli", "a"}}); err != nil {+ if _, err := AddLinks(ctx, alice.Git, tm.first, []Link{{Harness: "codex_cli", SessionID: "a"}}); err != nil {t.Fatal(err)}if res, err := PushNotes(ctx, alice, tm.remote); err != nil || !res.Pushed {@@ -117,14 +117,14 @@ func TestFetchKeepsLocalLinksAndListsTeammates(t *testing.T) {tm := newTeam(t)ctx := context.Background()alice, bob := tm.alice.open(), tm.bob.open()- if _, err := AddLinks(ctx, alice.Git, tm.first, []Link{{"codex_cli", "alice"}}); err != nil {+ if _, err := AddLinks(ctx, alice.Git, tm.first, []Link{{Harness: "codex_cli", SessionID: "alice"}}); err != nil {t.Fatal(err)}if _, err := PushNotes(ctx, alice, "origin"); err != nil {t.Fatal(err)}// Bob has an unpushed link of his own on the same commit.- if _, err := AddLinks(ctx, bob.Git, tm.first, []Link{{"cursor", "bob"}}); err != nil {+ if _, err := AddLinks(ctx, bob.Git, tm.first, []Link{{Harness: "cursor", SessionID: "bob"}}); err != nil {t.Fatal(err)}if added, err := ConfigureFetch(ctx, bob, []string{"origin"}); err != nil || !reflect.DeepEqual(added, []string{"origin"}) {@@ -172,7 +172,7 @@ func TestMergeNotesFromIntoEmptyAndUpToDate(t *testing.T) {tm := newTeam(t)ctx := context.Background()alice, bob := tm.alice.open(), tm.bob.open()- if _, err := AddLinks(ctx, alice.Git, tm.first, []Link{{"codex_cli", "alice"}}); err != nil {+ if _, err := AddLinks(ctx, alice.Git, tm.first, []Link{{Harness: "codex_cli", SessionID: "alice"}}); err != nil {t.Fatal(err)}if _, err := PushNotes(ctx, alice, "origin"); err != nil {diff --git a/docs/cli/git.mdx b/docs/cli/git.mdxindex 1507231c..2c3f9cd6 100644--- a/docs/cli/git.mdx+++ b/docs/cli/git.mdx@@ -62,6 +62,9 @@ Hooks live in the repository's shared hooks directory, so one `setup` covers eve|------|-------------|| `--hooks-path` | Install into the `core.hooksPath` directory when one is set (see below) || `--share-notes` | Share links with remotes (see [Sharing links with a team](#sharing-links-with-a-team)). `--share-notes=false` turns sharing off; without the flag, `setup` leaves it as it is |+| `--share-sessions` | Also share the sessions linked to pushed commits to beacon.sh during each push (see [Sharing sessions on push](#sharing-sessions-on-push)). Implies `--share-notes`; `--share-sessions=false`, `--share-notes=false` and `remove` turn it off |+| `--share-visibility <level>` | With `--share-sessions`, the visibility of new traces: `direct` (default), `private` or `public` |+| `--yes` | With `--share-visibility public`, set it up without asking || `-C`, `--cwd <dir>` | Repository to operate on || `--json` | Print what was installed as JSON |@@ -107,7 +110,34 @@ beacon git notes push # the branch's remote, or originbeacon git notes fetch upstream # read another remote's links```-A note holds only `beacon:<harness>/<session-id>` lines, so sharing a link shares that a session produced the commit, not what happened in it. The session itself stays in the runtime log of the machine that ran it.+A note holds only `beacon:<harness>/<session-id>` lines, optionally followed by the session's share URL, so sharing a link shares that a session produced the commit (and, when the session was shared, where its trace is), not what happened in it. The session itself stays in the runtime log of the machine that ran it.++## Share URLs in notes++When a linked session has been shared with [`beacon share`](/cli/share), its note line carries the trace's link after the session:++```text+beacon:claude_code/5f0c1d2e-aaaa-4bbb-8ccc-000000000001 https://beacon.sh/s/k3x7q9m2a8c4d1e5f6g7h8j9+```++The post-commit hook and `beacon git link` take the URL from the `session.shared` event `beacon share` writes in the runtime log, so they still never touch the network. Only an `https` URL on `beacon.sh`, or on the Beacon service the CLI is configured for (`BEACON_AUTH_URL`, or the service you signed in to), is written or shown: a note can come from anyone who pushes to the remote, so a URL on any other host is ignored and the link is shown without it. `beacon git notes` prints the URL after the session, and `--json` includes it as `url`.++## Sharing sessions on push++```bash+beacon git setup --share-sessions # new traces are direct (link only)+beacon git setup --share-sessions --share-visibility private+```++With `--share-sessions`, the pre-push hook also shares the sessions linked to the commits being pushed that have no share URL in their note yet, then writes their URLs into the notes before pushing `refs/notes/beacon`. A session already shared from this machine only gets its URL written. A session this machine does not have (a teammate's) is skipped. It is the same upload as [`beacon share`](/cli/share#what-is-uploaded), with the same redaction, and an existing trace keeps its visibility.++- It runs only during a push you started, and reads at most 100 pushed commits and shares at most 10 sessions per push.+- It uses your `beacon login` sign-in (with `traces:write`) or `BEACON_API_KEY`. Without either it shares nothing and prints nothing.+- It shares within the hook's ten seconds, keeping three of them for pushing the notes ref, and never fails the push; a failure prints one line.+- `public` lists every session linked to a pushed commit in Discover, so `setup` asks first, and without a terminal needs `--yes`.+- The choice is stored in the repository's own config (`beacon.shareSessions`, `beacon.shareVisibility`), so it applies to this clone only. `BEACON_GIT_HOOKS=0 git push` skips it for one push.++A `pre-push` hook installed by an older Beacon does not pass git's list of pushed refs to Beacon; run `beacon git setup` again to refresh it.## `beacon git remove`@@ -153,7 +183,7 @@ beacon git notes origin/main --json|------|-------------|| `--limit <n>` | Number of commits to walk (default 20); commits without links are skipped. Links fetched from remotes are included || `-C`, `--cwd <dir>` | Repository to operate on |-| `--json` | Print commits and their links as JSON |+| `--json` | Print commits and their links (with `url` when a link carries a share URL) as JSON |## Runtime log events@@ -194,10 +224,10 @@ match: >Links live under `refs/notes/beacon`, one per line:```text-beacon:<harness>/<session-id>+beacon:<harness>/<session-id> [<share-url>]```-`<harness>` is Beacon's canonical harness name (`claude_code`, `codex_cli`, `cursor`, …). A session id has no whitespace, no control or non-ASCII characters, and at most 256 characters. Readers ignore anything after whitespace on a link line, which is reserved for later fields, and ignore lines that do not start with `beacon:`.+`<harness>` is Beacon's canonical harness name (`claude_code`, `codex_cli`, `cursor`, …). A session id has no whitespace, no control or non-ASCII characters, and at most 256 characters. The first field after whitespace is the session's [share URL](#share-urls-in-notes) when it is an allowed `https` URL (at most 512 characters); anything else after whitespace is reserved for later fields and ignored. Lines that do not start with `beacon:` are ignored. When the same link appears with and without a URL (two people's notes merged), the line with the URL is kept.Beacon updates the note with a compare-and-swap on the notes ref, so two commits made at the same moment in two worktrees of one repository never lose each other's links.