Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

Link each new commit automatically with beacon git setup

Claudedc0b02eb1a2e
diff --git a/CLAUDE.md b/CLAUDE.md
index f89adb65..8932e3c7 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 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.
+- 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.
- 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.go
new file mode 100644
index 00000000..e2ce966e
--- /dev/null
+++ b/cli/beacon/cmd/git_hooks.go
@@ -0,0 +1,276 @@
+package cmd
+
+import (
+ "bufio"
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/gitlink"
+)
+
+// gitHookBudget bounds the post-commit hook. Linking reads recent runtime log and writes one
+// note, which takes milliseconds on a quiet endpoint and well under a second on a busy one; the
+// bound is for the case nothing anticipated, because a person is waiting on `git commit`.
+var gitHookBudget = 3 * time.Second
+
+var gitSetupCmd = &cobra.Command{
+ Use: "setup",
+ Short: "Install git hooks that link each new commit to the sessions that wrote it",
+ Long: `Install git hooks that link each new commit to the sessions that wrote it.
+
+Beacon adds post-commit and post-rewrite hooks to the repository. A hook already there keeps working: Beacon adds a
+marked block to it and a separate beacon-post-commit script beside it, and ` + "`beacon git remove`" + `
+takes out exactly that. It also sets notes.rewriteRef, so ` + "`git commit --amend`" + ` and ` + "`git rebase`" + `
+carry links to the rewritten commits.
+
+The hook reads the local runtime log and writes a git note. It never touches the network, never
+fails a commit, and skips rebases, cherry-picks and reverts. BEACON_GIT_HOOKS=0 turns it off for one
+command.`,
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: runGitSetup,
+}
+
+var gitRemoveCmd = &cobra.Command{
+ Use: "remove",
+ Short: "Remove Beacon's git hooks from the repository (links already written stay)",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: runGitRemove,
+}
+
+var gitStatusCmd = &cobra.Command{
+ Use: "status",
+ Short: "Show whether this repository links commits automatically",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: runGitStatus,
+}
+
+var gitHookCmd = &cobra.Command{
+ Use: "hook",
+ Short: "Entry points the installed git hooks call",
+ Hidden: true,
+}
+
+var gitHookPostCommitCmd = &cobra.Command{
+ Use: "post-commit",
+ Short: "Link HEAD to the sessions that wrote it (called by the post-commit hook)",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: runGitHookPostCommit,
+}
+
+var gitHookPostRewriteCmd = &cobra.Command{
+ Use: "post-rewrite [amend|rebase]",
+ Short: "Tidy the notes on rewritten commits (called by the post-rewrite hook)",
+ Args: cobra.MaximumNArgs(1),
+ SilenceUsage: true,
+ RunE: runGitHookPostRewrite,
+}
+
+var gitSetupOpts struct {
+ allowHooksPath bool
+}
+
+func runGitSetup(cmd *cobra.Command, _ []string) error {
+ ctx := cmd.Context()
+ repo, err := gitRepo(ctx)
+ if err != nil {
+ return err
+ }
+ result, err := gitlink.InstallHooks(ctx, repo, gitlink.InstallOptions{
+ BeaconPath: beaconExecutable(),
+ AllowHooksPath: gitSetupOpts.allowHooksPath,
+ })
+ out := cmd.OutOrStdout()
+ if err != nil {
+ switch {
+ case errors.Is(err, gitlink.ErrHooksPathSet):
+ return fmt.Errorf("%w; git runs this repository's hooks from %s, which a hook manager usually owns.\n"+
+ "Add this line to its post-commit hook:\n\n %s\n\n"+
+ "or run `beacon git setup --hooks-path` to install into that directory anyway", err, result.Hooks.Dir, gitlink.HookCall("post-commit"))
+ case errors.Is(err, gitlink.ErrForeignHook):
+ return fmt.Errorf("%w; Beacon only edits shell hooks. Call Beacon from that hook instead:\n\n %s", err, gitlink.HookCall("post-commit"))
+ }
+ return err
+ }
+ if gitOpts.jsonOutput {
+ return writeIndentedJSON(out, result)
+ }
+ for _, r := range result.Reports {
+ fmt.Fprintf(out, "%-9s %s (calls %s)\n", r.Action, r.Path, filepath.Base(r.Script))
+ }
+ if result.RewriteRefSet {
+ fmt.Fprintf(out, "set notes.rewriteRef = %s\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
+}
+
+func runGitRemove(cmd *cobra.Command, _ []string) error {
+ ctx := cmd.Context()
+ repo, err := gitRepo(ctx)
+ if err != nil {
+ return err
+ }
+ result, err := gitlink.RemoveHooks(ctx, repo)
+ if err != nil {
+ return err
+ }
+ out := cmd.OutOrStdout()
+ if gitOpts.jsonOutput {
+ return writeIndentedJSON(out, result)
+ }
+ for _, r := range result.Reports {
+ fmt.Fprintf(out, "%-9s %s\n", r.Action, r.Path)
+ }
+ if result.RewriteRefRemoved {
+ fmt.Fprintf(out, "unset notes.rewriteRef = %s\n", gitlink.NotesRef)
+ }
+ fmt.Fprintf(out, "Links already written stay in %s.\n", gitlink.NotesRef)
+ return nil
+}
+
+func runGitStatus(cmd *cobra.Command, _ []string) error {
+ ctx := cmd.Context()
+ repo, err := gitRepo(ctx)
+ if err != nil {
+ return err
+ }
+ status, err := gitlink.HookStatus(ctx, repo)
+ if err != nil {
+ return err
+ }
+ out := cmd.OutOrStdout()
+ if gitOpts.jsonOutput {
+ return writeIndentedJSON(out, struct {
+ gitlink.Status
+ Installed bool `json:"installed"`
+ }{status, status.Installed()})
+ }
+ fmt.Fprintf(out, "repository %s\n", repo.Root)
+ fmt.Fprintf(out, "hooks %s\n", status.Hooks.Dir)
+ if status.Hooks.HooksPath != "" {
+ fmt.Fprintf(out, " (core.hooksPath = %s)\n", status.Hooks.HooksPath)
+ }
+ for _, st := range status.States {
+ state := "not installed"
+ switch {
+ case st.Installed:
+ state = "installed"
+ case st.BlockPresent:
+ state = "broken: the hook calls a script that is missing (run `beacon git setup`)"
+ case st.ScriptExists:
+ state = "broken: the script exists but the hook does not call it (run `beacon git setup`)"
+ }
+ fmt.Fprintf(out, "%-11s %s\n", st.Hook, state)
+ }
+ rewrite := "not set"
+ if status.RewriteRef {
+ rewrite = "set"
+ }
+ fmt.Fprintf(out, "rewriteRef %s\n", rewrite)
+ return nil
+}
+
+// runGitHookPostCommit is the post-commit hook. It never returns an error: git ignores a
+// post-commit hook's exit status anyway, and a hook that printed a stack of errors on every commit
+// in a repository with no agent activity would be worse than one that stayed quiet.
+func runGitHookPostCommit(cmd *cobra.Command, _ []string) error {
+ if os.Getenv(gitlink.DisableEnv) == "0" {
+ return nil
+ }
+ ctx, cancel := context.WithTimeout(cmd.Context(), gitHookBudget)
+ defer cancel()
+ result, ran := gitPostCommit(ctx)
+ if gitOpts.jsonOutput && ran {
+ _ = writeIndentedJSON(cmd.OutOrStdout(), result)
+ }
+ return nil
+}
+
+func gitPostCommit(ctx context.Context) (gitlink.Result, bool) {
+ repo, err := gitRepo(ctx)
+ if err != nil || gitlink.ReplayInProgress(ctx, repo) {
+ return gitlink.Result{}, false
+ }
+ result, err := gitlink.Attribute(ctx, repo, gitlink.Options{LogPath: gitRuntimeLogPath()})
+ if err != nil {
+ return gitlink.Result{}, false
+ }
+ return result, true
+}
+
+// runGitHookPostRewrite reads git's `<old-sha> <new-sha> [<extra>]` lines and normalizes the note
+// on each new commit. Like the post-commit hook, it never returns an error.
+func runGitHookPostRewrite(cmd *cobra.Command, _ []string) error {
+ if os.Getenv(gitlink.DisableEnv) == "0" {
+ return nil
+ }
+ ctx, cancel := context.WithTimeout(cmd.Context(), gitHookBudget)
+ defer cancel()
+ repo, err := gitRepo(ctx)
+ if err != nil {
+ return nil
+ }
+ scanner := bufio.NewScanner(cmd.InOrStdin())
+ for scanner.Scan() {
+ fields := strings.Fields(scanner.Text())
+ if len(fields) < 2 {
+ continue
+ }
+ if _, err := gitlink.NormalizeNote(ctx, repo.Git, fields[1]); err != nil && ctx.Err() != nil {
+ return nil
+ }
+ }
+ return nil
+}
+
+// beaconExecutable is the path hook scripts call first: beacon on PATH when that is this binary
+// (a Homebrew symlink survives upgrades; the versioned Cellar path it points to does not), and
+// otherwise the running executable.
+func beaconExecutable() string {
+ self, err := os.Executable()
+ if err != nil {
+ return ""
+ }
+ if onPath, err := exec.LookPath("beacon"); err == nil {
+ if abs, err := filepath.Abs(onPath); err == nil && sameFile(abs, self) {
+ return abs
+ }
+ }
+ return self
+}
+
+func sameFile(a, b string) bool {
+ ai, err := os.Stat(a)
+ if err != nil {
+ return false
+ }
+ bi, err := os.Stat(b)
+ if err != nil {
+ return false
+ }
+ return os.SameFile(ai, bi)
+}
+
+func init() {
+ gitCmd.AddCommand(gitSetupCmd, gitRemoveCmd, gitStatusCmd, gitHookCmd)
+ gitHookCmd.AddCommand(gitHookPostCommitCmd, gitHookPostRewriteCmd)
+ for _, c := range []*cobra.Command{gitSetupCmd, gitRemoveCmd, gitStatusCmd, gitHookPostCommitCmd, gitHookPostRewriteCmd} {
+ c.Flags().StringVarP(&gitOpts.dir, "cwd", "C", "", "Repository to operate on (default the current directory)")
+ c.Flags().BoolVar(&gitOpts.jsonOutput, "json", false, "Print the result as JSON")
+ }
+ 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")
+}
diff --git a/cli/beacon/cmd/git_hooks_test.go b/cli/beacon/cmd/git_hooks_test.go
new file mode 100644
index 00000000..e31dfcdb
--- /dev/null
+++ b/cli/beacon/cmd/git_hooks_test.go
@@ -0,0 +1,148 @@
+package cmd
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/gitlink"
+)
+
+func writeRuntimeEvent(t *testing.T, logPath, top, session, file string) {
+ t.Helper()
+ event := schema.NewEvent(schema.NewEventOptions{Action: "file.modified", Harness: schema.HarnessInfo{Name: "cursor"}})
+ event.Timestamp = schema.FormatTimestamp(time.Now().Add(-time.Minute))
+ event.Session = &schema.SessionInfo{ID: session, WorkingDirectory: top}
+ event.File = &schema.FileInfo{Path: filepath.Join(top, file), Operation: "modify"}
+ 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 TestGitHookPostCommitLinksHEAD(t *testing.T) {
+ root := gitCommandRepo(t)
+ top := mustGit(t, root, "rev-parse", "--show-toplevel")
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ if err := os.WriteFile(filepath.Join(root, "x.go"), []byte("package x\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ writeRuntimeEvent(t, logPath, top, "cur-1", "x.go")
+ mustGit(t, root, "add", "-A")
+ mustGit(t, root, "commit", "-q", "-m", "x")
+ out, err := runGit(t, "hook", "post-commit", "--cwd", root, "--log-path", logPath)
+ if err != nil || out != "" {
+ t.Fatalf("hook: %v, printed %q (a hook must stay quiet)", err, out)
+ }
+ if note := mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "show", "HEAD"); note != "beacon:cursor/cur-1" {
+ t.Fatalf("note %q", note)
+ }
+}
+
+func TestGitHookPostCommitIsQuietOutsideARepositoryAndWhenDisabled(t *testing.T) {
+ gitCommandRepo(t)
+ dir := t.TempDir()
+ t.Setenv("GIT_CEILING_DIRECTORIES", filepath.Dir(dir))
+ if out, err := runGit(t, "hook", "post-commit", "--cwd", dir); err != nil || out != "" {
+ t.Fatalf("outside a repository: %v %q", err, out)
+ }
+ t.Setenv(gitlink.DisableEnv, "0")
+ if out, err := runGit(t, "hook", "post-commit", "--cwd", dir, "--json"); err != nil || out != "" {
+ t.Fatalf("disabled: %v %q", err, out)
+ }
+}
+
+func TestGitHookPostCommitSkipsReplays(t *testing.T) {
+ root := gitCommandRepo(t)
+ top := mustGit(t, root, "rev-parse", "--show-toplevel")
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ if err := os.WriteFile(filepath.Join(root, "x.go"), []byte("1"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ writeRuntimeEvent(t, logPath, top, "cur-1", "x.go")
+ mustGit(t, root, "add", "-A")
+ mustGit(t, root, "commit", "-q", "-m", "x")
+ // Pretend a rebase is underway.
+ if err := os.MkdirAll(filepath.Join(root, ".git", "rebase-merge"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := runGit(t, "hook", "post-commit", "--cwd", root, "--log-path", logPath); err != nil {
+ t.Fatal(err)
+ }
+ if note := mustGitAllowFail(root, "notes", "--ref="+gitlink.NotesRef, "show", "HEAD"); note != "" {
+ t.Fatalf("a replay was attributed: %q", note)
+ }
+}
+
+func TestGitSetupStatusRemove(t *testing.T) {
+ root := gitCommandRepo(t)
+ out, err := runGit(t, "status", "--cwd", root)
+ if err != nil || !strings.Contains(out, "post-commit not installed") {
+ t.Fatalf("status before: %v\n%s", err, out)
+ }
+ out, err = runGit(t, "setup", "--cwd", root)
+ if err != nil || !strings.Contains(out, "created") || !strings.Contains(out, "notes.rewriteRef") {
+ t.Fatalf("setup: %v\n%s", err, out)
+ }
+ hook, _ := os.ReadFile(filepath.Join(root, ".git", "hooks", "beacon-post-commit"))
+ if exe, _ := os.Executable(); !strings.Contains(string(hook), exe) && !strings.Contains(string(hook), "beacon") {
+ t.Fatalf("script does not name a beacon binary:\n%s", hook)
+ }
+ out, err = runGit(t, "status", "--cwd", root, "--json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var st struct {
+ Installed bool `json:"installed"`
+ RewriteRef bool `json:"rewrite_ref"`
+ }
+ if err := json.Unmarshal([]byte(out), &st); err != nil || !st.Installed || !st.RewriteRef {
+ t.Fatalf("status json %v: %s", err, out)
+ }
+ out, err = runGit(t, "remove", "--cwd", root)
+ if err != nil || !strings.Contains(out, "removed") || !strings.Contains(out, "Links already written stay") {
+ t.Fatalf("remove: %v\n%s", err, out)
+ }
+ if _, err := os.Stat(filepath.Join(root, ".git", "hooks", "post-commit")); !os.IsNotExist(err) {
+ t.Fatal("hook left behind")
+ }
+}
+
+func TestGitSetupExplainsCoreHooksPath(t *testing.T) {
+ root := gitCommandRepo(t)
+ mustGit(t, root, "config", "core.hooksPath", ".husky/_")
+ _, err := runGit(t, "setup", "--cwd", root)
+ if err == nil || !strings.Contains(err.Error(), "core.hooksPath") || !strings.Contains(err.Error(), "beacon git hook post-commit || true") || !strings.Contains(err.Error(), "--hooks-path") {
+ t.Fatalf("got %v", err)
+ }
+ if _, err := runGit(t, "setup", "--cwd", root, "--hooks-path"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(filepath.Join(root, ".husky", "_", "beacon-post-commit")); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestGitHookPostRewriteNormalizesRewrittenNotes(t *testing.T) {
+ root := gitCommandRepo(t)
+ mustGit(t, root, "commit", "-q", "--allow-empty", "-m", "c")
+ sha := mustGit(t, root, "rev-parse", "HEAD")
+ mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "add", "-m", "beacon:codex_cli/a\n\nbeacon:codex_cli/a", sha)
+ rootCmd.SetIn(strings.NewReader("0000000000000000000000000000000000000000 " + sha + "\nmalformed\n"))
+ t.Cleanup(func() { rootCmd.SetIn(nil) })
+ if _, err := runGit(t, "hook", "post-rewrite", "amend", "--cwd", root); err != nil {
+ t.Fatal(err)
+ }
+ if note := mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "show", sha); note != "beacon:codex_cli/a" {
+ t.Fatalf("note %q", note)
+ }
+}
diff --git a/cli/beacon/cmd/git_test.go b/cli/beacon/cmd/git_test.go
index 577ccd6a..2a09aaff 100644
--- a/cli/beacon/cmd/git_test.go
+++ b/cli/beacon/cmd/git_test.go
@@ -10,6 +10,7 @@ import (
"testing"
"time"
+ "github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
@@ -21,12 +22,18 @@ import (
func runGit(t *testing.T, args ...string) (string, error) {
t.Helper()
gitOpts = gitOptions{}
- for _, c := range gitCmd.Commands() {
+ gitSetupOpts.allowHooksPath = false
+ 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)
var stdout, stderr bytes.Buffer
rootCmd.SetOut(&stdout)
rootCmd.SetErr(&stderr)
diff --git a/cli/beacon/internal/gitlink/hooks.go b/cli/beacon/internal/gitlink/hooks.go
new file mode 100644
index 00000000..b899205b
--- /dev/null
+++ b/cli/beacon/internal/gitlink/hooks.go
@@ -0,0 +1,434 @@
+package gitlink
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+)
+
+const (
+ hookBlockStart = "# >>> beacon git hooks (do not edit)"
+ hookBlockEnd = "# <<< beacon git hooks"
+ // HookScriptPrefix names Beacon's standalone hook scripts: beacon-post-commit next to
+ // post-commit. The hook git runs calls the script through a marked block, so a repository's own
+ // hook keeps working and Beacon's part can be removed without touching the rest.
+ HookScriptPrefix = "beacon-"
+ // DisableEnv, set to 0, turns every installed Beacon git hook into a no-op for one command:
+ // BEACON_GIT_HOOKS=0 git commit ...
+ DisableEnv = "BEACON_GIT_HOOKS"
+)
+
+// ManagedHooks are the git hooks Beacon installs. post-commit links a new commit; post-rewrite
+// tidies the note on a commit `git commit --amend` or `git rebase` rewrote, after git has copied
+// the old commit's note across (see NormalizeNote).
+var ManagedHooks = []string{"post-commit", "post-rewrite"}
+
+// 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.
+var ErrHooksPathSet = errors.New("core.hooksPath is set")
+
+// ErrForeignHook is returned when an existing hook is not a shell script, so a shell block cannot
+// be added to it safely.
+var ErrForeignHook = errors.New("existing hook is not a shell script")
+
+// HooksLocation is where git looks for this repository's hooks.
+type HooksLocation struct {
+ Dir string `json:"dir"`
+ // HooksPath is core.hooksPath when it is set.
+ HooksPath string `json:"hooks_path,omitempty"`
+}
+
+// ResolveHooks returns the directory git runs this repository's hooks from. It honors
+// core.hooksPath, and for a linked worktree it is the shared directory in the common git dir.
+func ResolveHooks(ctx context.Context, repo Repo) (HooksLocation, error) {
+ dir, err := repo.Git.Run(ctx, nil, "rev-parse", "--git-path", "hooks")
+ if err != nil {
+ return HooksLocation{}, err
+ }
+ if !filepath.IsAbs(dir) {
+ dir = filepath.Join(repo.Root, dir)
+ }
+ loc := HooksLocation{Dir: filepath.Clean(dir)}
+ if value, err := repo.Git.Run(ctx, nil, "config", "--get", "core.hooksPath"); err == nil {
+ loc.HooksPath = strings.TrimSpace(value)
+ }
+ return loc, nil
+}
+
+// InstallOptions configures InstallHooks.
+type InstallOptions struct {
+ // BeaconPath is the absolute path of the beacon binary the hook scripts call first. They fall
+ // back to beacon on PATH when it is missing, which is what a package upgrade that moves the
+ // binary leaves behind.
+ BeaconPath string
+ // AllowHooksPath installs into core.hooksPath's directory when it is set.
+ AllowHooksPath bool
+}
+
+// HookReport is what installing or removing did to one hook.
+type HookReport struct {
+ Hook string `json:"hook"`
+ Path string `json:"path"`
+ Script string `json:"script"`
+ // Action is "created" (no hook existed), "added" (Beacon's block was added to an existing
+ // hook), "updated", "unchanged", "removed", or "absent".
+ Action string `json:"action"`
+}
+
+// InstallResult is the outcome of InstallHooks.
+type InstallResult struct {
+ Hooks HooksLocation `json:"hooks"`
+ Reports []HookReport `json:"reports"`
+ RewriteRefSet bool `json:"rewrite_ref_set"`
+}
+
+// InstallHooks installs Beacon's hooks. It is idempotent: a second run rewrites the scripts and
+// leaves the hooks unchanged.
+func InstallHooks(ctx context.Context, repo Repo, opts InstallOptions) (InstallResult, error) {
+ loc, err := ResolveHooks(ctx, repo)
+ if err != nil {
+ return InstallResult{}, err
+ }
+ result := InstallResult{Hooks: loc}
+ if loc.HooksPath != "" && !opts.AllowHooksPath {
+ return result, fmt.Errorf("%w to %s", ErrHooksPathSet, loc.HooksPath)
+ }
+ if err := os.MkdirAll(loc.Dir, 0o755); err != nil {
+ return result, err
+ }
+ // Check every hook before writing any, so a refusal leaves the repository as it was.
+ for _, hook := range ManagedHooks {
+ 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 {
+ report, err := installHook(loc.Dir, hook, opts.BeaconPath)
+ if err != nil {
+ return result, err
+ }
+ result.Reports = append(result.Reports, report)
+ }
+ set, err := ensureRewriteRef(ctx, repo)
+ if err != nil {
+ return result, err
+ }
+ result.RewriteRefSet = set
+ return result, nil
+}
+
+func installHook(dir, hook, beaconPath string) (HookReport, error) {
+ scriptName := HookScriptPrefix + hook
+ report := HookReport{Hook: hook, Path: filepath.Join(dir, hook), Script: filepath.Join(dir, scriptName)}
+ if err := writeExecutable(report.Script, hookScript(hook, beaconPath)); err != nil {
+ return report, err
+ }
+ existing, err := os.ReadFile(report.Path)
+ if err != nil && !os.IsNotExist(err) {
+ return report, err
+ }
+ block := hookBlock(scriptName)
+ var next string
+ switch {
+ case os.IsNotExist(err) || strings.TrimSpace(string(existing)) == "":
+ report.Action = "created"
+ next = "#!/bin/sh\n" + block
+ case strings.Contains(string(existing), hookBlockStart):
+ report.Action = "updated"
+ next = insertBlock(removeBlock(string(existing)), block)
+ if next == string(existing) {
+ report.Action = "unchanged"
+ }
+ default:
+ report.Action = "added"
+ next = insertBlock(string(existing), block)
+ }
+ if report.Action != "unchanged" {
+ if err := writeExecutable(report.Path, next); err != nil {
+ return report, err
+ }
+ } else if err := os.Chmod(report.Path, 0o755); err != nil {
+ return report, err
+ }
+ return report, nil
+}
+
+// insertBlock puts Beacon's block directly after the shebang. Running first matters: a hook that
+// ends in `exit 0` or `exec` would never reach a block appended after it. Beacon's part cannot
+// fail or stop the rest, so going first changes nothing the existing hook does.
+func insertBlock(script, block string) string {
+ if !strings.HasPrefix(script, "#!") {
+ return "#!/bin/sh\n" + block + script
+ }
+ shebang, rest, _ := strings.Cut(script, "\n")
+ return shebang + "\n" + block + rest
+}
+
+func removeBlock(script string) string {
+ start := strings.Index(script, hookBlockStart)
+ if start < 0 {
+ return script
+ }
+ end := strings.Index(script[start:], hookBlockEnd)
+ if end < 0 {
+ return script
+ }
+ end = start + end + len(hookBlockEnd)
+ if end < len(script) && script[end] == '\n' {
+ end++
+ }
+ return script[:start] + script[end:]
+}
+
+var shellShebang = regexp.MustCompile(`^#!\s*(/usr/bin/env\s+(-S\s+)?)?(\S*/)?(sh|bash|dash|zsh|ksh|ash)(\s|$)`)
+
+func checkHookEditable(path string) error {
+ data, err := os.ReadFile(path)
+ if os.IsNotExist(err) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ text := string(data)
+ if strings.TrimSpace(text) == "" || strings.Contains(text, hookBlockStart) {
+ return nil
+ }
+ first, _, _ := strings.Cut(text, "\n")
+ if !strings.HasPrefix(first, "#!") {
+ // No shebang: git runs it with sh.
+ return nil
+ }
+ if !shellShebang.MatchString(first) {
+ return fmt.Errorf("%w (%s)", ErrForeignHook, strings.TrimSpace(first))
+ }
+ return nil
+}
+
+func hookBlock(scriptName string) string {
+ return hookBlockStart + "\n" +
+ `if [ -x "$(git rev-parse --git-path hooks)/` + scriptName + `" ]; then` + "\n" +
+ ` "$(git rev-parse --git-path hooks)/` + scriptName + `" "$@"` + "\n" +
+ "fi\n" +
+ hookBlockEnd + "\n"
+}
+
+// HookCall is the line to put in a hook Beacon cannot edit (a hook manager's, or one written in
+// another language) so it links commits too.
+func HookCall(hook string) string {
+ return "beacon git hook " + hook + " || true"
+}
+
+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.",
+}
+
+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" {
+ stdin, args = "", ` "$@"`
+ }
+ 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.
+[ "${` + DisableEnv + `:-1}" = "0" ] && exit 0
+beacon_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
+exit 0
+`
+}
+
+func shellQuote(s string) string {
+ return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
+}
+
+func writeExecutable(path, content string) error {
+ tmp := path + ".beacon-tmp"
+ if err := os.WriteFile(tmp, []byte(content), 0o755); err != nil {
+ return err
+ }
+ if err := os.Chmod(tmp, 0o755); err != nil {
+ os.Remove(tmp)
+ return err
+ }
+ if err := os.Rename(tmp, path); err != nil {
+ os.Remove(tmp)
+ return err
+ }
+ return nil
+}
+
+// RemoveResult is the outcome of RemoveHooks.
+type RemoveResult struct {
+ Hooks HooksLocation `json:"hooks"`
+ Reports []HookReport `json:"reports"`
+ RewriteRefRemoved bool `json:"rewrite_ref_removed"`
+}
+
+// RemoveHooks removes Beacon's scripts and blocks. A hook left with nothing but a shebang is
+// deleted; anything else in it stays. The notes themselves are never removed: they are history.
+func RemoveHooks(ctx context.Context, repo Repo) (RemoveResult, error) {
+ loc, err := ResolveHooks(ctx, repo)
+ if err != nil {
+ 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) {
+ 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
+ }
+ result.Reports = append(result.Reports, report)
+ }
+ removed, err := removeRewriteRef(ctx, repo)
+ if err != nil {
+ return result, err
+ }
+ result.RewriteRefRemoved = removed
+ return result, nil
+}
+
+func onlyShebang(script string) bool {
+ for _, line := range strings.Split(script, "\n") {
+ line = strings.TrimSpace(line)
+ if line != "" && !strings.HasPrefix(line, "#!") {
+ return false
+ }
+ }
+ return true
+}
+
+// HookState is whether one hook is wired to Beacon.
+type HookState struct {
+ Hook string `json:"hook"`
+ // Installed is true when the hook calls Beacon's script and the script exists.
+ Installed bool `json:"installed"`
+ BlockPresent bool `json:"block_present"`
+ ScriptExists bool `json:"script_exists"`
+}
+
+// Status is the state of Beacon's git integration in one repository.
+type Status struct {
+ Hooks HooksLocation `json:"hooks"`
+ States []HookState `json:"states"`
+ RewriteRef bool `json:"rewrite_ref"`
+}
+
+// Installed is true when every managed hook is installed.
+func (s Status) Installed() bool {
+ for _, st := range s.States {
+ if !st.Installed {
+ return false
+ }
+ }
+ return len(s.States) > 0
+}
+
+// HookStatus reports Beacon's git integration in repo.
+func HookStatus(ctx context.Context, repo Repo) (Status, error) {
+ loc, err := ResolveHooks(ctx, repo)
+ if err != nil {
+ return Status{}, err
+ }
+ status := Status{Hooks: loc}
+ for _, hook := range ManagedHooks {
+ st := HookState{Hook: hook}
+ if data, err := os.ReadFile(filepath.Join(loc.Dir, hook)); err == nil {
+ st.BlockPresent = strings.Contains(string(data), hookBlockStart)
+ }
+ if _, err := os.Stat(filepath.Join(loc.Dir, HookScriptPrefix+hook)); err == nil {
+ st.ScriptExists = true
+ }
+ st.Installed = st.BlockPresent && st.ScriptExists
+ status.States = append(status.States, st)
+ }
+ status.RewriteRef, err = hasRewriteRef(ctx, repo)
+ return status, err
+}
+
+// ensureRewriteRef adds NotesRef to notes.rewriteRef, so `git commit --amend` and `git rebase`
+// carry a commit's links to the commit that replaces it.
+func ensureRewriteRef(ctx context.Context, repo Repo) (bool, error) {
+ if has, err := hasRewriteRef(ctx, repo); err != nil || has {
+ return false, err
+ }
+ if _, err := repo.Git.Run(ctx, nil, "config", "--local", "--add", "notes.rewriteRef", NotesRef); err != nil {
+ return false, err
+ }
+ return true, nil
+}
+
+func hasRewriteRef(ctx context.Context, repo Repo) (bool, error) {
+ out, err := repo.Git.Run(ctx, nil, "config", "--local", "--get-all", "notes.rewriteRef")
+ if err != nil {
+ var gitErr *GitError
+ if errors.As(err, &gitErr) {
+ return false, nil // exit 1: no value
+ }
+ return false, err
+ }
+ for _, line := range strings.Split(out, "\n") {
+ if strings.TrimSpace(line) == NotesRef {
+ return true, nil
+ }
+ }
+ return false, nil
+}
+
+func removeRewriteRef(ctx context.Context, repo Repo) (bool, error) {
+ has, err := hasRewriteRef(ctx, repo)
+ if err != nil || !has {
+ return false, err
+ }
+ pattern := "^" + regexp.QuoteMeta(NotesRef) + "$"
+ if _, err := repo.Git.Run(ctx, nil, "config", "--local", "--unset-all", "notes.rewriteRef", pattern); err != nil {
+ return false, err
+ }
+ return true, nil
+}
+
+// ReplayInProgress reports whether git is replaying existing commits -- a rebase, cherry-pick or
+// revert -- rather than recording new work. Their commits' links, when they have any, travel with
+// notes.rewriteRef; attributing them afresh would credit whoever is rebasing today.
+func ReplayInProgress(ctx context.Context, repo Repo) bool {
+ for _, name := range []string{"rebase-merge", "rebase-apply", "CHERRY_PICK_HEAD", "REVERT_HEAD", "sequencer"} {
+ path, err := repo.Git.Run(ctx, nil, "rev-parse", "--git-path", name)
+ if err != nil {
+ continue
+ }
+ if !filepath.IsAbs(path) {
+ path = filepath.Join(repo.Root, path)
+ }
+ if _, err := os.Stat(path); err == nil {
+ return true
+ }
+ }
+ return false
+}
diff --git a/cli/beacon/internal/gitlink/hooks_test.go b/cli/beacon/internal/gitlink/hooks_test.go
new file mode 100644
index 00000000..fad1c698
--- /dev/null
+++ b/cli/beacon/internal/gitlink/hooks_test.go
@@ -0,0 +1,435 @@
+package gitlink
+
+import (
+ "context"
+ "errors"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+)
+
+// fakeBeacon writes an executable that records each invocation's arguments and working directory
+// to a file, and returns both paths.
+func fakeBeacon(t *testing.T, dir string) (bin, calls string) {
+ t.Helper()
+ testenv.RequirePOSIXExecutableFixtures(t)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ bin = filepath.Join(dir, "beacon")
+ calls = filepath.Join(dir, "calls.log")
+ script := "#!/bin/sh\necho \"$(pwd -P) $*\" >> " + shellQuote(calls) + "\n"
+ if err := os.WriteFile(bin, []byte(script), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ return bin, calls
+}
+
+func readCalls(t *testing.T, path string) []string {
+ t.Helper()
+ data, err := os.ReadFile(path)
+ if os.IsNotExist(err) {
+ return nil
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ return strings.Split(strings.TrimSpace(string(data)), "\n")
+}
+
+func (r *testRepo) commitWithEnv(message string, extra ...string) {
+ r.t.Helper()
+ r.git("add", "-A")
+ cmd := exec.Command("git", "-C", r.root, "commit", "-q", "--allow-empty", "-m", message)
+ cmd.Env = append(append([]string{}, r.env...), extra...)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ r.t.Fatalf("commit: %v\n%s", err, out)
+ }
+}
+
+func TestInstallHooksFreshRepository(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ bin, calls := fakeBeacon(t, filepath.Join(t.TempDir(), "bin with 'quote"))
+ repo := r.open()
+
+ res, err := InstallHooks(ctx, repo, InstallOptions{BeaconPath: bin})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(res.Reports) != len(ManagedHooks) || res.Reports[0].Action != "created" || !res.RewriteRefSet {
+ t.Fatalf("install result %+v", res)
+ }
+ hook, _ := os.ReadFile(res.Reports[0].Path)
+ if !strings.HasPrefix(string(hook), "#!/bin/sh\n"+hookBlockStart) {
+ t.Fatalf("hook:\n%s", hook)
+ }
+ if testenv.HasPOSIXFileModes() {
+ for _, p := range []string{res.Reports[0].Path, res.Reports[0].Script} {
+ if info, _ := os.Stat(p); info.Mode()&0o111 == 0 {
+ t.Fatalf("%s is not executable", p)
+ }
+ }
+ }
+ if got := r.git("config", "--get-all", "notes.rewriteRef"); got != NotesRef {
+ t.Fatalf("rewriteRef %q", got)
+ }
+
+ r.write("a", "1")
+ r.commitWithEnv("first")
+ got := readCalls(t, calls)
+ root, _ := filepath.EvalSymlinks(r.root)
+ if len(got) != 1 || got[0] != root+" git hook post-commit" {
+ t.Fatalf("calls %q, want one from %s", got, root)
+ }
+
+ again, err := InstallHooks(ctx, repo, InstallOptions{BeaconPath: bin})
+ if err != nil || again.Reports[0].Action != "unchanged" || again.Reports[1].Action != "unchanged" || again.RewriteRefSet {
+ t.Fatalf("second install %+v %v", again, err)
+ }
+ if got := r.git("config", "--get-all", "notes.rewriteRef"); got != NotesRef {
+ t.Fatalf("rewriteRef duplicated: %q", got)
+ }
+
+ st, err := HookStatus(ctx, repo)
+ if err != nil || !st.Installed() || !st.RewriteRef {
+ t.Fatalf("status %+v %v", st, err)
+ }
+}
+
+func TestInstallHooksKeepsAnExistingShellHook(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ bin, calls := fakeBeacon(t, filepath.Join(t.TempDir(), "bin"))
+ repo := r.open()
+ loc, _ := ResolveHooks(ctx, repo)
+ marker := filepath.Join(t.TempDir(), "theirs.log")
+ // Ends in `exit 0`: a block appended after it would never run.
+ original := "#!/usr/bin/env bash\nset -e\necho ran >> '" + marker + "'\nexit 0\n"
+ if err := os.MkdirAll(loc.Dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(loc.Dir, "post-commit"), []byte(original), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ res, err := InstallHooks(ctx, repo, InstallOptions{BeaconPath: bin})
+ if err != nil || res.Reports[0].Action != "added" {
+ t.Fatalf("install %+v %v", res, err)
+ }
+ r.write("a", "1")
+ r.commitWithEnv("c")
+ if len(readCalls(t, calls)) != 1 {
+ t.Fatal("Beacon's hook did not run")
+ }
+ if data, _ := os.ReadFile(marker); string(data) != "ran\n" {
+ t.Fatalf("the existing hook did not run: %q", data)
+ }
+
+ rm, err := RemoveHooks(ctx, repo)
+ if err != nil || rm.Reports[0].Action != "removed" || !rm.RewriteRefRemoved {
+ t.Fatalf("remove %+v %v", rm, err)
+ }
+ after, _ := os.ReadFile(filepath.Join(loc.Dir, "post-commit"))
+ if string(after) != original {
+ t.Fatalf("remove did not restore the hook:\n%q\nwant\n%q", after, original)
+ }
+ if _, err := os.Stat(filepath.Join(loc.Dir, "beacon-post-commit")); !os.IsNotExist(err) {
+ t.Fatal("script left behind")
+ }
+}
+
+func TestRemoveHooksDeletesAHookItCreatedAndKeepsOtherRewriteRefs(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ bin, _ := fakeBeacon(t, filepath.Join(t.TempDir(), "bin"))
+ repo := r.open()
+ r.git("config", "--add", "notes.rewriteRef", "refs/notes/commits")
+ if _, err := InstallHooks(ctx, repo, InstallOptions{BeaconPath: bin}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := RemoveHooks(ctx, repo); err != nil {
+ t.Fatal(err)
+ }
+ loc, _ := ResolveHooks(ctx, repo)
+ if _, err := os.Stat(filepath.Join(loc.Dir, "post-commit")); !os.IsNotExist(err) {
+ t.Fatal("a hook that held only Beacon's block should be deleted")
+ }
+ if got := r.git("config", "--get-all", "notes.rewriteRef"); got != "refs/notes/commits" {
+ t.Fatalf("rewriteRef %q", got)
+ }
+ // Removing twice is fine.
+ again, err := RemoveHooks(ctx, repo)
+ if err != nil || again.Reports[0].Action != "absent" || again.RewriteRefRemoved {
+ t.Fatalf("second remove %+v %v", again, err)
+ }
+}
+
+func TestInstallHooksRefusesANonShellHook(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ repo := r.open()
+ loc, _ := ResolveHooks(ctx, repo)
+ _ = os.MkdirAll(loc.Dir, 0o755)
+ python := "#!/usr/bin/env python3\nprint('hi')\n"
+ if err := os.WriteFile(filepath.Join(loc.Dir, "post-commit"), []byte(python), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ _, err := InstallHooks(ctx, repo, InstallOptions{BeaconPath: "/nonexistent/beacon"})
+ if !errors.Is(err, ErrForeignHook) {
+ t.Fatalf("got %v, want ErrForeignHook", err)
+ }
+ if data, _ := os.ReadFile(filepath.Join(loc.Dir, "post-commit")); string(data) != python {
+ t.Fatal("the python hook was modified")
+ }
+ if _, err := os.Stat(filepath.Join(loc.Dir, "beacon-post-commit")); !os.IsNotExist(err) {
+ t.Fatal("a refusal must not leave a script behind")
+ }
+ if out, _ := r.gitClient().Run(ctx, nil, "config", "--get-all", "notes.rewriteRef"); out != "" {
+ t.Fatal("a refusal must not change config")
+ }
+}
+
+func TestShellShebangs(t *testing.T) {
+ for line, want := range map[string]bool{
+ "#!/bin/sh": true, "#!/bin/bash": true, "#!/usr/bin/env bash": true, "#!/usr/bin/env -S bash -e": true,
+ "#! /bin/sh": true, "#!/bin/zsh": true, "#!/usr/local/bin/dash": true,
+ "#!/usr/bin/env python3": false, "#!/usr/bin/env node": false, "#!/usr/bin/perl": false, "#!/bin/fish": false,
+ "#!/usr/bin/shellcheck": false,
+ } {
+ if got := shellShebang.MatchString(line); got != want {
+ t.Errorf("%q: got %v, want %v", line, got, want)
+ }
+ }
+}
+
+func TestInstallHooksHonorsCoreHooksPath(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ bin, calls := fakeBeacon(t, filepath.Join(t.TempDir(), "bin"))
+ r.git("config", "core.hooksPath", ".husky")
+ repo := r.open()
+ _, err := InstallHooks(ctx, repo, InstallOptions{BeaconPath: bin})
+ if !errors.Is(err, ErrHooksPathSet) {
+ t.Fatalf("got %v, want ErrHooksPathSet", err)
+ }
+ if _, err := os.Stat(filepath.Join(r.root, ".husky")); !os.IsNotExist(err) {
+ t.Fatal("a refusal must not create the directory")
+ }
+ res, err := InstallHooks(ctx, repo, InstallOptions{BeaconPath: bin, AllowHooksPath: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := filepath.Join(r.root, ".husky", "post-commit"); res.Reports[0].Path != want {
+ t.Fatalf("installed at %s, want %s", res.Reports[0].Path, want)
+ }
+ r.write("a", "1")
+ r.commitWithEnv("c")
+ if len(readCalls(t, calls)) != 1 {
+ t.Fatal("hook in core.hooksPath did not run")
+ }
+}
+
+func TestInstallHooksFromALinkedWorktree(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ bin, calls := fakeBeacon(t, filepath.Join(t.TempDir(), "bin"))
+ r.write("a", "1")
+ r.commitAt("init", t0)
+ wt := filepath.Join(filepath.Dir(r.root), "wt")
+ r.git("worktree", "add", "-q", "-b", "feature", wt)
+ wtRepo, err := OpenRepo(ctx, Git{Dir: wt, Env: r.env})
+ if err != nil {
+ t.Fatal(err)
+ }
+ res, err := InstallHooks(ctx, wtRepo, InstallOptions{BeaconPath: bin})
+ if err != nil {
+ t.Fatal(err)
+ }
+ common, _ := filepath.EvalSymlinks(filepath.Join(r.root, ".git", "hooks"))
+ got, _ := filepath.EvalSymlinks(filepath.Dir(res.Reports[0].Path))
+ if got != common {
+ t.Fatalf("installed in %s, want the shared %s", got, common)
+ }
+ // A commit in either worktree runs the hook, from that worktree.
+ w := &testRepo{t: t, root: wt, env: r.env}
+ w.write("b", "1")
+ w.commitWithEnv("in worktree")
+ r.write("c", "1")
+ r.commitWithEnv("in main")
+ callsSeen := readCalls(t, calls)
+ wtReal, _ := filepath.EvalSymlinks(wt)
+ rootReal, _ := filepath.EvalSymlinks(r.root)
+ if len(callsSeen) != 2 || !strings.HasPrefix(callsSeen[0], wtReal+" ") || !strings.HasPrefix(callsSeen[1], rootReal+" ") {
+ t.Fatalf("calls %q", callsSeen)
+ }
+}
+
+func TestHookScriptDisableAndPathFallback(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ binDir := filepath.Join(t.TempDir(), "bin")
+ _, calls := fakeBeacon(t, binDir)
+ repo := r.open()
+ // The recorded path is gone (an upgrade moved the binary); beacon on PATH is used instead.
+ if _, err := InstallHooks(ctx, repo, InstallOptions{BeaconPath: "/nonexistent/beacon"}); err != nil {
+ t.Fatal(err)
+ }
+ path := "PATH=" + binDir + string(os.PathListSeparator) + os.Getenv("PATH")
+ r.write("a", "1")
+ r.commitWithEnv("disabled", path, DisableEnv+"=0")
+ if len(readCalls(t, calls)) != 0 {
+ t.Fatal("BEACON_GIT_HOOKS=0 must skip the hook")
+ }
+ r.write("a", "2")
+ r.commitWithEnv("enabled", path)
+ if len(readCalls(t, calls)) != 1 {
+ t.Fatal("the hook did not fall back to beacon on PATH")
+ }
+ // With no beacon anywhere the hook is a quiet no-op, and the commit still succeeds.
+ r.write("a", "3")
+ r.commitWithEnv("no beacon", "PATH=/usr/bin:/bin")
+}
+
+func TestHookStatusDetectsABrokenInstall(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ bin, _ := fakeBeacon(t, filepath.Join(t.TempDir(), "bin"))
+ repo := r.open()
+ if st, _ := HookStatus(ctx, repo); st.Installed() {
+ t.Fatal("fresh repository reports installed")
+ }
+ res, err := InstallHooks(ctx, repo, InstallOptions{BeaconPath: bin})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Remove(res.Reports[0].Script); err != nil {
+ t.Fatal(err)
+ }
+ st, err := HookStatus(ctx, repo)
+ if err != nil || st.Installed() || !st.States[0].BlockPresent || st.States[0].ScriptExists {
+ t.Fatalf("status %+v %v", st, err)
+ }
+ // Setup repairs it.
+ if _, err := InstallHooks(ctx, repo, InstallOptions{BeaconPath: bin}); err != nil {
+ t.Fatal(err)
+ }
+ if st, _ := HookStatus(ctx, repo); !st.Installed() {
+ t.Fatal("setup did not repair the install")
+ }
+}
+
+func TestReplayInProgress(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ repo := r.open()
+ r.write("f", "base\n")
+ r.commitAt("base", t0)
+ if ReplayInProgress(ctx, repo) {
+ t.Fatal("idle repository reports a replay")
+ }
+ r.git("checkout", "-q", "-b", "side")
+ r.write("f", "side\n")
+ r.commitAt("side", t0.Add(time.Minute))
+ r.git("checkout", "-q", "main")
+ r.write("f", "main\n")
+ r.commitAt("main", t0.Add(2*time.Minute))
+ if _, err := r.gitClient().Run(ctx, nil, "cherry-pick", "side"); err == nil {
+ t.Fatal("expected a conflict")
+ }
+ if !ReplayInProgress(ctx, repo) {
+ t.Fatal("a conflicted cherry-pick is a replay")
+ }
+ r.git("cherry-pick", "--abort")
+ if _, err := r.gitClient().Run(ctx, nil, "rebase", "side"); err == nil {
+ t.Fatal("expected a conflict")
+ }
+ if !ReplayInProgress(ctx, repo) {
+ t.Fatal("a conflicted rebase is a replay")
+ }
+ r.git("rebase", "--abort")
+ if ReplayInProgress(ctx, repo) {
+ t.Fatal("an aborted rebase is over")
+ }
+}
+
+func TestAmendCarriesLinksThroughRewriteRef(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ bin, _ := fakeBeacon(t, filepath.Join(t.TempDir(), "bin"))
+ repo := r.open()
+ if _, err := InstallHooks(ctx, repo, InstallOptions{BeaconPath: bin}); err != nil {
+ t.Fatal(err)
+ }
+ r.write("a", "1")
+ r.commitWithEnv("c")
+ if _, err := AddLinks(ctx, repo.Git, r.git("rev-parse", "HEAD"), []Link{{"codex_cli", "s"}}); err != nil {
+ t.Fatal(err)
+ }
+ r.git("commit", "-q", "--amend", "-m", "c (amended)")
+ note, err := ReadNote(ctx, repo.Git, "HEAD")
+ if err != nil || !strings.Contains(note, "beacon:codex_cli/s") {
+ t.Fatalf("amended commit note %q %v", note, err)
+ }
+}
+
+func TestPostRewriteHookGetsGitsStdinAndArgument(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ testenv.RequirePOSIXExecutableFixtures(t)
+ dir := t.TempDir()
+ bin := filepath.Join(dir, "beacon")
+ seen := filepath.Join(dir, "seen.log")
+ // Record the arguments and whatever arrived on stdin.
+ script := "#!/bin/sh\necho \"args: $*\" >> " + shellQuote(seen) + "\ncat >> " + shellQuote(seen) + "\n"
+ if err := os.WriteFile(bin, []byte(script), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ repo := r.open()
+ if _, err := InstallHooks(ctx, repo, InstallOptions{BeaconPath: bin}); err != nil {
+ t.Fatal(err)
+ }
+ r.write("a", "1")
+ r.commitWithEnv("c")
+ old := r.git("rev-parse", "HEAD")
+ r.git("commit", "-q", "--amend", "-m", "c2")
+ amended := r.git("rev-parse", "HEAD")
+ data, _ := os.ReadFile(seen)
+ text := string(data)
+ if !strings.Contains(text, "args: git hook post-rewrite amend") || !strings.Contains(text, old+" "+amended) {
+ t.Fatalf("post-rewrite saw:\n%s", text)
+ }
+}
+
+func TestNormalizeNoteFoldsAnAmendedCopy(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ r.write("a", "1")
+ sha := r.commitAt("c", t0)
+ g := r.gitClient()
+ // What `git commit --amend` leaves: the hook's note, a blank line, then the copied old note.
+ r.git("notes", "--ref="+NotesRef, "add", "-m", "beacon:codex_cli/a\nbeacon:codex_cli/b\n\nbeacon:codex_cli/a", sha)
+ changed, err := NormalizeNote(ctx, g, sha)
+ if err != nil || !changed {
+ t.Fatalf("normalize: %v %v", changed, err)
+ }
+ if note, _ := ReadNote(ctx, g, sha); note != "beacon:codex_cli/a\nbeacon:codex_cli/b" {
+ t.Fatalf("note %q", note)
+ }
+ if changed, err := NormalizeNote(ctx, g, sha); err != nil || changed {
+ t.Fatalf("second normalize: %v %v", changed, err)
+ }
+ // A commit with no note stays without one.
+ r.write("a", "2")
+ bare := r.commitAt("d", t0.Add(time.Minute))
+ if changed, err := NormalizeNote(ctx, g, bare); err != nil || changed {
+ t.Fatalf("no-note normalize: %v %v", changed, err)
+ }
+ if note, _ := ReadNote(ctx, g, bare); note != "" {
+ t.Fatalf("note appeared: %q", note)
+ }
+}
diff --git a/cli/beacon/internal/gitlink/notes.go b/cli/beacon/internal/gitlink/notes.go
index 91e499aa..1f98882d 100644
--- a/cli/beacon/internal/gitlink/notes.go
+++ b/cli/beacon/internal/gitlink/notes.go
@@ -43,11 +43,6 @@ func readNote(ctx context.Context, g Git, ref, commit string) (string, error) {
}
// AddLinks merges links into commit's note and reports whether the note changed.
-//
-// The update is a compare-and-swap on NotesRef: the new notes commit is built on a private working
-// ref and then moved into place only if NotesRef still points where it did when the transaction
-// began. Two hooks committing at once in two worktrees of one repository therefore never lose each
-// other's links; the loser rebuilds on the winner and tries again.
func AddLinks(ctx context.Context, g Git, commit string, links []Link) (bool, error) {
var valid []Link
for _, link := range links {
@@ -58,13 +53,31 @@ func AddLinks(ctx context.Context, g Git, commit string, links []Link) (bool, er
if len(valid) == 0 {
return false, nil
}
+ return UpdateNote(ctx, g, commit, func(note string) string { return MergeNote(note, valid) })
+}
+
+// NormalizeNote rewrites commit's note in MergeNote's normal form -- no blank lines, no repeated
+// link -- and reports whether it changed. `git commit --amend` leaves the amended commit's note
+// concatenated onto the one the post-commit hook just wrote; this folds the two back into one.
+func NormalizeNote(ctx context.Context, g Git, commit string) (bool, error) {
+ return UpdateNote(ctx, g, commit, normalizeNote)
+}
+
+// UpdateNote replaces commit's note with update(note) and reports whether it changed. An update
+// returning an empty note removes it.
+//
+// The update is a compare-and-swap on NotesRef: the new notes commit is built on a private working
+// ref and then moved into place only if NotesRef still points where it did when the transaction
+// began. Two hooks committing at once in two worktrees of one repository therefore never lose each
+// other's links; the loser rebuilds on the winner and tries again.
+func UpdateNote(ctx context.Context, g Git, commit string, update func(string) string) (bool, error) {
token, err := txToken()
if err != nil {
return false, err
}
var lastErr error
for attempt := 1; attempt <= noteAttempts; attempt++ {
- changed, err := addLinksOnce(ctx, g, commit, valid, txRefPrefix+token+"-"+strconv.Itoa(attempt))
+ changed, err := updateNoteOnce(ctx, g, commit, update, txRefPrefix+token+"-"+strconv.Itoa(attempt))
if err == nil {
return changed, nil
}
@@ -78,7 +91,7 @@ func AddLinks(ctx context.Context, g Git, commit string, links []Link) (bool, er
var errRefMoved = errors.New("notes ref moved during update")
-func addLinksOnce(ctx context.Context, g Git, commit string, links []Link, txRef string) (changed bool, err error) {
+func updateNoteOnce(ctx context.Context, g Git, commit string, update func(string) string, txRef string) (changed bool, err error) {
base, err := resolveRef(ctx, g, NotesRef)
if err != nil {
return false, err
@@ -100,14 +113,19 @@ func addLinksOnce(ctx context.Context, g Git, commit string, links []Link, txRef
if err != nil {
return false, err
}
- merged := MergeNote(current, links)
- if merged == normalizeNote(current) {
+ next := update(current)
+ // git stores a note with exactly one trailing newline and shows it without; compare that way.
+ if strings.TrimRight(next, "\n") == strings.TrimRight(current, "\n") {
return false, nil
}
- if _, err := g.Run(ctx, []byte(merged), "notes", "--ref="+txRef, "add", "--force", "--file=-", commit); err != nil {
+ if strings.TrimSpace(next) == "" {
+ if _, err := g.Run(ctx, nil, "notes", "--ref="+txRef, "remove", "--ignore-missing", commit); err != nil {
+ return false, err
+ }
+ } else if _, err := g.Run(ctx, []byte(next), "notes", "--ref="+txRef, "add", "--force", "--file=-", commit); err != nil {
return false, err
}
- next, err := resolveRef(ctx, g, txRef)
+ next, err = resolveRef(ctx, g, txRef)
if err != nil {
return false, err
}
diff --git a/docs/cli/git.mdx b/docs/cli/git.mdx
index bdce3326..55ea6696 100644
--- a/docs/cli/git.mdx
+++ b/docs/cli/git.mdx
@@ -8,10 +8,15 @@ description: "Link git commits to the agent sessions that wrote them"
`beacon git` records which agent sessions produced a commit, as a git note on the commit.
```bash title="Command syntax"
+beacon git setup [flags]
+beacon git status [flags]
+beacon git remove [flags]
beacon git link [<commit>] [flags]
beacon git notes [<revision>] [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.
+
A link names a session by its harness and session id, for example `beacon:claude_code/0f8e2c1a-…`. The note carries identifiers only, never prompts, output, or diffs: notes can be shared with a remote, and the session's content stays in the local runtime log. `beacon handoff export <session-id>` reads a linked session back.
## How sessions are matched to a commit
@@ -26,6 +31,61 @@ For a merge commit, only files where the result differs from every parent count:
A link is an inference, not an observation. A session that edited a file a person then rewrote by hand is still linked, and a session that wrote nothing the commit kept is not.
+## `beacon git setup`
+
+Installs Beacon's git hooks in the current repository.
+
+```bash
+cd my-repo
+beacon git setup
+```
+
+```text title="Example output"
+created /work/my-repo/.git/hooks/post-commit (calls beacon-post-commit)
+created /work/my-repo/.git/hooks/post-rewrite (calls beacon-post-rewrite)
+set notes.rewriteRef = refs/notes/beacon
+```
+
+- **post-commit** links the new commit, exactly as `beacon git link` would. It reads the local runtime log and writes a git note, typically in tens of milliseconds, and gives up after three seconds rather than hold a commit. It never prints, never touches the network, and never fails a commit.
+- **post-rewrite** runs after `git commit --amend` and `git rebase` and tidies the note on each rewritten commit, folding the note git copied from the old commit into the one the post-commit hook just wrote.
+- **`notes.rewriteRef`** makes git copy a commit's links to the commit that replaces it when you amend or rebase.
+
+Rebases, cherry-picks and reverts are not attributed afresh: they replay existing commits, and their links, if any, travel with `notes.rewriteRef`.
+
+A hook already in place keeps working. Beacon writes its own `beacon-post-commit` and `beacon-post-rewrite` scripts and adds a short marked block to the top of the hook that calls them, so a hook ending in `exit 0` still runs Beacon's part. Only shell hooks are edited: if the hook is another language, `setup` stops and prints the line to add yourself. The scripts call Beacon by the absolute path it had at setup and fall back to `beacon` on `PATH`, so a GUI git client without Beacon on its `PATH` still links commits.
+
+Hooks live in the repository's shared hooks directory, so one `setup` covers every linked worktree.
+
+| Flag | Description |
+|------|-------------|
+| `--hooks-path` | Install into the `core.hooksPath` directory when one is set (see below) |
+| `-C`, `--cwd <dir>` | Repository to operate on |
+| `--json` | Print what was installed as JSON |
+
+Set `BEACON_GIT_HOOKS=0` to skip the hooks for one command:
+
+```bash
+BEACON_GIT_HOOKS=0 git commit -m "..."
+```
+
+### Hook managers and `core.hooksPath`
+
+Tools such as husky and lefthook point `core.hooksPath` at a directory they own, often one tracked in the repository. `setup` refuses to write there by default and prints the line to add to that tool's `post-commit` hook instead:
+
+```bash
+beacon git hook post-commit || true
+```
+
+Pass `--hooks-path` to install into that directory anyway.
+
+## `beacon git status`
+
+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.
+
+## `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`.
+
## `beacon git link`
Links a commit (default `HEAD`) and writes the note.