Skip to content

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

Keep git's stdin for the repository's own pre-push and post-rewrite hooks

Claude2587fed9b7c6
diff --git a/cli/beacon/cmd/git_hooks.go b/cli/beacon/cmd/git_hooks.go
index 34ac7486..65424f14 100644
--- a/cli/beacon/cmd/git_hooks.go
+++ b/cli/beacon/cmd/git_hooks.go
@@ -248,6 +248,8 @@ func runGitStatus(cmd *cobra.Command, _ []string) error {
for _, st := range status.States {
state := "not installed"
switch {
+ case st.Installed && st.Outdated:
+ state = "installed, from an earlier Beacon (run `beacon git setup` to update it)"
case st.Installed:
state = "installed"
case st.BlockPresent:
diff --git a/cli/beacon/cmd/git_share.go b/cli/beacon/cmd/git_share.go
index 9264d32a..4e0f1f2a 100644
--- a/cli/beacon/cmd/git_share.go
+++ b/cli/beacon/cmd/git_share.go
@@ -129,15 +129,18 @@ func runGitHookPrePush(cmd *cobra.Command, args []string) error {
// A hook has no terminal to ask for credentials on; git's own push has already authenticated,
// and a credential helper answers the same way for this one.
repo.Git = repo.Git.WithExtraEnv("GIT_TERMINAL_PROMPT=0")
- stdin := readHookStdin(cmd.InOrStdin())
- if enabled, visibility := gitlink.ShareSessionsConfig(ctx, repo); enabled && stdin != "" {
- // Sharing sessions gets the budget less what pushing the notes ref needs, so the links
- // (with whatever URLs it recorded) still reach the remote.
- shareCtx, cancelShare := context.WithTimeout(ctx, gitShareBudget-gitShareNotesReserve)
- if _, err := gitShareSessionsOnPush(shareCtx, repo, args[0], stdin, visibility); err != nil && shareCtx.Err() == nil {
- fmt.Fprintf(cmd.ErrOrStderr(), "beacon: linked sessions were not all shared: %s\n", gitlink.ErrorSummary(err))
+ // git's stdin (the refs being pushed) is read only when sessions are shared; the hook block
+ // hands Beacon a copy and replays the original to the rest of the repository's hook.
+ if enabled, visibility := gitlink.ShareSessionsConfig(ctx, repo); enabled {
+ if stdin := readHookStdin(cmd.InOrStdin()); stdin != "" {
+ // Sharing sessions gets the budget less what pushing the notes ref needs, so the links
+ // (with whatever URLs it recorded) still reach the remote.
+ shareCtx, cancelShare := context.WithTimeout(ctx, gitShareBudget-gitShareNotesReserve)
+ if _, err := gitShareSessionsOnPush(shareCtx, repo, args[0], stdin, visibility); err != nil && shareCtx.Err() == nil {
+ fmt.Fprintf(cmd.ErrOrStderr(), "beacon: linked sessions were not all shared: %s\n", gitlink.ErrorSummary(err))
+ }
+ cancelShare()
}
- cancelShare()
}
if _, err := gitlink.PushNotes(ctx, repo, args[0]); err != nil {
fmt.Fprintf(cmd.ErrOrStderr(), "beacon: commit links were not shared with %s: %s\n", args[0], gitlink.ErrorSummary(err))
diff --git a/cli/beacon/internal/gitlink/hooks.go b/cli/beacon/internal/gitlink/hooks.go
index 83f66327..7573a689 100644
--- a/cli/beacon/internal/gitlink/hooks.go
+++ b/cli/beacon/internal/gitlink/hooks.go
@@ -213,7 +213,7 @@ func installHook(dir, hook, beaconPath string) (HookReport, error) {
if err != nil && !os.IsNotExist(err) {
return report, err
}
- block := hookBlock(scriptName)
+ block := hookBlock(hook)
var next string
switch {
case os.IsNotExist(err) || strings.TrimSpace(string(existing)) == "":
@@ -291,14 +291,66 @@ func checkHookEditable(path string) error {
return nil
}
-func hookBlock(scriptName string) string {
+func hookBlock(hook string) string {
+ scriptName := HookScriptPrefix + hook
+ if !hookReadsStdin(hook) {
+ 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"
+ }
+ // git writes this hook's input to stdin once, and the rest of the hook (`git lfs pre-push`, a
+ // hook manager) needs it as much as Beacon does. The block copies it to a temporary file, gives
+ // Beacon the copy, and points the hook's own stdin at the file before the rest runs. The file
+ // is unlinked once it is open; the descriptor keeps it readable. When it cannot be copied,
+ // Beacon gets nothing and stdin is left alone.
+ feed := ` "$beacon_hook" "$@" <"$beacon_stdin"` + "\n"
+ if hook == ShareHook {
+ // The refs being pushed matter to Beacon only when it shares sessions on push.
+ feed = ` if [ "$(git config --local --get ` + ShareSessionsKey + ` 2>/dev/null)" = "true" ]; then` + "\n" +
+ ` "$beacon_hook" "$@" <"$beacon_stdin"` + "\n" +
+ " else\n" +
+ ` "$beacon_hook" "$@" </dev/null` + "\n" +
+ " fi\n"
+ }
return hookBlockStart + "\n" +
- `if [ -x "$(git rev-parse --git-path hooks)/` + scriptName + `" ]; then` + "\n" +
- ` "$(git rev-parse --git-path hooks)/` + scriptName + `" "$@"` + "\n" +
+ `beacon_hook="$(git rev-parse --git-path hooks)/` + scriptName + `"` + "\n" +
+ `if [ -x "$beacon_hook" ]; then` + "\n" +
+ ` beacon_stdin="$(mktemp "${TMPDIR:-/tmp}/beacon-hook.XXXXXX" 2>/dev/null)" || beacon_stdin=""` + "\n" +
+ ` if [ -n "$beacon_stdin" ]; then` + "\n" +
+ ` trap 'rm -f "$beacon_stdin"' EXIT` + "\n" +
+ ` cat >"$beacon_stdin" || :` + "\n" +
+ feed +
+ ` exec 0<"$beacon_stdin"` + "\n" +
+ ` rm -f "$beacon_stdin"` + "\n" +
+ " trap - EXIT\n" +
+ " else\n" +
+ ` "$beacon_hook" "$@" </dev/null` + "\n" +
+ " fi\n" +
"fi\n" +
+ "unset beacon_hook beacon_stdin\n" +
hookBlockEnd + "\n"
}
+// hookReadsStdin is true for the hooks git gives input on stdin: post-rewrite (the rewritten
+// commits) and pre-push (the refs being pushed).
+func hookReadsStdin(hook string) bool { return hook == "post-rewrite" || hook == ShareHook }
+
+// blockOutdated is true when script carries a Beacon block other than the one this version
+// writes, which `beacon git setup` refreshes.
+func blockOutdated(script, hook string) bool {
+ start := strings.Index(script, hookBlockStart)
+ if start < 0 {
+ return false
+ }
+ end := strings.Index(script[start:], hookBlockEnd)
+ if end < 0 {
+ return true
+ }
+ return script[start:start+end+len(hookBlockEnd)]+"\n" != hookBlock(hook)
+}
+
// 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 {
@@ -452,6 +504,8 @@ type HookState struct {
Installed bool `json:"installed"`
BlockPresent bool `json:"block_present"`
ScriptExists bool `json:"script_exists"`
+ // Outdated is true when the hook carries a block an earlier Beacon wrote; setup refreshes it.
+ Outdated bool `json:"outdated,omitempty"`
}
// Status is the state of Beacon's git integration in one repository.
@@ -495,6 +549,7 @@ func HookStatus(ctx context.Context, repo Repo) (Status, error) {
st := HookState{Hook: hook}
if data, err := os.ReadFile(filepath.Join(loc.Dir, hook)); err == nil {
st.BlockPresent = strings.Contains(string(data), hookBlockStart)
+ st.Outdated = blockOutdated(string(data), hook)
}
if _, err := os.Stat(filepath.Join(loc.Dir, HookScriptPrefix+hook)); err == nil {
st.ScriptExists = true
diff --git a/cli/beacon/internal/gitlink/hooks_test.go b/cli/beacon/internal/gitlink/hooks_test.go
index c18ebb31..7cf4b1d4 100644
--- a/cli/beacon/internal/gitlink/hooks_test.go
+++ b/cli/beacon/internal/gitlink/hooks_test.go
@@ -541,3 +541,109 @@ func TestReplayDetectionWithoutAReflog(t *testing.T) {
t.Fatal("a revert must be recognized by its message when there is no reflog")
}
}
+
+// The pre-push block must leave git's stdin to the repository's own pre-push hook (`git lfs
+// pre-push` reads it), whether or not Beacon reads a copy to share sessions.
+func TestPrePushBlockKeepsStdinForTheRepositorysHook(t *testing.T) {
+ for _, shareSessions := range []bool{false, true} {
+ t.Run(map[bool]string{false: "sessions off", true: "sessions on"}[shareSessions], func(t *testing.T) {
+ testenv.RequirePOSIXExecutableFixtures(t)
+ r := newTestRepo(t)
+ ctx := context.Background()
+ dir := t.TempDir()
+ tmp := filepath.Join(dir, "tmp")
+ if err := os.MkdirAll(tmp, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ r.env = append(r.env, "TMPDIR="+tmp)
+ // The fake beacon reads all of its stdin, as `beacon git hook pre-push` does.
+ beaconSaw := filepath.Join(dir, "beacon-stdin")
+ bin := filepath.Join(dir, "beacon")
+ if err := os.WriteFile(bin, []byte("#!/bin/sh\ncat > "+shellQuote(beaconSaw)+"\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ hooks := filepath.Join(r.root, ".git", "hooks")
+ userSaw := filepath.Join(dir, "user-stdin")
+ if err := os.MkdirAll(hooks, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ userHook := "#!/bin/sh\ncat > " + shellQuote(userSaw) + "\nexit 0\n"
+ if err := os.WriteFile(filepath.Join(hooks, ShareHook), []byte(userHook), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ repo := r.open()
+ on := true
+ if _, err := InstallHooks(ctx, repo, InstallOptions{BeaconPath: bin, ShareNotes: &on}); err != nil {
+ t.Fatal(err)
+ }
+ if err := SetShareSessions(ctx, repo, shareSessions, ""); err != nil {
+ t.Fatal(err)
+ }
+ remote := filepath.Join(dir, "remote.git")
+ r.git("init", "-q", "--bare", remote)
+ r.git("remote", "add", "origin", remote)
+ r.write("f", "1")
+ head := r.commitAt("first", t0)
+ r.git("push", "-q", "origin", "main")
+
+ want := "refs/heads/main " + head + " refs/heads/main "
+ got, err := os.ReadFile(userSaw)
+ if err != nil || !strings.HasPrefix(string(got), want) {
+ t.Fatalf("the repository's hook read %q (%v), want a line starting %q", got, err, want)
+ }
+ saw, err := os.ReadFile(beaconSaw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if shareSessions != strings.HasPrefix(string(saw), want) {
+ t.Fatalf("beacon read %q with sessions shared = %v", saw, shareSessions)
+ }
+ if leftovers, _ := filepath.Glob(filepath.Join(tmp, "beacon-hook.*")); len(leftovers) > 0 {
+ t.Fatalf("temporary files left behind: %v", leftovers)
+ }
+ })
+ }
+}
+
+// A block an earlier Beacon wrote shows as outdated, and setup replaces it with the current one.
+func TestStatusFlagsAnOutdatedBlockAndSetupRefreshesIt(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ bin, _ := fakeBeacon(t, t.TempDir())
+ repo := r.open()
+ if _, err := InstallHooks(ctx, repo, InstallOptions{BeaconPath: bin}); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(r.root, ".git", "hooks", "post-rewrite")
+ old := hookBlockStart + "\nif [ -x \"$(git rev-parse --git-path hooks)/beacon-post-rewrite\" ]; then\n" +
+ " \"$(git rev-parse --git-path hooks)/beacon-post-rewrite\" \"$@\"\nfi\n" + hookBlockEnd + "\n"
+ if err := os.WriteFile(path, []byte("#!/bin/sh\n"+old+"echo mine\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ outdated := func() bool {
+ st, err := HookStatus(ctx, repo)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, s := range st.States {
+ if s.Hook == "post-rewrite" {
+ return s.Outdated
+ }
+ }
+ t.Fatal("no post-rewrite state")
+ return false
+ }
+ if !outdated() {
+ t.Fatal("the old block is not reported as outdated")
+ }
+ if _, err := InstallHooks(ctx, repo, InstallOptions{BeaconPath: bin}); err != nil {
+ t.Fatal(err)
+ }
+ if outdated() {
+ t.Fatal("setup did not refresh the block")
+ }
+ data, _ := os.ReadFile(path)
+ if !strings.HasSuffix(string(data), "echo mine\n") || strings.Count(string(data), hookBlockStart) != 1 {
+ t.Fatalf("hook after refresh:\n%s", data)
+ }
+}
diff --git a/cli/beacon/internal/gitlink/share.go b/cli/beacon/internal/gitlink/share.go
index 41cdea4a..20ccb8f3 100644
--- a/cli/beacon/internal/gitlink/share.go
+++ b/cli/beacon/internal/gitlink/share.go
@@ -314,9 +314,9 @@ func SetShareSessions(ctx context.Context, repo Repo, enabled bool, visibility s
// PushedCommits lists the commits a pre-push hook's stdin says are being pushed: for each
// `<local-ref> <local-sha> <remote-ref> <remote-sha>` line, the commits reachable from the local
-// sha and not from the remote sha (or, for a new remote branch, from any of the remote's
-// tracking branches when remote is a configured remote). Deletions push nothing. At most limit
-// commits, newest first.
+// sha and not from the remote sha (or, for a new remote branch or a remote sha this clone does not
+// have, from any of the remote's tracking branches when remote is a configured remote). Deletions
+// push nothing. At most limit commits, newest first.
func PushedCommits(ctx context.Context, repo Repo, remote string, stdin string, limit int) ([]string, error) {
if limit <= 0 {
limit = 100
@@ -331,9 +331,11 @@ func PushedCommits(ctx context.Context, repo Repo, remote string, stdin string,
}
args := []string{"rev-list", "--max-count=" + strconv.Itoa(limit), fields[1], "--not"}
switch {
- case !isZeroSHA(fields[3]):
+ case !isZeroSHA(fields[3]) && hasCommit(ctx, repo, fields[3]):
args = append(args, fields[3])
case named:
+ // A new remote branch, or a force push over commits this clone never fetched: the
+ // remote's tip is not here to exclude, so exclude everything already on the remote.
args = append(args, "--remotes="+remote)
}
list, err := repo.Git.Run(ctx, nil, args...)
@@ -353,6 +355,12 @@ func PushedCommits(ctx context.Context, repo Repo, remote string, stdin string,
return out, nil
}
+// hasCommit reports whether sha names a commit present in this repository.
+func hasCommit(ctx context.Context, repo Repo, sha string) bool {
+ _, err := repo.Git.Run(ctx, nil, "cat-file", "-e", sha+"^{commit}")
+ return err == nil
+}
+
func isSHA(s string) bool {
if len(s) != 40 && len(s) != 64 {
return false
diff --git a/cli/beacon/internal/gitlink/share_test.go b/cli/beacon/internal/gitlink/share_test.go
index e918f472..95d83f0d 100644
--- a/cli/beacon/internal/gitlink/share_test.go
+++ b/cli/beacon/internal/gitlink/share_test.go
@@ -9,6 +9,7 @@ import (
"sort"
"strings"
"testing"
+ "time"
)
// team is a bare remote with two clones of it, alice and bob, sharing a first commit.
@@ -357,3 +358,29 @@ func TestPlainSetupIgnoresALeftoverShareScriptBesideAForeignPrePush(t *testing.T
t.Fatalf("explicit share: %v", err)
}
}
+
+// A force push over commits this clone never fetched names a remote sha that is not here; the
+// pushed commits are then the ones not already on any of the remote's tracking branches.
+func TestPushedCommitsForcePushOverUnfetchedRemoteTip(t *testing.T) {
+ tm := newTeam(t)
+ ctx := context.Background()
+ tm.alice.write("f", "alice")
+ unfetched := tm.alice.commitAt("alice", t0.Add(time.Minute))
+ tm.alice.git("push", "-q", "origin", "main")
+
+ tm.bob.git("config", "commit.gpgsign", "false")
+ tm.bob.write("f", "bob")
+ mine := tm.bob.commitAt("bob", t0.Add(2*time.Minute))
+ bob := tm.bob.open()
+ if _, err := bob.Git.Run(ctx, nil, "cat-file", "-e", unfetched+"^{commit}"); err == nil {
+ t.Fatal("bob should not have alice's commit")
+ }
+ stdin := "refs/heads/main " + mine + " refs/heads/main " + unfetched + "\n"
+ got, err := PushedCommits(ctx, bob, "origin", stdin, 0)
+ if err != nil {
+ t.Fatalf("PushedCommits: %v", err)
+ }
+ if !reflect.DeepEqual(got, []string{mine}) {
+ t.Fatalf("pushed %v, want [%s]", got, mine)
+ }
+}