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
Resolve branch from local git checkout in hook events
Claude71fdd0fd167c
diff --git a/cli/beacon-hooks/cmd/endpoint_events.go b/cli/beacon-hooks/cmd/endpoint_events.goindex 0f28f10d..b91f60d9 100644--- a/cli/beacon-hooks/cmd/endpoint_events.go+++ b/cli/beacon-hooks/cmd/endpoint_events.go@@ -13,6 +13,7 @@ import ("time""github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/cloudshuttle"+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/git""github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging")@@ -38,11 +39,12 @@ func emitHookEvent(logger *logging.Logger, action, category, severity, message sif model := getFirstStr(input, "model"); model != "" {fields["model"] = model}- if cwd := resolveCwd(input, platformFlag); cwd != "" {+ cwd := resolveCwd(input, platformFlag)+ if cwd != "" {fields["session"] = mergeNested(fields["session"], map[string]interface{}{"working_directory": cwd})fields["repository"] = cwd}- if branch := getFirstStr(input, "branch", "git_branch"); branch != "" {+ if branch := resolveBranch(input, cwd); branch != "" {fields["branch"] = branch}if err := logger.EndpointEvent(action, category, severity, message, fields); err != nil {@@ -50,6 +52,28 @@ func emitHookEvent(logger *logging.Logger, action, category, severity, message s}}+// resolveBranch prefers a runtime-provided branch and otherwise derives the+// checked-out branch from the event's working directory. Runtime-provided+// values pass through even when local git metadata enrichment is disabled.+func resolveBranch(input map[string]interface{}, cwd string) string {+ if branch := getFirstStr(input, "branch", "git_branch"); branch != "" {+ return branch+ }+ if cwd == "" || gitMetadataDisabled() {+ return ""+ }+ return git.CurrentBranch(cwd)+}++// gitMetadataDisabled accepts 1/true/yes, matching other Beacon disable flags.+func gitMetadataDisabled() bool {+ switch strings.ToLower(strings.TrimSpace(os.Getenv("BEACON_DISABLE_GIT_METADATA"))) {+ case "1", "true", "yes":+ return true+ }+ return false+}+func uploadCloudTelemetry(logger *logging.Logger, force bool) {ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()diff --git a/cli/beacon-hooks/cmd/endpoint_events_test.go b/cli/beacon-hooks/cmd/endpoint_events_test.goindex b9256a60..ec9d4041 100644--- a/cli/beacon-hooks/cmd/endpoint_events_test.go+++ b/cli/beacon-hooks/cmd/endpoint_events_test.go@@ -4,12 +4,118 @@ import ("context""os""os/exec"+ "path/filepath""reflect""testing""github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging")+func writeGitHead(t *testing.T, repo, head string) {+ t.Helper()+ gitDir := filepath.Join(repo, ".git")+ if err := os.MkdirAll(gitDir, 0o755); err != nil {+ t.Fatalf("mkdir %s: %v", gitDir, err)+ }+ if err := os.WriteFile(filepath.Join(gitDir, "HEAD"), []byte(head), 0o644); err != nil {+ t.Fatalf("write HEAD: %v", err)+ }+}++func TestResolveBranchPrefersRuntimeProvidedBranch(t *testing.T) {+ repo := t.TempDir()+ writeGitHead(t, repo, "ref: refs/heads/local-branch\n")++ got := resolveBranch(map[string]interface{}{"git_branch": "cloud-branch"}, repo)+ if got != "cloud-branch" {+ t.Fatalf("resolveBranch = %q, want runtime-provided cloud-branch", got)+ }+}++func TestResolveBranchReadsLocalCheckout(t *testing.T) {+ repo := t.TempDir()+ writeGitHead(t, repo, "ref: refs/heads/feature/local\n")++ got := resolveBranch(map[string]interface{}{}, repo)+ if got != "feature/local" {+ t.Fatalf("resolveBranch = %q, want feature/local", got)+ }+}++func TestResolveBranchOutsideRepo(t *testing.T) {+ if got := resolveBranch(map[string]interface{}{}, t.TempDir()); got != "" {+ t.Fatalf("resolveBranch = %q, want empty outside a repo", got)+ }+ if got := resolveBranch(map[string]interface{}{}, ""); got != "" {+ t.Fatalf("resolveBranch = %q, want empty without cwd", got)+ }+}++func TestResolveBranchDisabledByEnv(t *testing.T) {+ repo := t.TempDir()+ writeGitHead(t, repo, "ref: refs/heads/feature/local\n")++ for _, value := range []string{"1", "true", "YES"} {+ t.Setenv("BEACON_DISABLE_GIT_METADATA", value)+ if got := resolveBranch(map[string]interface{}{}, repo); got != "" {+ t.Fatalf("resolveBranch = %q, want empty with BEACON_DISABLE_GIT_METADATA=%s", got, value)+ }+ // Runtime-provided branch still passes through when disabled.+ if got := resolveBranch(map[string]interface{}{"git_branch": "cloud-branch"}, repo); got != "cloud-branch" {+ t.Fatalf("resolveBranch = %q, want runtime-provided branch to pass through", got)+ }+ }++ t.Setenv("BEACON_DISABLE_GIT_METADATA", "0")+ if got := resolveBranch(map[string]interface{}{}, repo); got != "feature/local" {+ t.Fatalf("resolveBranch = %q, want feature/local with disable flag off", got)+ }+}++func TestRunPromptSubmitEmitsLocalGitBranch(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "cursor"+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ repo := t.TempDir()+ writeGitHead(t, repo, "ref: refs/heads/feature/local\n")++ runHookWithInput(t, runPromptSubmit, map[string]interface{}{+ "conversation_id": "conv-branch",+ "hook_event_name": "beforeSubmitPrompt",+ "workspace_roots": []interface{}{repo},+ "prompt": "hello",+ })++ event := lastEndpointEvent(t, logPath)+ if got := event["branch"]; got != "feature/local" {+ t.Fatalf("branch = %q, want feature/local", got)+ }+ if got := event["repository"]; got != repo {+ t.Fatalf("repository = %q, want %q", got, repo)+ }+}++func TestRunPromptSubmitOmitsBranchOutsideRepo(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "cursor"+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ runHookWithInput(t, runPromptSubmit, map[string]interface{}{+ "conversation_id": "conv-no-repo",+ "hook_event_name": "beforeSubmitPrompt",+ "workspace_roots": []interface{}{t.TempDir()},+ "prompt": "hello",+ })++ event := lastEndpointEvent(t, logPath)+ if branch, ok := event["branch"]; ok {+ t.Fatalf("branch = %q, want no branch field outside a repo", branch)+ }+}+func TestToolFieldsMapsMCPGenAIStandardFields(t *testing.T) {tests := []struct {name stringdiff --git a/cli/beacon-hooks/internal/git/git.go b/cli/beacon-hooks/internal/git/git.goindex ee3a7843..2947bbaa 100644--- a/cli/beacon-hooks/internal/git/git.go+++ b/cli/beacon-hooks/internal/git/git.go@@ -2,12 +2,126 @@ package gitimport ("bufio"+ "io""os""path/filepath""regexp""strings")+// maxGitMetadataBytes caps reads of repository metadata files so hostile or+// corrupt .git contents cannot balloon hook memory or telemetry.+const maxGitMetadataBytes = 4096++// CurrentBranch returns the branch checked out in the repository containing+// cwd, reading HEAD directly so no git binary is required. It returns "" when+// cwd is not inside a git repository, HEAD is detached, or HEAD does not+// parse as a local branch ref.+func CurrentBranch(cwd string) string {+ headPath := findHeadFile(cwd)+ if headPath == "" {+ return ""+ }+ ref, ok := strings.CutPrefix(firstNonEmptyLine(readCapped(headPath)), "ref:")+ if !ok {+ return ""+ }+ branch, ok := strings.CutPrefix(strings.TrimSpace(ref), "refs/heads/")+ if !ok || !isValidBranchName(branch) {+ return ""+ }+ return branch+}++// findHeadFile walks up from cwd to the HEAD file of the innermost checkout.+// Unlike findGitDir, a worktree ".git" pointer file resolves to the+// per-worktree gitdir, which holds this checkout's HEAD; the shared commondir+// HEAD would report another worktree's branch.+func findHeadFile(cwd string) string {+ if cwd == "" {+ var err error+ cwd, err = os.Getwd()+ if err != nil {+ return ""+ }+ }++ dir := cwd+ for {+ gitPath := filepath.Join(dir, ".git")+ if info, err := os.Stat(gitPath); err == nil {+ if info.IsDir() {+ return filepath.Join(gitPath, "HEAD")+ }+ if gitdir := parseGitDirPointer(gitPath); gitdir != "" {+ head := filepath.Join(gitdir, "HEAD")+ if _, err := os.Stat(head); err == nil {+ return head+ }+ }+ }++ parent := filepath.Dir(dir)+ if parent == dir {+ return ""+ }+ dir = parent+ }+}++// parseGitDirPointer reads a ".git" pointer file ("gitdir: <path>") and+// returns the referenced gitdir as an absolute cleaned path, or "".+func parseGitDirPointer(dotGitFile string) string {+ gitdir, ok := strings.CutPrefix(firstNonEmptyLine(readCapped(dotGitFile)), "gitdir:")+ if !ok {+ return ""+ }+ gitdir = strings.TrimSpace(gitdir)+ if gitdir == "" {+ return ""+ }+ if !filepath.IsAbs(gitdir) {+ gitdir = filepath.Join(filepath.Dir(dotGitFile), gitdir)+ }+ return filepath.Clean(gitdir)+}++func readCapped(path string) string {+ f, err := os.Open(path)+ if err != nil {+ return ""+ }+ defer f.Close()+ data, err := io.ReadAll(io.LimitReader(f, maxGitMetadataBytes))+ if err != nil {+ return ""+ }+ return string(data)+}++func firstNonEmptyLine(content string) string {+ for _, line := range strings.Split(content, "\n") {+ if trimmed := strings.TrimSpace(line); trimmed != "" {+ return trimmed+ }+ }+ return ""+}++// isValidBranchName rejects ref names git itself would refuse, so malformed+// or hostile HEAD content never reaches telemetry.+func isValidBranchName(branch string) bool {+ if branch == "" || len(branch) > 255 {+ return false+ }+ for _, r := range branch {+ if r < 0x20 || r == 0x7f || r == ' ' {+ return false+ }+ }+ return true+}+// GetRemoteInfo returns the owner and repository name from the git remote origin.// Returns empty strings if not in a git repo or no origin remote is configured.// Supports both SSH ([email protected]:owner/name.git) and HTTPS (https://github.com/owner/name.git) URLs.@@ -71,27 +185,11 @@ func findGitDir(cwd string) string {// extracts the gitdir path, and resolves the common git directory// that contains the config with remote URLs.func resolveWorktreeGitDir(dotGitFile string) string {- data, err := os.ReadFile(dotGitFile)- if err != nil {- return ""- }-- // Parse "gitdir: <path>" from the .git file- line := strings.TrimSpace(string(data))- if !strings.HasPrefix(line, "gitdir:") {- return ""- }- gitdir := strings.TrimSpace(strings.TrimPrefix(line, "gitdir:"))+ gitdir := parseGitDirPointer(dotGitFile)if gitdir == "" {return ""}- // Resolve relative paths against the .git file's parent directory- if !filepath.IsAbs(gitdir) {- gitdir = filepath.Join(filepath.Dir(dotGitFile), gitdir)- }- gitdir = filepath.Clean(gitdir)-// In a worktree, gitdir points to e.g. /repo/.git/worktrees/foo// which contains a "commondir" file with a relative path to the shared .git dircommondirPath := filepath.Join(gitdir, "commondir")diff --git a/cli/beacon-hooks/internal/git/git_test.go b/cli/beacon-hooks/internal/git/git_test.gonew file mode 100644index 00000000..3f731c4f--- /dev/null+++ b/cli/beacon-hooks/internal/git/git_test.go@@ -0,0 +1,129 @@+package git++import (+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func writeTestFile(t *testing.T, path, content string) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatalf("mkdir %s: %v", filepath.Dir(path), err)+ }+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {+ t.Fatalf("write %s: %v", path, err)+ }+}++func TestCurrentBranchNormalRepo(t *testing.T) {+ repo := t.TempDir()+ writeTestFile(t, filepath.Join(repo, ".git", "HEAD"), "ref: refs/heads/main\n")++ if got := CurrentBranch(repo); got != "main" {+ t.Fatalf("CurrentBranch = %q, want main", got)+ }+}++func TestCurrentBranchWithSlashes(t *testing.T) {+ repo := t.TempDir()+ writeTestFile(t, filepath.Join(repo, ".git", "HEAD"), "ref: refs/heads/feature/custom-fields\n")++ if got := CurrentBranch(repo); got != "feature/custom-fields" {+ t.Fatalf("CurrentBranch = %q, want feature/custom-fields", got)+ }+}++func TestCurrentBranchWalksUpFromSubdirectory(t *testing.T) {+ repo := t.TempDir()+ writeTestFile(t, filepath.Join(repo, ".git", "HEAD"), "ref: refs/heads/main\n")+ nested := filepath.Join(repo, "pkg", "internal", "deep")+ if err := os.MkdirAll(nested, 0o755); err != nil {+ t.Fatalf("mkdir nested: %v", err)+ }++ if got := CurrentBranch(nested); got != "main" {+ t.Fatalf("CurrentBranch = %q, want main", got)+ }+}++func TestCurrentBranchDetachedHead(t *testing.T) {+ repo := t.TempDir()+ writeTestFile(t, filepath.Join(repo, ".git", "HEAD"), "0123456789abcdef0123456789abcdef01234567\n")++ if got := CurrentBranch(repo); got != "" {+ t.Fatalf("CurrentBranch = %q, want empty for detached HEAD", got)+ }+}++func TestCurrentBranchOutsideRepo(t *testing.T) {+ if got := CurrentBranch(t.TempDir()); got != "" {+ t.Fatalf("CurrentBranch = %q, want empty outside a repo", got)+ }+}++func TestCurrentBranchWorktreeUsesPerWorktreeHead(t *testing.T) {+ base := t.TempDir()+ mainRepo := filepath.Join(base, "main-repo")+ worktree := filepath.Join(base, "wt")++ writeTestFile(t, filepath.Join(mainRepo, ".git", "HEAD"), "ref: refs/heads/main\n")+ writeTestFile(t, filepath.Join(mainRepo, ".git", "config"), "[remote \"origin\"]\n\turl = [email protected]:asymptote-labs/agent-beacon.git\n")+ worktreeGitDir := filepath.Join(mainRepo, ".git", "worktrees", "wt")+ writeTestFile(t, filepath.Join(worktreeGitDir, "HEAD"), "ref: refs/heads/feature/wt-branch\n")+ writeTestFile(t, filepath.Join(worktreeGitDir, "commondir"), "../..\n")+ writeTestFile(t, filepath.Join(worktree, ".git"), "gitdir: "+worktreeGitDir+"\n")++ if got := CurrentBranch(worktree); got != "feature/wt-branch" {+ t.Fatalf("CurrentBranch = %q, want the worktree's own branch", got)+ }+ if got := CurrentBranch(mainRepo); got != "main" {+ t.Fatalf("CurrentBranch = %q, want the main checkout's branch", got)+ }+ // The commondir path used by GetRemoteInfo must keep working after the+ // shared pointer-parsing refactor.+ owner, name := GetRemoteInfo(worktree)+ if owner != "asymptote-labs" || name != "agent-beacon" {+ t.Fatalf("GetRemoteInfo = %q/%q, want asymptote-labs/agent-beacon", owner, name)+ }+}++func TestCurrentBranchWorktreeRelativeGitDirPointer(t *testing.T) {+ base := t.TempDir()+ mainRepo := filepath.Join(base, "main-repo")+ worktree := filepath.Join(base, "wt")++ worktreeGitDir := filepath.Join(mainRepo, ".git", "worktrees", "wt")+ writeTestFile(t, filepath.Join(worktreeGitDir, "HEAD"), "ref: refs/heads/relative-branch\n")+ writeTestFile(t, filepath.Join(worktree, ".git"), "gitdir: ../main-repo/.git/worktrees/wt\n")++ if got := CurrentBranch(worktree); got != "relative-branch" {+ t.Fatalf("CurrentBranch = %q, want relative-branch", got)+ }+}++func TestCurrentBranchRejectsMalformedHead(t *testing.T) {+ tests := []struct {+ name string+ head string+ }{+ {"empty", ""},+ {"non-branch ref", "ref: refs/remotes/origin/main\n"},+ {"missing name", "ref: refs/heads/\n"},+ {"embedded space", "ref: refs/heads/bad name\n"},+ {"control character", "ref: refs/heads/bad\x01name\n"},+ {"overlong name", "ref: refs/heads/" + strings.Repeat("a", 300) + "\n"},+ {"garbage", "not a head file\n"},+ {"oversized garbage", strings.Repeat("x", 2*maxGitMetadataBytes)},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ repo := t.TempDir()+ writeTestFile(t, filepath.Join(repo, ".git", "HEAD"), tt.head)+ if got := CurrentBranch(repo); got != "" {+ t.Fatalf("CurrentBranch = %q, want empty for %s HEAD", got, tt.name)+ }+ })+ }+}diff --git a/docs/runtimes/cursor.mdx b/docs/runtimes/cursor.mdxindex 29ee4576..fe34987e 100644--- a/docs/runtimes/cursor.mdx+++ b/docs/runtimes/cursor.mdx@@ -49,6 +49,7 @@ beacon endpoint hooks install --harness cursor --level project|------|---------|| Prompt telemetry | Supported for local Cursor through `beforeSubmitPrompt` hooks; not available in Cursor Cloud Agents because Cursor submits the prompt before the cloud VM exists. See [Cursor's Cloud Agent hook support matrix](https://cursor.com/docs/hooks#cloud-agent-support). || Command, tool, and file telemetry | Supported for tool, shell command, MCP-like, approval, and file edit payloads where Cursor exposes them; Cursor Cloud support is limited to Cursor's [cloud-supported command hooks](https://cursor.com/docs/hooks#cloud-agent-support). |+| Repository and branch context | Events include the workspace path as `repository`, and `branch` is resolved from the workspace's local git checkout (`.git/HEAD`) when Cursor does not supply one; disable local git resolution with `BEACON_DISABLE_GIT_METADATA=1` || Local JSONL and dashboard | Supported || MDM deployment | Supported for the endpoint agent; Cursor hooks are installed separately in the logged-in user's context |diff --git a/docs/security/data-inventory.mdx b/docs/security/data-inventory.mdxindex 6bda77b7..4c83a32b 100644--- a/docs/security/data-inventory.mdx+++ b/docs/security/data-inventory.mdx@@ -80,6 +80,8 @@ By default, snapshots include config-file metadata, MCP server metadata, skill mTop-level `model`, `repository`, `branch`, `message`, `raw`, and `field_truncated` fields can add shared context across entities. Content-bearing fields follow the configured retention mode.+For hook-based runtimes, `branch` is derived locally from the workspace's `.git/HEAD` file when the runtime payload does not provide one. This is a local file read only — no git command runs and nothing leaves the machine — and it can be disabled with `BEACON_DISABLE_GIT_METADATA=1`.+## Related<Columns cols={2}>diff --git a/docs/telemetry-schema/fields.mdx b/docs/telemetry-schema/fields.mdxindex 15c00f49..365f770d 100644--- a/docs/telemetry-schema/fields.mdx+++ b/docs/telemetry-schema/fields.mdx@@ -36,6 +36,8 @@ Beacon models each event as an action plus a set of typed entities. The [`event`Top-level `model`, `repository`, `branch`, `message`, `raw`, and `field_truncated` fields add shared context that can apply across multiple entities. For example, a command event can include both `tool` and `command`; a file edit can include `file`, `session`, `repository`, and `branch`; a CI event can include `origin` and `run`; and a GenAI tool call can include both `tool` and nested `gen_ai.tool` metadata.+For hook-based runtimes, when the runtime payload does not supply a branch, Beacon fills `branch` from the working directory's git checkout by reading `.git/HEAD` directly — no git binary is required, and the field is omitted when the directory is not a git repository or HEAD is detached. Set `BEACON_DISABLE_GIT_METADATA=1` (accepts `1`, `true`, or `yes`) in the runtime's environment to turn off local git metadata enrichment; runtime-provided branch values still pass through.+## GenAI contextWhen a runtime emits OpenTelemetry GenAI semantic convention attributes, Beacon preserves them under `gen_ai` while also projecting commonly queried values into top-level fields such as `model`, `tool.name`, or `prompt.text`.