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
Share commit links with teammates, opt-in
Claude352b6369e37a
diff --git a/CLAUDE.md b/CLAUDE.mdindex 1b55f8dd..f3aac908 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -66,7 +66,7 @@ Supported runtime surfaces today:- Token usage and runtime-reported cost capture across spans, logs, and metric datapoints, normalized into `gen_ai.usage`, with attribution rollups served by the dashboard token view (`/api/tokens`) and the `beacon token-usage` report command for local and CI logs.- 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.-- 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.+- 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.- 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`.Current non-goals unless explicitly requested:diff --git a/cli/beacon/cmd/git_hooks.go b/cli/beacon/cmd/git_hooks.goindex d36bebff..6dfde1d0 100644--- a/cli/beacon/cmd/git_hooks.go+++ b/cli/beacon/cmd/git_hooks.go@@ -79,6 +79,7 @@ var gitHookPostRewriteCmd = &cobra.Command{var gitSetupOpts struct {allowHooksPath bool+ shareNotes bool}func runGitSetup(cmd *cobra.Command, _ []string) error {@@ -87,10 +88,15 @@ func runGitSetup(cmd *cobra.Command, _ []string) error {if err != nil {return err}- result, err := gitlink.InstallHooks(ctx, repo, gitlink.InstallOptions{+ opts := gitlink.InstallOptions{BeaconPath: beaconExecutable(),AllowHooksPath: gitSetupOpts.allowHooksPath,- })+ }+ if cmd.Flags().Changed("share-notes") {+ share := gitSetupOpts.shareNotes+ opts.ShareNotes = &share+ }+ result, err := gitlink.InstallHooks(ctx, repo, opts)out := cmd.OutOrStdout()if err != nil {switch {@@ -112,6 +118,15 @@ func runGitSetup(cmd *cobra.Command, _ []string) error {if result.RewriteRefSet {fmt.Fprintf(out, "set notes.rewriteRef = %s\n", gitlink.NotesRef)}+ for _, remote := range result.FetchAdded {+ fmt.Fprintf(out, "set remote.%s.fetch += %s\n", remote, gitlink.FetchRefspec(remote))+ }+ for _, remote := range result.FetchRemoved {+ fmt.Fprintf(out, "unset remote.%s.fetch %s\n", remote, gitlink.FetchRefspec(remote))+ }+ 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)+ }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@@ -137,6 +152,9 @@ func runGitRemove(cmd *cobra.Command, _ []string) error {if result.RewriteRefRemoved {fmt.Fprintf(out, "unset notes.rewriteRef = %s\n", gitlink.NotesRef)}+ for _, remote := range result.FetchRemoved {+ fmt.Fprintf(out, "unset remote.%s.fetch %s\n", remote, gitlink.FetchRefspec(remote))+ }fmt.Fprintf(out, "Links already written stay in %s.\n", gitlink.NotesRef)return nil}@@ -180,6 +198,14 @@ func runGitStatus(cmd *cobra.Command, _ []string) error {rewrite = "set"}fmt.Fprintf(out, "rewriteRef %s\n", rewrite)+ sharing := "off (`beacon git setup --share-notes` turns it on)"+ if status.Sharing {+ sharing = "on: pushes share links"+ }+ fmt.Fprintf(out, "sharing %s\n", sharing)+ for _, remote := range status.FetchRemotes {+ fmt.Fprintf(out, " fetches from %s bring its links\n", remote)+ }return nil}@@ -276,4 +302,5 @@ 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.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.gonew file mode 100644index 00000000..dd2ad8ef--- /dev/null+++ b/cli/beacon/cmd/git_share.go@@ -0,0 +1,147 @@+package cmd++import (+ "context"+ "fmt"+ "os"+ "time"++ "github.com/spf13/cobra"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/gitlink"+)++// gitShareBudget bounds the pre-push hook's own push of the notes ref. It is network time, so it+// is longer than the post-commit budget, and it still ends well before a person would think their+// push had hung.+var gitShareBudget = 10 * time.Second++var gitNotesPushCmd = &cobra.Command{+ Use: "push [<remote>]",+ Short: "Share this repository's commit links with a remote (default the branch's remote, or origin)",+ Long: `Share this repository's commit links with a remote.++Fetches the remote's ` + gitlink.NotesRef + `, merges it with the local one (keeping every line of both), and+pushes the result. Nothing but the notes ref is pushed, and the repository's own pre-push hooks do not+run for it.`,+ Args: cobra.MaximumNArgs(1),+ SilenceUsage: true,+ RunE: runGitNotesPush,+}++var gitNotesFetchCmd = &cobra.Command{+ Use: "fetch [<remote>]",+ Short: "Fetch a remote's commit links so `beacon git notes` shows them",+ Long: `Fetch a remote's commit links so ` + "`beacon git notes`" + ` shows them.++The links land in ` + gitlink.RemoteNotesPrefix + `<remote>, a read-only copy that ` + "`beacon git notes`" + ` reads+alongside the local links. The local ` + gitlink.NotesRef + ` is not changed; ` + "`beacon git notes push`" + ` merges.`,+ Args: cobra.MaximumNArgs(1),+ SilenceUsage: true,+ RunE: runGitNotesFetch,+}++var gitHookPrePushCmd = &cobra.Command{+ Use: "pre-push <remote> [<url>]",+ Short: "Share commit links with the remote being pushed to (called by the pre-push hook)",+ Args: cobra.RangeArgs(1, 2),+ SilenceUsage: true,+ RunE: runGitHookPrePush,+}++func defaultRemote(ctx context.Context, repo gitlink.Repo) string {+ if branch, err := repo.Git.Run(ctx, nil, "symbolic-ref", "--quiet", "--short", "HEAD"); err == nil && branch != "" {+ if remote, err := repo.Git.Run(ctx, nil, "config", "--get", "branch."+branch+".remote"); err == nil && remote != "" && remote != "." {+ return remote+ }+ }+ return "origin"+}++func runGitNotesPush(cmd *cobra.Command, args []string) error {+ ctx := cmd.Context()+ repo, err := gitRepo(ctx)+ if err != nil {+ return err+ }+ remote := defaultRemote(ctx, repo)+ if len(args) == 1 {+ remote = args[0]+ }+ result, err := gitlink.PushNotes(ctx, repo, remote)+ if err != nil {+ return fmt.Errorf("share links with %s: %w", remote, err)+ }+ out := cmd.OutOrStdout()+ if gitOpts.jsonOutput {+ return writeIndentedJSON(out, result)+ }+ switch {+ case !result.Pushed:+ fmt.Fprintln(out, "No commit links here to share.")+ case result.Merged:+ fmt.Fprintf(out, "Merged %s's links and pushed %s to %s.\n", remote, gitlink.NotesRef, remote)+ default:+ fmt.Fprintf(out, "Pushed %s to %s.\n", gitlink.NotesRef, remote)+ }+ return nil+}++func runGitNotesFetch(cmd *cobra.Command, args []string) error {+ ctx := cmd.Context()+ repo, err := gitRepo(ctx)+ if err != nil {+ return err+ }+ remote := defaultRemote(ctx, repo)+ if len(args) == 1 {+ remote = args[0]+ }+ found, err := gitlink.FetchNotes(ctx, repo, remote)+ if err != nil {+ return fmt.Errorf("fetch links from %s: %w", remote, err)+ }+ out := cmd.OutOrStdout()+ if gitOpts.jsonOutput {+ return writeIndentedJSON(out, map[string]interface{}{"remote": remote, "found": found, "ref": gitlink.TrackingRef(remote)})+ }+ if !found {+ fmt.Fprintf(out, "%s has no commit links yet.\n", remote)+ return nil+ }+ fmt.Fprintf(out, "Fetched %s's links into %s.\n", remote, gitlink.TrackingRef(remote))+ return nil+}++// runGitHookPrePush is the pre-push hook. It never fails the push: sharing links is a courtesy to+// teammates, and the person's code reaching the remote matters more. A failure is one line on+// stderr, which git shows alongside its own output.+func runGitHookPrePush(cmd *cobra.Command, args []string) error {+ if os.Getenv(gitlink.DisableEnv) == "0" {+ return nil+ }+ ctx, cancel := context.WithTimeout(cmd.Context(), gitShareBudget)+ defer cancel()+ repo, err := gitRepo(ctx)+ if err != nil {+ return nil+ }+ // 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")+ 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))+ }+ return nil+}++func init() {+ gitNotesCmd.AddCommand(gitNotesPushCmd, gitNotesFetchCmd)+ gitHookCmd.AddCommand(gitHookPrePushCmd)+ for _, c := range []*cobra.Command{gitNotesPushCmd, gitNotesFetchCmd, gitHookPrePushCmd} {+ c.Flags().StringVarP(&gitOpts.dir, "cwd", "C", "", "Repository to operate on (default the current directory)")+ if c != gitHookPrePushCmd {+ c.Flags().BoolVar(&gitOpts.jsonOutput, "json", false, "Print the result as JSON")+ }+ }+}diff --git a/cli/beacon/cmd/git_share_test.go b/cli/beacon/cmd/git_share_test.gonew file mode 100644index 00000000..9af2fdda--- /dev/null+++ b/cli/beacon/cmd/git_share_test.go@@ -0,0 +1,114 @@+package cmd++import (+ "bytes"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/gitlink"+)++// gitCommandTeam returns a repository with an origin remote holding one commit.+func gitCommandTeam(t *testing.T) (root, remote string) {+ t.Helper()+ root = gitCommandRepo(t)+ remote = filepath.Join(t.TempDir(), "remote.git")+ mustGit(t, root, "init", "-q", "--bare", "-b", "main", remote)+ mustGit(t, root, "commit", "-q", "--allow-empty", "-m", "first")+ mustGit(t, root, "remote", "add", "origin", remote)+ mustGit(t, root, "push", "-q", "-u", "origin", "main")+ return root, remote+}++func TestGitNotesPushAndFetchCommands(t *testing.T) {+ root, remote := gitCommandTeam(t)+ sha := mustGit(t, root, "rev-parse", "HEAD")+ out, err := runGit(t, "notes", "push", "--cwd", root)+ if err != nil || !strings.Contains(out, "No commit links here to share") {+ t.Fatalf("empty push: %v %q", err, out)+ }+ mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "add", "-m", "beacon:codex_cli/s1", sha)+ out, err = runGit(t, "notes", "push", "--cwd", root)+ if err != nil || !strings.Contains(out, "Pushed refs/notes/beacon to origin") {+ t.Fatalf("push: %v %q", err, out)+ }+ if got := mustGit(t, remote, "notes", "--ref="+gitlink.NotesRef, "show", sha); got != "beacon:codex_cli/s1" {+ t.Fatalf("remote note %q", got)+ }++ other := filepath.Join(t.TempDir(), "other")+ mustGit(t, root, "clone", "-q", remote, other)+ out, err = runGit(t, "notes", "fetch", "--cwd", other)+ if err != nil || !strings.Contains(out, "Fetched origin's links into refs/notes/beacon-remotes/origin") {+ t.Fatalf("fetch: %v %q", err, out)+ }+ out, err = runGit(t, "notes", "--cwd", other)+ if err != nil || !strings.Contains(out, "codex_cli/s1") {+ t.Fatalf("notes after fetch: %v %q", err, out)+ }+ // A revision argument still means a revision, not a subcommand.+ if out, err := runGit(t, "notes", "--cwd", other, "HEAD"); err != nil || !strings.Contains(out, "codex_cli/s1") {+ t.Fatalf("notes HEAD: %v %q", err, out)+ }+ out, err = runGit(t, "notes", "fetch", "--cwd", other, "nowhere")+ if err == nil || !strings.Contains(err.Error(), "fetch links from nowhere") {+ t.Fatalf("fetch from an unknown remote: %v %q", err, out)+ }+}++func TestGitHookPrePushSharesAndNeverFails(t *testing.T) {+ root, remote := gitCommandTeam(t)+ sha := mustGit(t, root, "rev-parse", "HEAD")+ mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "add", "-m", "beacon:cursor/c1", sha)+ if out, err := runGit(t, "hook", "pre-push", "--cwd", root, "origin", remote); err != nil || out != "" {+ t.Fatalf("pre-push: %v %q", err, out)+ }+ if got := mustGit(t, remote, "notes", "--ref="+gitlink.NotesRef, "show", sha); got != "beacon:cursor/c1" {+ t.Fatalf("remote note %q", got)+ }+ // An unreachable remote: one warning line on stderr, and still no error for git to see.+ var stderr bytes.Buffer+ rootCmd.SetErr(&stderr)+ missing := filepath.Join(t.TempDir(), "gone.git")+ if _, err := runGitStderr(t, &stderr, "hook", "pre-push", "--cwd", root, missing, missing); err != nil {+ t.Fatalf("pre-push must not fail: %v", err)+ }+ if got := stderr.String(); !strings.HasPrefix(got, "beacon: commit links were not shared with "+missing) || strings.Count(got, "\n") != 1 {+ t.Fatalf("stderr %q", got)+ }+ t.Setenv(gitlink.DisableEnv, "0")+ stderr.Reset()+ if _, err := runGitStderr(t, &stderr, "hook", "pre-push", "--cwd", root, missing); err != nil || stderr.Len() != 0 {+ t.Fatalf("disabled: %v %q", err, stderr.String())+ }+}++func TestGitSetupShareNotesFlag(t *testing.T) {+ root, _ := gitCommandTeam(t)+ out, err := runGit(t, "setup", "--cwd", root, "--share-notes")+ if err != nil || !strings.Contains(out, "remote.origin.fetch += +refs/notes/beacon:refs/notes/beacon-remotes/origin") || !strings.Contains(out, "Commit links are shared") {+ t.Fatalf("setup --share-notes: %v\n%s", err, out)+ }+ if _, err := os.Stat(filepath.Join(root, ".git", "hooks", "beacon-pre-push")); err != nil {+ t.Fatal(err)+ }+ out, _ = runGit(t, "status", "--cwd", root)+ if !strings.Contains(out, "sharing on") || !strings.Contains(out, "fetches from origin bring its links") {+ t.Fatalf("status:\n%s", out)+ }+ if _, err := runGit(t, "setup", "--cwd", root); err != nil {+ t.Fatal(err)+ }+ if out, _ := runGit(t, "status", "--cwd", root); !strings.Contains(out, "sharing on") {+ t.Fatalf("a plain re-run changed sharing:\n%s", out)+ }+ out, err = runGit(t, "setup", "--cwd", root, "--share-notes=false")+ if err != nil || !strings.Contains(out, "unset remote.origin.fetch") {+ t.Fatalf("setup --share-notes=false: %v\n%s", err, out)+ }+ if out, _ := runGit(t, "status", "--cwd", root); !strings.Contains(out, "sharing off") {+ t.Fatalf("status after off:\n%s", out)+ }+}diff --git a/cli/beacon/cmd/git_test.go b/cli/beacon/cmd/git_test.goindex 2a09aaff..e5226f8e 100644--- a/cli/beacon/cmd/git_test.go+++ b/cli/beacon/cmd/git_test.go@@ -23,6 +23,7 @@ func runGit(t *testing.T, args ...string) (string, error) {t.Helper()gitOpts = gitOptions{}gitSetupOpts.allowHooksPath = false+ gitSetupOpts.shareNotes = falsevar reset func(*cobra.Command)reset = func(c *cobra.Command) {c.Flags().VisitAll(func(f *pflag.Flag) {@@ -185,3 +186,31 @@ func TestPrintGitLinkResultLabelsTheLimit(t *testing.T) {}}}++// runGitStderr is runGit with stderr captured into w.+func runGitStderr(t *testing.T, w *bytes.Buffer, args ...string) (string, error) {+ t.Helper()+ var stdout bytes.Buffer+ gitOpts = gitOptions{}+ var reset func(*cobra.Command)+ reset = func(c *cobra.Command) {+ c.Flags().VisitAll(func(f *pflag.Flag) {+ _ = f.Value.Set(f.DefValue)+ f.Changed = false+ })+ for _, sub := range c.Commands() {+ reset(sub)+ }+ }+ reset(gitCmd)+ rootCmd.SetOut(&stdout)+ rootCmd.SetErr(w)+ rootCmd.SetArgs(append([]string{"git"}, args...))+ t.Cleanup(func() {+ rootCmd.SetOut(nil)+ rootCmd.SetErr(nil)+ rootCmd.SetArgs(nil)+ })+ err := rootCmd.Execute()+ return stdout.String(), err+}diff --git a/cli/beacon/internal/gitlink/git.go b/cli/beacon/internal/gitlink/git.goindex 63873c23..144ce18a 100644--- a/cli/beacon/internal/gitlink/git.go+++ b/cli/beacon/internal/gitlink/git.go@@ -26,6 +26,14 @@ type Git struct {// Env, when set, replaces the process environment for every git invocation. Tests use it to// keep the caller's global git configuration out of the repository under test.Env []string+ // ExtraEnv is added to the environment (Env, or the process's own) for every invocation.+ ExtraEnv []string+}++// WithExtraEnv returns g with vars added to every invocation's environment.+func (g Git) WithExtraEnv(vars ...string) Git {+ g.ExtraEnv = append(append([]string{}, g.ExtraEnv...), vars...)+ return g}// ErrNotRepository is returned when Dir is not inside a git work tree.@@ -49,6 +57,13 @@ func (g Git) run(ctx context.Context, stdin []byte, args ...string) ([]byte, errif g.Env != nil {cmd.Env = g.Env}+ if len(g.ExtraEnv) > 0 {+ base := cmd.Env+ if base == nil {+ base = os.Environ()+ }+ cmd.Env = append(append([]string{}, base...), g.ExtraEnv...)+ }if stdin != nil {cmd.Stdin = bytes.NewReader(stdin)}@@ -88,6 +103,25 @@ func (e *GitError) Error() string {func (e *GitError) Unwrap() error { return e.Err }+// ErrorSummary is err in one line for a person: for a failed git invocation, git's own first+// complaint without its "fatal:"/"error:" prefix, rather than the command line and every hint.+func ErrorSummary(err error) string {+ var gitErr *GitError+ if !errors.As(err, &gitErr) {+ return err.Error()+ }+ for _, line := range strings.Split(gitErr.Message, "\n") {+ line = strings.TrimSpace(line)+ for _, prefix := range []string{"fatal:", "error:", "remote:"} {+ line = strings.TrimSpace(strings.TrimPrefix(line, prefix))+ }+ if line != "" && !strings.HasPrefix(line, "hint:") && !strings.HasPrefix(line, "To ") {+ return line+ }+ }+ return gitErr.Err.Error()+}+// Repo is a resolved repository: the top of the work tree, the per-worktree git directory, and the// common directory worktrees share (where hooks and refs live).type Repo struct {@@ -124,7 +158,7 @@ func OpenRepo(ctx context.Context, g Git) (Repo, error) {common = filepath.Join(base, common)}return Repo{- Git: Git{Dir: root, Env: g.Env},+ Git: Git{Dir: root, Env: g.Env, ExtraEnv: g.ExtraEnv},Root: root,GitDir: gitDir,CommonDir: filepath.Clean(common),diff --git a/cli/beacon/internal/gitlink/hooks.go b/cli/beacon/internal/gitlink/hooks.goindex b899205b..26ffbd8a 100644--- a/cli/beacon/internal/gitlink/hooks.go+++ b/cli/beacon/internal/gitlink/hooks.go@@ -27,6 +27,14 @@ const (// the old commit's note across (see NormalizeNote).var ManagedHooks = []string{"post-commit", "post-rewrite"}+// ShareHook is the hook `beacon git setup --share-notes` adds. It is off by default because it is+// the one Beacon hook that reaches the network: during a push the person started, it pushes+// refs/notes/beacon to the same remote.+const ShareHook = "pre-push"++// allHooks is every hook Beacon may have installed, which is what remove and status look at.+var allHooks = append(append([]string{}, ManagedHooks...), ShareHook)+// ErrHooksPathSet is returned by InstallHooks when core.hooksPath points git somewhere other than// the repository's own hooks directory -- usually a hook manager's tracked directory -- and the// caller did not ask to write there.@@ -68,6 +76,10 @@ type InstallOptions struct {BeaconPath string// AllowHooksPath installs into core.hooksPath's directory when it is set.AllowHooksPath bool+ // ShareNotes, when set, turns sharing on (true) or off (false): the pre-push hook and a fetch+ // refspec on every remote. Nil leaves sharing as it is, so re-running setup to repair an+ // install does not change it.+ ShareNotes *bool}// HookReport is what installing or removing did to one hook.@@ -85,6 +97,9 @@ type InstallResult struct {Hooks HooksLocation `json:"hooks"`Reports []HookReport `json:"reports"`RewriteRefSet bool `json:"rewrite_ref_set"`+ // FetchAdded and FetchRemoved are the remotes whose fetch refspec setup changed.+ FetchAdded []string `json:"fetch_added,omitempty"`+ FetchRemoved []string `json:"fetch_removed,omitempty"`}// InstallHooks installs Beacon's hooks. It is idempotent: a second run rewrites the scripts and@@ -101,13 +116,19 @@ func InstallHooks(ctx context.Context, repo Repo, opts InstallOptions) (InstallRif err := os.MkdirAll(loc.Dir, 0o755); err != nil {return result, err}+ hooks := append([]string{}, ManagedHooks...)+ if opts.ShareNotes != nil && *opts.ShareNotes {+ hooks = append(hooks, ShareHook)+ } else if opts.ShareNotes == nil && hookInstalled(loc.Dir, ShareHook) {+ hooks = append(hooks, ShareHook) // refresh the script along with the others+ }// Check every hook before writing any, so a refusal leaves the repository as it was.- for _, hook := range ManagedHooks {+ for _, hook := range hooks {if err := checkHookEditable(filepath.Join(loc.Dir, hook)); err != nil {return result, fmt.Errorf("%s: %w", filepath.Join(loc.Dir, hook), err)}}- for _, hook := range ManagedHooks {+ for _, hook := range hooks {report, err := installHook(loc.Dir, hook, opts.BeaconPath)if err != nil {return result, err@@ -119,7 +140,36 @@ func InstallHooks(ctx context.Context, repo Repo, opts InstallOptions) (InstallRreturn result, err}result.RewriteRefSet = set- return result, nil+ if opts.ShareNotes == nil {+ return result, nil+ }+ if *opts.ShareNotes {+ remotes, err := Remotes(ctx, repo)+ if err != nil {+ return result, err+ }+ result.FetchAdded, err = ConfigureFetch(ctx, repo, remotes)+ return result, err+ }+ report, err := removeHook(loc.Dir, ShareHook)+ if err != nil {+ return result, err+ }+ if report.Action == "removed" {+ result.Reports = append(result.Reports, report)+ }+ result.FetchRemoved, err = UnconfigureFetch(ctx, repo)+ return result, err+}++func hookInstalled(dir, hook string) bool {+ data, err := os.ReadFile(filepath.Join(dir, hook))+ return err == nil && strings.Contains(string(data), hookBlockStart) && fileExists(filepath.Join(dir, HookScriptPrefix+hook))+}++func fileExists(path string) bool {+ _, err := os.Stat(path)+ return err == nil}func installHook(dir, hook, beaconPath string) (HookReport, error) {@@ -227,27 +277,38 @@ 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.",}func hookScript(hook, beaconPath string) string {// post-rewrite reads the rewritten commits from stdin; the others get nothing to read.- stdin := " </dev/null"- args := ""- if hook == "post-rewrite" {+ // pre-push needs the remote git passes, 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"}return `#!/bin/sh# Beacon ` + hook + ` hook: ` + hookPurpose[hook] + `# Installed by: beacon git setup Removed by: beacon git remove-# Reads the local runtime log and writes a git note; never touches the network or fails the commit.+# ` + hookScope(hook) + `[ "${` + DisableEnv + `:-1}" = "0" ] && exit 0beacon_bin=` + shellQuote(beaconPath) + `[ -n "$beacon_bin" ] && [ -x "$beacon_bin" ] || beacon_bin="$(command -v beacon 2>/dev/null)" || exit 0-"$beacon_bin" git hook ` + hook + args + stdin + ` >/dev/null 2>&1+"$beacon_bin" git hook ` + hook + args + stdin + output + `exit 0`}+func 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 "Reads the local runtime log and writes a git note; never touches the network or fails the commit."+}+func shellQuote(s string) string {return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"}@@ -273,6 +334,32 @@ type RemoveResult struct {Hooks HooksLocation `json:"hooks"`Reports []HookReport `json:"reports"`RewriteRefRemoved bool `json:"rewrite_ref_removed"`+ FetchRemoved []string `json:"fetch_removed,omitempty"`+}++func removeHook(dir, hook string) (HookReport, error) {+ report := HookReport{Hook: hook, Path: filepath.Join(dir, hook), Script: filepath.Join(dir, HookScriptPrefix+hook), Action: "absent"}+ if err := os.Remove(report.Script); err == nil {+ report.Action = "removed"+ } else if !os.IsNotExist(err) {+ return report, err+ }+ data, err := os.ReadFile(report.Path)+ if err == nil && strings.Contains(string(data), hookBlockStart) {+ rest := removeBlock(string(data))+ if onlyShebang(rest) {+ err = os.Remove(report.Path)+ } else {+ err = writeExecutable(report.Path, rest)+ }+ if err != nil {+ return report, err+ }+ report.Action = "removed"+ } else if err != nil && !os.IsNotExist(err) {+ return report, err+ }+ return report, nil}// RemoveHooks removes Beacon's scripts and blocks. A hook left with nothing but a shebang is@@ -283,30 +370,19 @@ func RemoveHooks(ctx context.Context, repo Repo) (RemoveResult, error) {return RemoveResult{}, err}result := RemoveResult{Hooks: loc}- for _, hook := range ManagedHooks {- report := HookReport{Hook: hook, Path: filepath.Join(loc.Dir, hook), Script: filepath.Join(loc.Dir, HookScriptPrefix+hook), Action: "absent"}- if err := os.Remove(report.Script); err == nil {- report.Action = "removed"- } else if !os.IsNotExist(err) {+ for _, hook := range allHooks {+ report, err := removeHook(loc.Dir, hook)+ if err != nil {return result, err}- data, err := os.ReadFile(report.Path)- if err == nil && strings.Contains(string(data), hookBlockStart) {- rest := removeBlock(string(data))- if onlyShebang(rest) {- err = os.Remove(report.Path)- } else {- err = writeExecutable(report.Path, rest)- }- if err != nil {- return result, err- }- report.Action = "removed"- } else if err != nil && !os.IsNotExist(err) {- return result, err+ if hook == ShareHook && report.Action == "absent" {+ continue // never installed; not worth a line}result.Reports = append(result.Reports, report)}+ if result.FetchRemoved, err = UnconfigureFetch(ctx, repo); err != nil {+ return result, err+ }removed, err := removeRewriteRef(ctx, repo)if err != nil {return result, err@@ -339,16 +415,25 @@ type Status struct {Hooks HooksLocation `json:"hooks"`States []HookState `json:"states"`RewriteRef bool `json:"rewrite_ref"`+ // Sharing is true when the pre-push hook is installed; FetchRemotes are the remotes whose+ // fetches bring their links along.+ Sharing bool `json:"sharing"`+ FetchRemotes []string `json:"fetch_remotes,omitempty"`}-// Installed is true when every managed hook is installed.+// Installed is true when every managed hook is installed. Sharing is optional and not counted.func (s Status) Installed() bool {+ n := 0for _, st := range s.States {+ if st.Hook == ShareHook {+ continue+ }if !st.Installed {return false}+ n++}- return len(s.States) > 0+ return n == len(ManagedHooks)}// HookStatus reports Beacon's git integration in repo.@@ -358,7 +443,7 @@ func HookStatus(ctx context.Context, repo Repo) (Status, error) {return Status{}, err}status := Status{Hooks: loc}- for _, hook := range ManagedHooks {+ for _, hook := range allHooks {st := HookState{Hook: hook}if data, err := os.ReadFile(filepath.Join(loc.Dir, hook)); err == nil {st.BlockPresent = strings.Contains(string(data), hookBlockStart)@@ -367,8 +452,21 @@ func HookStatus(ctx context.Context, repo Repo) (Status, error) {st.ScriptExists = true}st.Installed = st.BlockPresent && st.ScriptExists+ if hook == ShareHook {+ status.Sharing = st.Installed+ if !st.BlockPresent && !st.ScriptExists {+ continue // not installed and not half-installed: nothing to report+ }+ }status.States = append(status.States, st)}+ if remotes, err := Remotes(ctx, repo); err == nil {+ for _, remote := range remotes {+ if has, err := hasFetchRefspec(ctx, repo, remote); err == nil && has {+ status.FetchRemotes = append(status.FetchRemotes, remote)+ }+ }+ }status.RewriteRef, err = hasRewriteRef(ctx, repo)return status, err}diff --git a/cli/beacon/internal/gitlink/notes.go b/cli/beacon/internal/gitlink/notes.goindex 1f98882d..4420692b 100644--- a/cli/beacon/internal/gitlink/notes.go+++ b/cli/beacon/internal/gitlink/notes.go@@ -188,7 +188,8 @@ type LinkedCommit struct {}// ListLinked walks up to limit commits reachable from rev (HEAD when empty), newest first, and-// returns those whose Beacon note names at least one session.+// returns those whose Beacon note names at least one session. Links fetched from remotes (see+// RemoteNotesPrefix) are included alongside local ones.func ListLinked(ctx context.Context, g Git, rev string, limit int) ([]LinkedCommit, error) {if rev == "" {rev = "HEAD"@@ -196,13 +197,27 @@ func ListLinked(ctx context.Context, g Git, rev string, limit int) ([]LinkedCommif limit <= 0 {limit = 20}- if exists, err := refExists(ctx, g, NotesRef); err != nil || !exists {+ args := []string{"log", "--no-notes"}+ if exists, err := refExists(ctx, g, NotesRef); err != nil {return nil, err+ } else if exists {+ args = append(args, "--notes="+NotesRef)+ }+ tracking, err := TrackingRefs(ctx, g)+ if err != nil {+ return nil, err+ }+ if len(tracking) > 0 {+ args = append(args, "--notes="+RemoteNotesPrefix+"*")+ }+ if len(args) == 2 {+ return nil, nil}// Records end in RS and fields are split by NUL, so a note or subject containing newlines- // cannot shift fields. --no-notes first clears any notes.displayRef the user configured.- out, err := g.RunRaw(ctx, "log", "--no-notes", "--notes="+NotesRef, "-n", strconv.Itoa(limit),- "--format=%H%x00%ct%x00%s%x00%N%x1e", rev, "--")+ // cannot shift fields. --no-notes first clears any notes.displayRef the user configured. With+ // several notes refs, %N holds each one's note in turn; ParseNote folds repeats.+ args = append(args, "-n", strconv.Itoa(limit), "--format=%H%x00%ct%x00%s%x00%N%x1e", rev, "--")+ out, err := g.RunRaw(ctx, args...)if err != nil {return nil, err}diff --git a/cli/beacon/internal/gitlink/share.go b/cli/beacon/internal/gitlink/share.gonew file mode 100644index 00000000..9b1e2161--- /dev/null+++ b/cli/beacon/internal/gitlink/share.go@@ -0,0 +1,267 @@+package gitlink++import (+ "context"+ "errors"+ "fmt"+ "regexp"+ "strconv"+ "strings"+)++// RemoteNotesPrefix holds a read-only copy of each remote's links: refs/notes/beacon-remotes/origin+// is origin's refs/notes/beacon as of the last fetch. Readers union it with NotesRef, so a+// teammate's links show up without ever being merged into -- or overwriting -- the local ref.+const RemoteNotesPrefix = "refs/notes/beacon-remotes/"++// incomingRefPrefix holds a one-off fetch from a remote that has no name (a push to a URL).+const incomingRefPrefix = "refs/notes/beacon-incoming/"++// TrackingRef is where remote's links are fetched to.+func TrackingRef(remote string) string { return RemoteNotesPrefix + remote }++// FetchRefspec is the refspec that makes a plain `git fetch <remote>` bring its links along. The+// destination is the tracking ref, never NotesRef: a forced fetch into NotesRef would replace+// links written here and not yet pushed.+func FetchRefspec(remote string) string { return "+" + NotesRef + ":" + TrackingRef(remote) }++// Remotes lists the repository's configured remotes.+func Remotes(ctx context.Context, repo Repo) ([]string, error) {+ out, err := repo.Git.Run(ctx, nil, "remote")+ if err != nil {+ return nil, err+ }+ var remotes []string+ for _, line := range strings.Split(out, "\n") {+ if name := strings.TrimSpace(line); name != "" {+ remotes = append(remotes, name)+ }+ }+ return remotes, nil+}++func isRemote(ctx context.Context, repo Repo, name string) bool {+ remotes, err := Remotes(ctx, repo)+ if err != nil {+ return false+ }+ for _, r := range remotes {+ if r == name {+ return true+ }+ }+ return false+}++// ConfigureFetch adds FetchRefspec to each remote that lacks it and returns the remotes changed.+func ConfigureFetch(ctx context.Context, repo Repo, remotes []string) ([]string, error) {+ var added []string+ for _, remote := range remotes {+ has, err := hasFetchRefspec(ctx, repo, remote)+ if err != nil {+ return added, err+ }+ if has {+ continue+ }+ if _, err := repo.Git.Run(ctx, nil, "config", "--local", "--add", "remote."+remote+".fetch", FetchRefspec(remote)); err != nil {+ return added, err+ }+ added = append(added, remote)+ }+ return added, nil+}++// UnconfigureFetch removes FetchRefspec from every remote and returns the remotes changed. The+// tracking refs stay: they are copies of what the remote holds, and the next fetch refreshes them.+func UnconfigureFetch(ctx context.Context, repo Repo) ([]string, error) {+ remotes, err := Remotes(ctx, repo)+ if err != nil {+ return nil, err+ }+ var removed []string+ for _, remote := range remotes {+ has, err := hasFetchRefspec(ctx, repo, remote)+ if err != nil {+ return removed, err+ }+ if !has {+ continue+ }+ pattern := "^" + regexp.QuoteMeta(FetchRefspec(remote)) + "$"+ if _, err := repo.Git.Run(ctx, nil, "config", "--local", "--unset-all", "remote."+remote+".fetch", pattern); err != nil {+ return removed, err+ }+ removed = append(removed, remote)+ }+ return removed, nil+}++func hasFetchRefspec(ctx context.Context, repo Repo, remote string) (bool, error) {+ out, err := repo.Git.Run(ctx, nil, "config", "--local", "--get-all", "remote."+remote+".fetch")+ if err != nil {+ var gitErr *GitError+ if errors.As(err, &gitErr) {+ return false, nil+ }+ return false, err+ }+ for _, line := range strings.Split(out, "\n") {+ if strings.TrimSpace(line) == FetchRefspec(remote) {+ return true, nil+ }+ }+ return false, nil+}++// FetchNotes copies remote's links into its tracking ref and reports whether the remote had any.+// remote is a remote's name; see fetchInto for a URL.+func FetchNotes(ctx context.Context, repo Repo, remote string) (bool, error) {+ return fetchInto(ctx, repo, remote, TrackingRef(remote))+}++func fetchInto(ctx context.Context, repo Repo, remote, dest string) (bool, error) {+ // --no-write-fetch-head keeps FETCH_HEAD for the person's own fetches; the empty --refmap stops+ // git also updating the remote's configured branch tracking refs.+ _, err := repo.Git.Run(ctx, nil, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--refmap=", remote, "+"+NotesRef+":"+dest)+ if err != nil {+ var gitErr *GitError+ if errors.As(err, &gitErr) && strings.Contains(strings.ToLower(gitErr.Message), "couldn't find remote ref") {+ return false, nil+ }+ return false, err+ }+ return true, nil+}++// MergeNotesFrom merges the links in ref into NotesRef and reports whether NotesRef changed. It+// uses git's cat_sort_uniq strategy, which keeps every line of both sides, and the same+// compare-and-swap as UpdateNote, so a hook linking a commit meanwhile is not lost.+func MergeNotesFrom(ctx context.Context, repo Repo, ref string) (bool, error) {+ g := repo.Git+ token, err := txToken()+ if err != nil {+ return false, err+ }+ for attempt := 1; attempt <= noteAttempts; attempt++ {+ incoming, err := resolveRef(ctx, g, ref)+ if err != nil || incoming == "" {+ return false, err+ }+ base, err := resolveRef(ctx, g, NotesRef)+ if err != nil {+ return false, err+ }+ next := incoming+ if base != "" {+ if base == incoming {+ return false, nil+ }+ next, err = mergeOnTx(ctx, g, base, ref, txRefPrefix+token+"-m"+strconv.Itoa(attempt))+ if err != nil {+ return false, err+ }+ if next == base {+ return false, nil+ }+ }+ if _, err := g.Run(ctx, nil, "update-ref", "-m", "beacon: merge shared links", NotesRef, next, base); err != nil {+ if moved, checkErr := refMoved(ctx, g, base); checkErr == nil && moved {+ continue+ }+ return false, err+ }+ return true, nil+ }+ return false, fmt.Errorf("merge into %s: %w", NotesRef, errRefMoved)+}++func mergeOnTx(ctx context.Context, g Git, base, ref, txRef string) (string, error) {+ if _, err := g.Run(ctx, nil, "update-ref", txRef, base); err != nil {+ return "", err+ }+ defer func() { _, _ = g.Run(context.Background(), nil, "update-ref", "-d", txRef) }()+ if _, err := g.Run(ctx, nil, "notes", "--ref="+txRef, "merge", "--quiet", "--strategy=cat_sort_uniq", ref); err != nil {+ return "", err+ }+ return resolveRef(ctx, g, txRef)+}++// PushResult is the outcome of PushNotes.+type PushResult struct {+ Remote string `json:"remote"`+ // Merged is true when the remote had links this repository lacked, now merged in.+ Merged bool `json:"merged"`+ // Pushed is false only when there was nothing local to push.+ Pushed bool `json:"pushed"`+}++// PushNotes shares this repository's links with remote: it fetches the remote's links, merges them+// in, and pushes NotesRef. A push rejected because someone pushed links in between is retried once+// after merging again. remote may be a remote's name or a URL.+//+// The push runs with --no-verify, so it never triggers the repository's own pre-push hooks --+// Beacon's included, which is what calls this during a person's push.+func PushNotes(ctx context.Context, repo Repo, remote string) (PushResult, error) {+ result := PushResult{Remote: remote}+ named := isRemote(ctx, repo, remote)+ var lastErr error+ for attempt := 1; attempt <= 2; attempt++ {+ merged, err := fetchAndMerge(ctx, repo, remote, named)+ if err != nil {+ return result, err+ }+ result.Merged = result.Merged || merged+ if exists, err := refExists(ctx, repo.Git, NotesRef); err != nil || !exists {+ return result, err+ }+ _, err = repo.Git.Run(ctx, nil, "push", "--quiet", "--no-verify", remote, NotesRef+":"+NotesRef)+ if err == nil {+ result.Pushed = true+ if named {+ // The remote now holds exactly what was pushed; say so without another round trip.+ if local, err := resolveRef(ctx, repo.Git, NotesRef); err == nil && local != "" {+ _, _ = repo.Git.Run(ctx, nil, "update-ref", TrackingRef(remote), local)+ }+ }+ return result, nil+ }+ if ctx.Err() != nil {+ return result, ctx.Err()+ }+ lastErr = err+ }+ return result, lastErr+}++func fetchAndMerge(ctx context.Context, repo Repo, remote string, named bool) (bool, error) {+ dest := TrackingRef(remote)+ if !named {+ token, err := txToken()+ if err != nil {+ return false, err+ }+ dest = incomingRefPrefix + token+ defer func() { _, _ = repo.Git.Run(context.Background(), nil, "update-ref", "-d", dest) }()+ }+ found, err := fetchInto(ctx, repo, remote, dest)+ if err != nil || !found {+ return false, err+ }+ return MergeNotesFrom(ctx, repo, dest)+}++// TrackingRefs lists the refs holding remotes' links.+func TrackingRefs(ctx context.Context, g Git) ([]string, error) {+ out, err := g.Run(ctx, nil, "for-each-ref", "--format=%(refname)", RemoteNotesPrefix)+ if err != nil {+ return nil, err+ }+ var refs []string+ for _, line := range strings.Split(out, "\n") {+ if ref := strings.TrimSpace(line); ref != "" {+ refs = append(refs, ref)+ }+ }+ return refs, nil+}diff --git a/cli/beacon/internal/gitlink/share_test.go b/cli/beacon/internal/gitlink/share_test.gonew file mode 100644index 00000000..f4286ba3--- /dev/null+++ b/cli/beacon/internal/gitlink/share_test.go@@ -0,0 +1,262 @@+package gitlink++import (+ "context"+ "os"+ "path/filepath"+ "reflect"+ "sort"+ "strings"+ "testing"+)++// team is a bare remote with two clones of it, alice and bob, sharing a first commit.+type team struct {+ remote string+ alice, bob *testRepo+ first string+}++func newTeam(t *testing.T) *team {+ t.Helper()+ a := newTestRepo(t)+ base := filepath.Dir(a.root)+ remote := filepath.Join(base, "remote.git")+ a.git("init", "-q", "--bare", "-b", "main", remote)+ a.write("f", "1")+ first := a.commitAt("first", t0)+ a.git("remote", "add", "origin", remote)+ a.git("push", "-q", "origin", "main")+ bobRoot := filepath.Join(base, "bob")+ a.git("clone", "-q", remote, bobRoot)+ b := &testRepo{t: t, root: bobRoot, env: a.env}+ return &team{remote: remote, alice: a, bob: b, first: first}+}++func linksOn(t *testing.T, r *testRepo, ref, commit string) []string {+ t.Helper()+ note, err := readNote(context.Background(), r.gitClient(), ref, commit)+ if err != nil {+ t.Fatal(err)+ }+ got := keys(ParseNote(note))+ sort.Strings(got)+ return got+}++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 {+ t.Fatal(err)+ }+ if _, err := AddLinks(ctx, bob.Git, tm.first, []Link{{"cursor", "bob"}}); err != nil {+ t.Fatal(err)+ }+ res, err := PushNotes(ctx, alice, "origin")+ if err != nil || !res.Pushed || res.Merged {+ t.Fatalf("alice push %+v %v", res, err)+ }+ // Bob's history of refs/notes/beacon does not contain Alice's: a plain push would be rejected.+ res, err = PushNotes(ctx, bob, "origin")+ if err != nil || !res.Pushed || !res.Merged {+ t.Fatalf("bob push %+v %v", res, err)+ }+ remote := &testRepo{t: t, root: tm.remote, env: tm.alice.env}+ want := []string{"codex_cli/alice", "cursor/bob"}+ if got := linksOn(t, remote, NotesRef, tm.first); !reflect.DeepEqual(got, want) {+ t.Fatalf("remote links %v, want %v", got, want)+ }+ if got := linksOn(t, tm.bob, NotesRef, tm.first); !reflect.DeepEqual(got, want) {+ t.Fatalf("bob's local links %v", got)+ }+ // Alice catches up the same way.+ if res, err := PushNotes(ctx, alice, "origin"); err != nil || !res.Merged {+ t.Fatalf("alice second push %+v %v", res, err)+ }+ if got := linksOn(t, tm.alice, NotesRef, tm.first); !reflect.DeepEqual(got, want) {+ t.Fatalf("alice's local links %v", got)+ }+ // Nothing left behind but the local ref and origin's tracking copy.+ refs := tm.bob.git("for-each-ref", "--format=%(refname)", "refs/notes/")+ if refs != NotesRef+"\n"+TrackingRef("origin") {+ t.Fatalf("refs:\n%s", refs)+ }+}++func TestPushNotesEdgeCases(t *testing.T) {+ tm := newTeam(t)+ ctx := context.Background()+ alice := tm.alice.open()+ // Nothing anywhere: nothing to push, no error.+ if res, err := PushNotes(ctx, alice, "origin"); err != nil || res.Pushed || res.Merged {+ t.Fatalf("empty push %+v %v", res, err)+ }+ if found, err := FetchNotes(ctx, alice, "origin"); err != nil || found {+ 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 {+ t.Fatal(err)+ }+ if res, err := PushNotes(ctx, alice, tm.remote); err != nil || !res.Pushed {+ t.Fatalf("push to URL %+v %v", res, err)+ }+ if refs := tm.alice.git("for-each-ref", "--format=%(refname)", "refs/notes/"); refs != NotesRef {+ t.Fatalf("a URL push must leave no incoming or tracking ref:\n%s", refs)+ }+ // An unreachable remote is an error, not a hang or a panic.+ if _, err := PushNotes(ctx, alice, filepath.Join(t.TempDir(), "missing.git")); err == nil {+ t.Fatal("want an error for an unreachable remote")+ }+}++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 {+ 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 {+ t.Fatal(err)+ }+ if added, err := ConfigureFetch(ctx, bob, []string{"origin"}); err != nil || !reflect.DeepEqual(added, []string{"origin"}) {+ t.Fatalf("configure %v %v", added, err)+ }+ if added, _ := ConfigureFetch(ctx, bob, []string{"origin"}); len(added) != 0 {+ t.Fatal("configure is not idempotent")+ }+ // A plain `git fetch` never touches Bob's own links...+ tm.bob.git("fetch", "-q", "origin")+ if got := linksOn(t, tm.bob, NotesRef, tm.first); !reflect.DeepEqual(got, []string{"cursor/bob"}) {+ t.Fatalf("a fetch changed bob's local links: %v", got)+ }+ // ...and brings Alice's into the tracking ref.+ if got := linksOn(t, tm.bob, TrackingRef("origin"), tm.first); !reflect.DeepEqual(got, []string{"codex_cli/alice"}) {+ t.Fatalf("tracking links %v", got)+ }+ commits, err := ListLinked(ctx, bob.Git, "", 10)+ if err != nil || len(commits) != 1 {+ t.Fatalf("list %+v %v", commits, err)+ }+ got := keys(commits[0].Links)+ sort.Strings(got)+ if !reflect.DeepEqual(got, []string{"codex_cli/alice", "cursor/bob"}) {+ t.Fatalf("listed links %v", got)+ }+ // With no local ref at all, fetched links alone still list.+ carol := &testRepo{t: t, root: filepath.Join(filepath.Dir(tm.alice.root), "carol"), env: tm.alice.env}+ tm.alice.git("clone", "-q", tm.remote, carol.root)+ if found, err := FetchNotes(ctx, carol.open(), "origin"); err != nil || !found {+ t.Fatalf("carol fetch %v %v", found, err)+ }+ if commits, err := ListLinked(ctx, carol.gitClient(), "", 10); err != nil || len(commits) != 1 {+ t.Fatalf("carol list %+v %v", commits, err)+ }+ if removed, err := UnconfigureFetch(ctx, bob); err != nil || !reflect.DeepEqual(removed, []string{"origin"}) {+ t.Fatalf("unconfigure %v %v", removed, err)+ }+ if out := tm.bob.git("config", "--get-all", "remote.origin.fetch"); strings.Contains(out, "beacon") {+ t.Fatalf("refspec left behind: %s", out)+ }+}++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 {+ t.Fatal(err)+ }+ if _, err := PushNotes(ctx, alice, "origin"); err != nil {+ t.Fatal(err)+ }+ if _, err := FetchNotes(ctx, bob, "origin"); err != nil {+ t.Fatal(err)+ }+ // Bob has no local ref yet: the merge adopts the remote's.+ if changed, err := MergeNotesFrom(ctx, bob, TrackingRef("origin")); err != nil || !changed {+ t.Fatalf("merge into empty %v %v", changed, err)+ }+ if changed, err := MergeNotesFrom(ctx, bob, TrackingRef("origin")); err != nil || changed {+ t.Fatalf("merge when up to date %v %v", changed, err)+ }+ if changed, err := MergeNotesFrom(ctx, bob, TrackingRef("nowhere")); err != nil || changed {+ t.Fatalf("merge from a missing ref %v %v", changed, err)+ }+}++func TestShareNotesInstallAndRemove(t *testing.T) {+ tm := newTeam(t)+ ctx := context.Background()+ bin, calls := fakeBeacon(t, filepath.Join(t.TempDir(), "bin"))+ bob := tm.bob.open()+ on, off := true, false+ res, err := InstallHooks(ctx, bob, InstallOptions{BeaconPath: bin, ShareNotes: &on})+ if err != nil || len(res.Reports) != 3 || res.Reports[2].Hook != ShareHook || !reflect.DeepEqual(res.FetchAdded, []string{"origin"}) {+ t.Fatalf("install %+v %v", res, err)+ }+ st, _ := HookStatus(ctx, bob)+ if !st.Installed() || !st.Sharing || !reflect.DeepEqual(st.FetchRemotes, []string{"origin"}) {+ t.Fatalf("status %+v", st)+ }+ // The pre-push hook gets git's remote name and URL.+ tm.bob.write("g", "1")+ tm.bob.commitWithEnv("bob")+ tm.bob.git("push", "-q", "origin", "main")+ got := readCalls(t, calls)+ last := got[len(got)-1]+ if !strings.HasSuffix(last, "git hook pre-push origin "+tm.remote) {+ t.Fatalf("pre-push call %q", last)+ }+ // Re-running setup without the flag keeps sharing on.+ if _, err := InstallHooks(ctx, bob, InstallOptions{BeaconPath: bin}); err != nil {+ t.Fatal(err)+ }+ if st, _ := HookStatus(ctx, bob); !st.Sharing {+ t.Fatal("a plain re-run turned sharing off")+ }+ // --share-notes=false turns it off and leaves the rest installed.+ res, err = InstallHooks(ctx, bob, InstallOptions{BeaconPath: bin, ShareNotes: &off})+ if err != nil || !reflect.DeepEqual(res.FetchRemoved, []string{"origin"}) {+ t.Fatalf("turn off %+v %v", res, err)+ }+ if st, _ := HookStatus(ctx, bob); st.Sharing || !st.Installed() || len(st.FetchRemotes) != 0 {+ t.Fatalf("status after off %+v", st)+ }+ loc, _ := ResolveHooks(ctx, bob)+ if _, err := os.Stat(filepath.Join(loc.Dir, "pre-push")); !os.IsNotExist(err) {+ t.Fatal("pre-push hook left behind")+ }+ // Remove takes sharing out along with everything else.+ if _, err := InstallHooks(ctx, bob, InstallOptions{BeaconPath: bin, ShareNotes: &on}); err != nil {+ t.Fatal(err)+ }+ rm, err := RemoveHooks(ctx, bob)+ if err != nil || len(rm.Reports) != 3 || !reflect.DeepEqual(rm.FetchRemoved, []string{"origin"}) {+ t.Fatalf("remove %+v %v", rm, err)+ }+ if st, _ := HookStatus(ctx, bob); st.Sharing || len(st.States) != 2 || st.States[0].Installed {+ t.Fatalf("status after remove %+v", st)+ }+}++func TestErrorSummary(t *testing.T) {+ err := &GitError{Args: []string{"push"}, Message: "To /x/remote.git\n ! [rejected] refs/notes/beacon (fetch first)\nerror: failed to push some refs to '/x/remote.git'\nhint: Updates were rejected"}+ if got := ErrorSummary(err); got != "! [rejected] refs/notes/beacon (fetch first)" {+ t.Fatalf("got %q", got)+ }+ err = &GitError{Message: "fatal: '/gone.git' does not appear to be a git repository\nfatal: Could not read from remote repository."}+ if got := ErrorSummary(err); got != "'/gone.git' does not appear to be a git repository" {+ t.Fatalf("got %q", got)+ }+ if got := ErrorSummary(context.DeadlineExceeded); got != "context deadline exceeded" {+ t.Fatalf("got %q", got)+ }+}diff --git a/docs/cli/git.mdx b/docs/cli/git.mdxindex 29e1812c..1507231c 100644--- a/docs/cli/git.mdx+++ b/docs/cli/git.mdx@@ -13,6 +13,8 @@ beacon git status [flags]beacon git remove [flags]beacon git link [<commit>] [flags]beacon git notes [<revision>] [flags]+beacon git notes push [<remote>] [flags]+beacon git notes fetch [<remote>] [flags]````beacon git setup` installs hooks so every new commit in the repository is linked as it is made. `beacon git link` links one commit by hand, which is also how to link commits made before setup.@@ -59,6 +61,7 @@ Hooks live in the repository's shared hooks directory, so one `setup` covers eve| Flag | Description ||------|-------------|| `--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 || `-C`, `--cwd <dir>` | Repository to operate on || `--json` | Print what was installed as JSON |@@ -82,9 +85,33 @@ Pass `--hooks-path` to install into that directory anyway.Shows whether each hook is installed, reports an install that is broken (a hook calling a script that is gone, or the reverse), and says whether `notes.rewriteRef` is set. `--json` prints the same as JSON, with a top-level `installed` field.+## Sharing links with a team++Links start out local. Nothing leaves the machine until you share them, and sharing is off unless you turn it on.++```bash+beacon git setup --share-notes+```++This does two things in the repository:++- **Fetching.** Each remote gets a fetch refspec, `+refs/notes/beacon:refs/notes/beacon-remotes/<remote>`, so a plain `git fetch` or `git pull` brings teammates' links into a read-only copy. `beacon git notes` reads that copy alongside your own links. Your `refs/notes/beacon` is never overwritten by a fetch, so links you have not pushed yet are safe. A fetch or pull that names a refspec on the command line, such as `git pull origin main`, skips configured refspecs; run `beacon git notes fetch` to fetch links then.+- **Pushing.** A `pre-push` hook shares your links whenever you `git push`. It fetches the remote's links, merges them with yours (every line of both is kept), and pushes only `refs/notes/beacon` to the same remote. It runs with `--no-verify`, so your other pre-push hooks are not run twice. It gives up after ten seconds and never fails your push: if sharing fails, it prints one line and your code is pushed as usual.++This is the one Beacon hook that reaches the network, and only during a push you started, to the remote you are pushing to. `BEACON_GIT_HOOKS=0 git push` skips it for one push, and `beacon git setup --share-notes=false` turns it off.++To share by hand instead, without the hook:++```bash+beacon git notes push # the branch's remote, or origin+beacon 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.+## `beacon git remove`-Removes Beacon's scripts, its blocks in the hooks, and its `notes.rewriteRef` value, leaving everything else as it was. A hook that held nothing but Beacon's block is deleted. Links already written stay in `refs/notes/beacon`.+Removes Beacon's scripts, its blocks in the hooks, its `notes.rewriteRef` value, and the fetch refspecs `--share-notes` added, leaving everything else as it was. A hook that held nothing but Beacon's block is deleted. Links already written stay in `refs/notes/beacon`.## `beacon git link`@@ -124,7 +151,7 @@ beacon git notes origin/main --json| Flag | Description ||------|-------------|-| `--limit <n>` | Number of commits to walk (default 20); commits without links are skipped |+| `--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 |@@ -174,8 +201,8 @@ beacon:<harness>/<session-id>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.-To see links in `git log`:+To see links in `git log`, including those fetched from remotes:```bash-git log --notes=beacon+git log --notes=beacon --notes='beacon-remotes/*'```